Search completed in 1.37 seconds.
How to implement a custom autocomplete search component
The XUL textbox element supports an auto
complete mechanism that is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. There are actually two auto
complete mechanisms: An older mechanism that is part of the "xpfe" codebase and is used in older applications such as Thunderbird and SeaMonkey. A newer and slightly simplified mechanism that is used in "toolkit" applications such as Firefox and XULRunner. Thunderbird 2.x and SeaMonkey 1.1.x support the toolkit interfaces, although they do not use the same auto
complete widget. ...
...auto
complete mechanisms: An older mechanism that is part of the "xpfe" codebase and is used in older applications such as Thunderbird and SeaMonkey. A newer and slightly simplified mechanism that is used in "toolkit" applications such as Firefox and XULRunner. Thunderbird 2.x and SeaMonkey 1.1.x support the toolkit interfaces, although they do not use the same auto
complete widget. To use auto
complete with a XUL textbox, all you need to do is set some attributes: <textbox type="auto
complete" auto
completesearch="history"/> The type="auto
complete" turns on the auto
complete mechanism and the auto
completesearch="history" sets the source for the auto
complete. There are more options and features, see XUL:textbox_(Firefox_auto
complete) for more details. The toolkit mechanism has built-in support for...
...extbox, all you need to do is set some attributes: <textbox type="auto
complete" auto
completesearch="history"/> The type="auto
complete" turns on the auto
complete mechanism and the auto
completesearch="history" sets the source for the auto
complete. There are more options and features, see XUL:textbox_(Firefox_auto
complete) for more details. The toolkit mechanism has built-in support for several auto
complete sources, including: history: Search the browser's URL history (Firefox: 1.0+; SeaMonkey: 1.1+) form-history: Search the values that the user has entered into form fields. (Firefox: 1.0+; SeaMonkey: 2.0+) file: Search file names (Firefox: 2.0+; Thunderbird: 2.0+; SeaMonkey: 1.1+; GTK builds only). ...
...And 52 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
<< XUL Reference home [ Examples | Attributes | Properties | Methods | Related ] This element is created by setting the type attribute of a textbox to auto
complete. It is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. The auto
complete functionality is handled through one of more session objects, each of which can return a set of results given the current value of the textbox. The sessions can be set using the searchSessions attribute or by calling the addSession method. ...
...pup containing a list of possible completions for what the user has started to type. The auto
complete functionality is handled through one of more session objects, each of which can return a set of results given the current value of the textbox. The sessions can be set using the searchSessions attribute or by calling the addSession method. ...
...t of possible completions for what the user has started to type. The auto
complete functionality is handled through one of more session objects, each of which can return a set of results given the current value of the textbox. The sessions can be set using the searchSessions attribute or by calling the addSession method. ...
...And 42 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
<< XUL Reference home [ Examples | Attributes | Properties | Methods | Related ] This element is created by setting the type attribute of the textbox to auto
complete. It is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. Toolkit applications (such as Firefox) use a different auto
complete mechanism than the Mozilla suite. The example below will create an auto
complete textbox that will search the user's history. ...
...type attribute of the textbox to auto
complete. It is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. Toolkit applications (such as Firefox) use a different auto
complete mechanism than the Mozilla suite. The example below will create an auto
complete textbox that will search the user's history. ...
...he textbox to auto
complete. It is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. Toolkit applications (such as Firefox) use a different auto
complete mechanism than the Mozilla suite. The example below will create an auto
complete textbox that will search the user's history. ...
...And 27 more matches
nsIAutoCompleteInput
toolkit/components/auto
complete/public/nsIAuto
CompleteInput.idlScriptable This interface monitors the input in a text field and displays an auto
complete panel at the appropriate time. ...
...toolkit/components/auto
complete/public/nsIAuto
CompleteInput.idlScriptable This interface monitors the input in a text field and displays an auto
complete panel at the appropriate time. ...
... overview ACString getSearchAt(in unsigned long index); void onSearchBegin(); void onSearch
Complete(); boolean onTextEntered(); boolean onTextReverted(); void selectTextRange(in long startIndex, in long endIndex); Attributes Attribute Type Description
completeDefaultIndex boolean If a search result has its defaultIndex set, this will optionally try to
complete the text in the textbox to the entire text of the result at the default index as the user types. This means that auto-fill is enabled.
completeSelectedIndex boolean If true, the text in the text field will be auto
completed as the user selects from the popup...
...And 8 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
The HTML auto
complete attribute is available on <input> elements that take a text or numeric value as input, <textarea> elements, <select> elements, and <form> elements. auto
complete lets web developers specify what if any permission the user agent has to provide automated assistance in filling out form field values, as well as guidance to the browser as to the type of information expected in the field. The source of the suggested values is generally up to the browser; typically values come from past values entered by the user, but they may also come from pre-configured values. For instance, a browser might let the user save their name, address, phone number, and email addresses for auto
complete purposes. Perhaps the browser offers the ability to save encrypted credit card information, for autoc...
...entered by the user, but they may also come from pre-configured values. For instance, a browser might let the user save their name, address, phone number, and email addresses for auto
complete purposes. Perhaps the browser offers the ability to save encrypted credit card information, for autocompletion following an authentication procedure. If an <input>, <select> or <textarea> element has no auto
complete attribute, then browsers use the auto
complete attribute of the element's form owner, which is either the <form> element that the element is a descendant of, or the <form> whose id is specified by the form attribute of the element. For more information, see the auto
complete attribute in <form>. In order to provide autocompletion, user-agents might require <input>/<select>/<textarea> elements to...
...ute in <form>. In order to provide autocompletion, user-agents might require <input>/<select>/<textarea> elements to: Have a name and/or id attribute Be descendants of a <form> element The form to have a submit button Values "off" The browser is not permitted to automatically enter or select a value for this field. It is possible that the document or application provides its own auto
complete feature, or that security concerns require that the field's value not be automatically entered. Note: In most modern browsers, setting auto
complete to "off" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. See the auto
complete attribute and login fields. ...
...And 7 more matches
PaymentResponse.complete() - Web APIs
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. ...
...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. ...
...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. ...
...And 6 more matches
IDBTransaction.oncomplete - Web APIs
The on
complete event handler of the IDBTransaction interface handles the
complete event, fired when the transaction successfully
completes. As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702), which is the same behaviour as other IndexedDB-supporting browsers. Previously in a readwrite transaction IDBTransaction.on
complete was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the
complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. ...
...se performance (see bug 1112702), which is the same behaviour as other IndexedDB-supporting browsers. Previously in a readwrite transaction IDBTransaction.on
complete was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the
complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The
complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Note: This feature is available in Web Workers. Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed late...
...s a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Note: This feature is available in Web Workers. Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the
complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config. Syntax transaction.on
complete = function(event) { ... }; Example In the following code snippet, we open a read/write transaction on our database and ...
...And 5 more matches
HTMLImageElement.complete - Web APIs
The srcset attribute is absent and the src attribute, while specified, is the empty string (""). The image resource has been fully fetched and has been queued for rendering/compositing. The image element has previously determined that the image is fully available and ready for use. ...
... The srcset attribute is absent and the src attribute, while specified, is the empty string (""). The image resource has been fully fetched and has been queued for rendering/compositing. The image element has previously determined that the image is fully available and ready for use. ...
.... The image resource has been fully fetched and has been queued for rendering/compositing. The image element has previously determined that the image is fully available and ready for use. The image is "broken;" that is, the image failed to load due to an error or because image loading is disabled. It's worth noting that due to the image potentially being received asynchronously, the value of
complete may change while your script is running. Examples Consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. These photos may be very large, so you don't want to wait for them to load, so your code uses async/await to load the images in the background. But imagine that you have other code that needs to only r...
...And 4 more matches
Introducing a complete toolchain - Learn web development
ment environment and putting transformation tools in place to actually deploying your app on Netlify. In this article we'll introduce the case study, set up our development environment, and set up our code transformation tools. Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages. Objective: To solidify what we've learnt so far by working through a
complete toolchain case study. There really are unlimited combinations of tools and ways to use them, what you see in this article and the next is only one way that the featured tools can be used for a project. Note: It's also worth repeating that not all of these tools need to be run on the command line. Many of today's code editors (such as VS Code and Atom) have integration support for a lot o...
...hich were manually minified using SVGO before adding them to the project. A couple of prerequisites Besides the tools we're going to install that contribute to our toolchain, we mentioned two web services in the above list of tools. Let's take this opportunity to make sure we are set up with them before we continue. You will need to create accounts with each of GitHub and Netlify if you wish to
complete the tutorial. As mentioned previously, GitHub is a source code repository service that adds community features such as issue tracking, following project releases and much more. In the next chapter we will push to a GitHub code repository, which will cause a cascade effect that (should) deploy all the software to a home on the web. Netlify is a hosting service for static websites (that is, web...
...ay, setting up your development environment, if done well, needs doing only once and should be reusable in many future projects. You will probably want to review this part of the toolchain semi-regularly and consider if there's any upgrades or changes you should introduce, but this shouldn't be required too often. Your toolchain will depend on your own needs, but for this example of a (possible)
complete toolchain, the tools that will be installed up front will be: Library installation tools -- for adding dependencies. Code revision control. Code tidying tools -- for tidying JavaScript, CSS, and HTML. Code linting tools -- for linting our code. Library installation tools We'll use npm to install our tools, which you first met in Chapter 2. You should have Node.js and npm installed alread...
...And 3 more matches
nsIAutoCompleteObserver
void onSearchResult( in nsIAuto
CompleteSearch search, in nsIAuto
CompleteResult result ); Parameters search The search object that processed this search. result The search result object. onUpdateSearchResult() Called to update with new results. ...
...result The search result object. ...
...result The search result object. ...
...And 3 more matches
PerformanceNavigationTiming.domComplete - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
...And 3 more matches
autocompletesearch - Archive of obsolete content
mydomain New in Thunderbird 3 Requires SeaMonkey 2.0 The user's email domain is suggested. ...
...The components are created using the name @mozilla.org/auto
complete/search;1?name= where name is listed in this attribute. search-auto
complete Requires SeaMonkey 2.1 The user's default search engine's suggestions are searched. ...
... mydomain New in Thunderbird 3 Requires SeaMonkey 2.0 The user's email domain is suggested. ...
...And 2 more matches
nsIAutoCompleteListener
xpfe/components/auto
complete/public/nsIAuto
CompleteListener.idlScriptable This interface is deprecated. It only exists for legacy LDAP auto
complete session support. New code should use toolkit auto
complete interfaces. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onAuto
Complete(in nsIAuto
CompleteResults result, in Auto
CompleteStatus status); void onStatus(in wstring statusText); Attributes Attribute Type Description param nsISupports Private parameter used by the auto
complete widget. Methods onAuto
Complete() Called by the auto
complete session when the search is done or over. As of Gecko 1.9.1, can also be called with partial results, in a similar manner to the toolkit auto
complete interface. void onAuto
Complete( in nsIAuto
CompleteResult...
... onStatus() Called by the auto
complete session during the search. ...
... onStatus() Called by the auto
complete session during the search. This method does not seem to have ever been implemented. ...
...And 2 more matches
OfflineAudioContext: complete event - Web APIs
The
complete event of the OfflineAudioContext interface is fired when the rendering of an offline audio context is
complete. ...
... The
complete event of the OfflineAudioContext interface is fired when the rendering of an offline audio context is
complete. ...
... The
complete event of the OfflineAudioContext interface is fired when the rendering of an offline audio context is
complete. ...
...And 2 more matches
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. ...
... asyncOperationId must correspond to the operation ID previously returned from Debug.msTraceAsyncOperationStarting. ...
...NC_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. ...
...e app. function asyncWrapperFunction() { var opID = Debug.msTraceAsyncOperationStarting('async trace'); doSomethingAsync().then(function (result) { Debug.msTraceAsyncOperation
Completed(opID, Debug.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperation
Completed(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallback
Completed(); } 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...
IDBTransaction: complete event - Web APIs
The
complete handler is executed when a transaction successfully
completed. ...
... The
complete handler is executed when a transaction successfully
completed. ...
...eIndex('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'); // add a listener for `
complete` transaction.addEventListener('
complete', event => { console.log('Transaction was competed'); }); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; const objectStoreRequest = objectStore.add(newItem); }; Using the on
complete property: // Open the database const DBOpen...
...eIndex('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'); // add a listener for `
complete` transaction.on
complete = event => { console.log('Transaction was competed'); }; const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; const objectStoreRequest = objectStore.add(newItem); }; ...
Autocomplete - Archive of obsolete content
Turning auto
complete on for a XUL widget This article is about XUL widgets and not about HTML form inputs. First, declare a panel with the "auto
complete" type, like so: <panel id="popup_auto
complete" type="auto
complete" noautofocus="true" /> Now set the auto
completepopup attribute of your <browser> element to the id of the panel you just declared: <browser id="my_browser" ... auto
completepopup="popup_auto
complete" /> Finally, make sure that the value of the browser.formfill.enable pref is set to true. ...
...plete" type, like so: <panel id="popup_auto
complete" type="auto
complete" noautofocus="true" /> Now set the auto
completepopup attribute of your <browser> element to the id of the panel you just declared: <browser id="my_browser" ... auto
completepopup="popup_auto
complete" /> Finally, make sure that the value of the browser.formfill.enable pref is set to true. ...
..._auto
complete" type="auto
complete" noautofocus="true" /> Now set the auto
completepopup attribute of your <browser> element to the id of the panel you just declared: <browser id="my_browser" ... auto
completepopup="popup_auto
complete" /> Finally, make sure that the value of the browser.formfill.enable pref is set to true. ...
onMSVideoFrameStepCompleted - 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. onMSVideoFrameStep
Completed is an event which occurs when the video frame has been stepped forward or backward one frame. ...
... be large incompatibilities between implementations and the behavior may change in the future. onMSVideoFrameStep
Completed is an event which occurs when the video frame has been stepped forward or backward one frame. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
...ure. onMSVideoFrameStep
Completed is an event which occurs when the video frame has been stepped forward or backward one frame. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
Complete - Archive of obsolete content
ntroduction to extensions. However, because it is so simple it does not support some of the usual features of extensions. This page describes how to structure the extension in a more conventional way. This page is not a step-by-step tutorial. Instead it explains the missing features, and outlines how to add them. If you want to see these techniques in action, then you can download and install the
complete AllCustom extension: allcustom.xpi (The link is external only because this wiki does not support XPI files.) The extension does not contain any useful functions. It is just an extended code sample. To see the code, use a jar tool or zip tool to unpack the XPI file that you downloaded. For more information about developing extensions, see the main Extensions page here. Features of this extension ...
...registers SeaMonkey's skins in a seamonkey subdirectory. Firefox etc. use: skin/classic/allcustom/ This directory is specified in chrome.manifest, which only Firefox etc. use. SeaMonkey uses: skin/classic/allcustom/seamonkey/ This directory is specified in install.js, which only SeaMonkey uses. A similar structure is used for Modern, even though there is no conflict. Package structure Here is the
complete package structure for this extension. This diagram shows all the directories but only a few of the files. You can see all the files if you unpack the XPI and the jar. ...
nsIAutoCompleteSearch
Inherits from: nsISupports Last changed in Gecko 1.7 Users call startSearch() and pass in an nsIAuto
CompleteObserver 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 nsIAuto
CompleteResult previousResult, in nsIAuto
CompleteObserver listener); void stopSearch(); Methods startSearch() Search for a given string and notify a listener (either synchronously or asynchronously) of the result. ...
...n. Method overview void startSearch(in AString searchString, in AString searchParam, in nsIAuto
CompleteResult previousResult, in nsIAuto
CompleteObserver 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 nsIAuto
CompleteResult previousResult, in nsIAuto
CompleteObserver listener ); Parameters searchString The string to search for. searchParam An extra parameter. Can be empty if not needed. previousResult The previous nsIAuto
CompleteResult to use for faster searching. Can be null. listener An nsIAuto
CompleteObserver listener to notify when the search is
complete. stopSearch() Stop all searches that are in prog...
autocompletepopup - Archive of obsolete content
<< XUL Reference home auto
completepopup Type: id The id of a popup element used to hold auto
complete results for the element. Examples How to enable auto
complete (form fill) in a browser element. ...
disableautocomplete - Archive of obsolete content
<< XUL Reference home disableauto
complete New in Thunderbird 3Requires SeaMonkey 2.0 Type: boolean If true, the auto
complete behavior will be disabled. You might use a script to change this attribute. If false, the default, auto
complete is enabled. ...
forcecomplete - Archive of obsolete content
<< XUL Reference home force
complete New in Thunderbird 3Requires SeaMonkey 2.0 Type: boolean If true, the textbox will be filled in with the best match when it loses the focus. If false, it will only be filled in when the user selects an item. ...
textbox.disableAutocomplete - Archive of obsolete content
<< XUL Reference home disableAuto
complete Obsolete since Gecko 1.9.1 Type: boolean If true, the auto
complete behavior will be disabled. You might use a script to change this attribute. If false, the default, auto
complete is enabled. As of Gecko 1.9.1, this attribute is now always specified in lower case. ...
mozIPlacesAutoComplete
1.0 66 Introduced Gecko 1.9.2 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void registerOpenPage(in nsIURI aURI); void unregisterOpenPage(in nsIURI aURI); Constants Constant Value Description MATCH_ANYWHERE 0 Match anywhere in each searchable term. MATCH_BOUNDARY_ANYWHERE 1 Match first on word boundaries, and if we do not get enough results, then match anywhere in each searchable term. ...
nsIAutoCompleteItem
Inherits from: nsISupports Last changed in Gecko 1.7 Attributes Attribute Type Description className string Class name used to define some style through css like the colors, an icon url, and so on. comment wstring An extra comment that will be displayed next to the value but that will not be part of the value itself. param nsISupports Parameter use by the search engine. value AString The result value using AString to avoid excess allocations. ...
nsIAutoCompleteResult
toolkit/components/auto
complete/nsIAuto
CompleteResult.idlScriptable This interface is implemented by results of auto
complete search. Inherits from: nsISupports Last changed in Gecko 1.7 See nsIAuto
CompleteSearch ...
LockedFile.oncomplete - Web APIs
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. Summary Specifies an event listener to receive
complete events. These events occur each time a read or write operation is successful. Syntax instanceOfLockedFile.on
complete = funcRef; Where funcRef is a function to be called when the
complete event occurs. Specifications Specification Status Comment FileSystem API Editor's Draft Draft proposal. ...
OfflineAudioContext.oncomplete - Web APIs
The on
complete event handler of the OfflineAudioContext interface is called when the audio processing is terminated, that is when the
complete event (of type OfflineAudioCompletionEvent) is raised. Syntax var offlineAudioCtx = new OfflineAudioContext(); offlineAudioCtx.on
complete = function() { ... } Example When processing is
complete, you might want to use the on
complete handler the prompt the user that the audio can now be played, and enable the play button. offlineAudioCtx.on
complete = function() { console.log('Offline audio processing now
complete'); showModalDialog('Song processed and ready to play'); playBtn.disabled = false; } Specifications Specification Status Comment Web Audio APIThe definition of 'on
complete' in that specification. Working Dra...
PerformanceTiming.domComplete - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.dom
Complete read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, when the parser finished its work on the main document, that is when its Document.readyState changes to '
complete' and the corresponding readystatechange event is thrown. Syntax time = performanceTiming.dom
Complete; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.dom
Complete' in that specification. Recommendation Initial definition. ...
Index - Web APIs
ortController() API, AbortController, Constructor, Experimental, Fetch, Reference The AbortController() constructor creates a new AbortController object instance. 8 AbortController.abort() API, AbortController, Experimental, Fetch, Method, Reference, abort() The abort() method 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. 9 AbortController.signal API, AbortController, Experimental, Fetch, Property, Reference, signal 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. 10 AbortSig...
...ticatorAttestationResponse, Interface, Reference, Web Authentication API, WebAuthn The AuthenticatorAttestationResponse interface of the Web Authentication API is returned by CredentialsContainer.create() when a PublicKeyCredential is passed, and provides a cryptographic root of trust for the new key pair that has been generated. This response should be sent to the relying party's server to
complete the creation of the credential. 221 AuthenticatorAttestationResponse.attestationObject API, AuthenticatorAttestationResponse, Property, Reference, Web Authentication API, WebAuthn The attestationObject property of the AuthenticatorAttestationResponse interface returns an ArrayBuffer containing the new public key, as well as signature over the entire attestationObject with a p...
...g hardware timestamp in seconds that can be used for scheduling audio playback, visualizing timelines, etc. It starts at 0. 247 BaseAudioContext.decodeAudioData() API, Audio, AudioContext, BaseAudioContext, Method, Reference, Web Audio API, decodeAudioData 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. 248 BaseAudioContext.destination API, AudioContext, BaseAudioContext, Property, Reference, Web Audio API, destination An AudioDestinationNode. 249 BaseAudioContext.listener API, AudioContext, BaseAudioContext, Property, Reference, Web Audio API, listener, spatialization An AudioListener object. 250 B...
...And 58 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
ay. Finally, we will learn a bit more about components. So far, we've seen how components can share data using props, and communicate with their parents using events and two-way data binding. Now we will see how components can also expose methods and variables. The following new components will be developed throughout the course of this article: MoreActions: Displays the Check All and Remove
Completed buttons, and emits the corresponding events required to handle their functionality. NewTodo: Displays the <input> field and Add button for adding a new todo. TodosStatus: Displays the "x out of y items
completed" status heading. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to t...
...epts Or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts Remember to run npm install && npm run dev to start your app in development mode. ...
...ckle the Check All and Remove
Completed buttons. Let's create a component that will be in charge of displaying the buttons and emitting the corresponding events. Create a new file -- components/MoreActions.svelte. When the first 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 remove
Completed event to signal that all of the
completed todos should be removed. ...
...And 47 more matches
Index - Archive of obsolete content
ckage that contains the modules you want to use: 170 Bootstrapped extensions Add-ons, Extensions, Firefox 4, Gecko 2.0, Guide, Localization No summary! 171 Code snippets Add-ons, Code snippets, Extensions No summary! 172 Alerts and Notifications Code snippets non-modal notification and further interaction with users 173 Auto
complete Code snippets, Form Fill, Satchel No summary! 174 Bookmarks Code snippets, Developing Mozilla, Extensions, Places No summary! 175 Boxes Code snippets Make the BOX style="display: block" and the wrapping behavior will occur when the box is resized: 176 Canvas code snippets Canvas, Code snippets, Graphics No summary! 17...
...t distributable to other users. The two ways of doing that are to integrate it into the Mozilla codebase (in which case it is no longer an extension but rather part of the default Mozilla distribution) and to package it into an installer that users can run from within Mozilla to add the extension to their Mozilla installation. 396 Prerequisites Add-ons, Extensions In order to
complete this tutorial you need to have and know how to use the following programs on your computer: 397 Specifying the appearance Add-ons, Extensions Now that we have defined a panel in which to display an icon, we use CSS to specify which icon to display. For this we have to first create four icons, one for each tinderbox state (none, success, test failed, and busted), then create a...
...t_packs I hesitate to call it "original", tho, because I've basically rewritten the entire thing so that it's easier and faster to use to create Help content. The previous document had a lot of places where ideas were simply introduced without explanation, and I've tried to go through things a bit more slowly with better descriptions. This is still very much a work in progress, tho, and I need to
complete the rest of it soon (where "
complete" means "use what's there that's good, build on the stuff that's not as good, and add other useful information as necessary". 485 Helper Apps (and a bit of Save As) Outdated_articles, Uriloader 486 Hidden prefs This page has been flagged by editors or users as needing technical review. Until it is fully reviewed, it ...
...And 27 more matches
TypeScript support in Svelte - Learn web development
d that you are familiar with the core HTML, CSS, and JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn how to configure and use TypeScript when developing Svelte applications. Note that our application is fully functional and porting it to TypeScript is
completely optional. There are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using TypeScript. Even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at diff...
...ypeScript transpiles many recent ES6 features to plain old-school JavaScript, allowing you to use them even on user-agents that don't support them natively yet. TypeScript also has some disadvantages: Not true static typing: Types are only checked at compile time, and they are removed from the generated code. Steep learning curve: Even though TypeScript is a superset of JavaScript and not a
completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like Java or C#. More code: You have to write and maintain more code. No replacement for automatic tests: Even though types might help you catch several bugs, TypeScript is not a true replacement for a comprehensive suite of automated tests. Boiler plate code: Working with ...
...ively, you can download the setupTypeScript.js file to a scripts folder inside your project's root folder, and then run node scripts/setupTypeScript.js. You can even use degit to download the script. That's what we will do to start porting our application to TypeScript. Note: Remember that you can run npx degit opensas/mdn-svelte-tutorial/07-typescript-support svelte-todo-typescript to get the
complete to-do list application in JavaScript before you start porting it to TypeScript. Go to the root directory of the project and enter these commands: npx degit sveltejs/template/scripts scripts # download script file to a scripts folder node scripts/setupTypeScript.js # run it Converted to TypeScript. You will need to re-run your dependency manager to get started. npm in...
...And 26 more matches
React interactivity: Events and state - Learn web development
Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line. ...
... Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line. ...
...State() returns these two things, so we are using array destructuring to capture them both in separate variables. Reading state You can see the name state in action right away. Add a value attribute to the form's input, and set its value to name. Your browser will render "Use hooks!" inside the input. <input type="text" id="new-todo-input" className="input input__lg" name="text" auto
Complete="off" value={name} /> Change "Use hooks!" to an empty string once you're done; this is what we want for our initial state. const [name, setName] = useState(''); Reading user input Before we can change the value of name, we need to capture a user's input as they type. For this, we can listen to the onChange event. Let's write a handleChange() function, and listen for it on the <input /> tag.
...And 20 more matches
Componentizing our Svelte app - Learn web development
nents. Both approaches should complement each other, and help you decide how to better organize your components. Eventually, we will split up our app into the following components: Alert.svelte: A general notification box for communicating actions that have occurred. NewTodo.svelte: The text input and button that allow you to enter a new todo item. FilterButton.svelte: The All, Active, and
Completed buttons that allow you to apply filters to the displayed todo items. TodosStatus.svelte: The "x out of y items
completed" heading. Todo.svelte: An individual todo item. Each visible todo item will be displayed in a separate copy of this component. MoreActions.svelte: The Check All and Remove
Completed buttons at the bottom of the UI that allow you to perform mass actions on the todo items. ...
...First of all, we need to import it -- add the following line at the top of the Todos.sv...
...First of all, we need to import it -- add the following line at the top of the Todos.svelte <script> section: import Filte...
...And 20 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
Previous Overview: Client-side JavaScript frameworks Next Now that we have our markup and styles ready we can start developing the required features for our Svelte To-Do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete todos, mark them as
complete, and filter them by status. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn and put into practice some basic Svelte concepts, like creating components, passing data using props, render JavaScript expressions into our mar...
...h us using the REPL, start at https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2 Working with todos Our Todos.svelte component is currently just displaying static markup; let's start making it a bit more dynamic. We'll take the tasks information from the markup and store it in a todos array. ...
...tore it in a todos array. We'll also create two variables to keep track of the total number of tasks and the
completed tasks. The state of our component will be represented by these three top-level variables. Create a <script> section at the top of src/components/Todos.svelte and give it some content, as follows: <script> let todos = [ { id: 1, name: 'Create a Svelte starter app',
completed: true }, { id: 2, name: 'Create your first component',
completed: true }, { id: 3, name: '
Complete the rest of the tutorial',
completed: false } ] let totalTodos = todos.length let
completedTodos = todos.filter(todo => todo.
completed).length </script> Now let's do something with that information. Let's start by showing a status message. Find the <h2> heading with an id of...
...And 20 more matches
Index
178 amIInstallTrigger Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference Retained for backwards compatibility. 179 amIWebInstallInfo Add-on Manager, Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference Starts all installs. 180 amIWebInstallListener Interfaces, Interfaces:Scriptable, XPCOM, XPCOM In...
...etween "load" and "decode" notifications. Load notifications are fired as the image is loaded from the network or filesystem. Decode notifications are fired as the image is decoded. If an image is decoded on load and not visibly discarded, decode notifications are nested logically inside load notifications as one might expect. However, with decode-on-draw, the set of decode notifications can come
completely after the load notifications, and can come multiple times if the image is discardable. Moreover, they can be interleaved in various ways. In general, any presumed ordering between load and decode notifications should not be relied upon. 188 imgIEncoder Interfaces, Interfaces:Scriptable, NeedsHelp, XPCOM, XPCOM Interface Reference Possible values for input format (note that ...
...OM Interface Reference Implemented by: @mozilla.org/moz/jssubscript-loader;1. To get this service, use: 197 mozIPersonalDictionary Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference Implemented by: @mozilla.org/spellchecker/personaldictionary;1. To access this service, use 198 mozIPlaceInfo No summary! 199 mozIPlacesAuto
Complete Interfaces, Interfaces:Scriptable, Places, XPCOM, XPCOM Interface Reference Mark a page as being currently open. 200 mozIRegistry Outdated_articles Clients will rely on nsRepository to create instances of a given class. Clients requiring dynamic "binding" of CLSIDs will be required to use some higher-level services (TBD) to figure out the CLSIDs they should use. The...
...And 17 more matches
Index - Learn web development
2 Accessibility ARIA, Accessibility, Articles, Beginner, CSS, CodingScripting, HTML, JavaScript, Landing, Learn, Module Learning some HTML, CSS, and JavaScript is useful if you want to become a web developer. ...
...derstand these concepts before working through the other articles in the module. 53 Graceful asynchronous programming with Promises Beginner, CodingScripting, Guide, JavaScript, Learn, Promises, async, asynchronous, catch, finally, then Promises are a comparatively new feature of the JavaScript language that allow you to defer further actions until after a previous action has
completed, or respond to its failure. 54 Introducing asynchronous JavaScript Beginner, CodingScripting, Guide, Introducing, JavaScript, Learn, Promises, async, asynchronous, await, callbacks In this article we briefly recap the problems associated with synchronous JavaScript, and take a first look at some of the different asynchronous techniques you'll encounter, showing how they can ...
...variables, strings, numbers and arrays. 76 A first splash into JavaScript Article, Beginner, CodingScripting, Conditionals, Functions, JavaScript, Learn, Objects, Operators, Variables, events, l10n:priority Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a
completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step. 77 Arrays Arrays, Article, Beginner, CodingScripting, JavaScript, Join, Learn, Pop, Push, l10n:priority, shift, split, unshift In the final article of this module, we'll look at arrays -- a neat way of storing a list of data items under a single variable name. Here we look at why this i...
...And 15 more matches
Index - Archive of obsolete content
background XUL Attributes, XUL Reference No summary! 17 alwaysopenpopup XUL Attributes, XUL Reference No summary! 18 attribute XUL Attributes, XUL Reference No summary! 19 autoFillAfterMatch XUL Attributes, XUL Reference No summary! 20 autocheck XUL Attributes, XUL Reference No summary! 21 auto
completeenabled XUL Attributes, XUL Reference No summary! 22 auto
completepopup XUL Attributes, XUL Reference No summary! 23 auto
completesearch XUL Attributes, XUL Reference No summary! 24 auto
completesearchparam XUL Attributes, XUL Reference No summary! 25 autofill XUL Attributes, XUL Reference No summary! ...
...ary! 63 color XUL Attributes, XUL Reference No summary! 64 colorpicker.type XUL Attributes, XUL Reference No summary! 65 cols XUL Attributes, XUL Reference No summary! 66 command XUL Attributes, XUL Reference No summary! 67 commandupdater XUL Attributes, XUL Reference No summary! 68
completedefaultindex XUL Attributes, XUL Reference No summary! 69
completeselectedindex No summary! 70 container XUL Attributes, XUL Reference No summary! 71 containment XUL Attributes, XUL Reference No summary! 72 contentcontextmenu XUL Attributes, XUL Reference No summary! 73 contenttooltip XUL ...
...aultButton XUL Attributes, XUL Reference No summary! 90 defaultset XUL Attributes, XUL Reference No summary! 91 description XUL Attributes, XUL Reference No summary! 92 dir XUL Attributes, XUL Reference No summary! 93 disableKeyNavigation XUL Attributes, XUL Reference No summary! 94 disableauto
complete XUL Attributes, XUL Reference No summary! 95 disableautoselect XUL Attributes, XUL Reference No summary! 96 disablechrome XUL, XUL Attribute, XUL Reference No summary! 97 disableclose XUL Attributes, XUL Reference No summary! 98 disabled XUL Attributes, XUL Reference No summary! 99 disablefast...
...And 13 more matches
Routing in Ember - Learn web development
Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and JavaScript languages, and have knowledge of the terminal/command line. ...
... the URL so that if (for any reason), the page needs to refresh, the user isn't surprised by the state of the web app -- they can link directly to significant views of the app. At the moment, we already have the "All" page, as we are currently not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "Active" and "
Completed" todos. An Ember application has a default "application" route, which is tied to the app/templates/application.hbs template. Because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing. Creating the routes Let's start by creating three new routes: "Index", "Active" and "
Completed". To do this you'll need to enter the following com...
...hbs template. Because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing. Creating the routes Let's start by creating three new routes: "Index", "Active" and "
Completed". To do this you'll need to enter the following commands into your terminal, inside the root directory of your app: ember generate route index ember generate route
completed ember generate 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; } Ro...
...And 13 more matches
Mozilla's Section 508 Compliance
Windows Linux/UNIX Mac OS Requirement Windows Linux/UNIX Mac OS (a) When software is designed to run on a system that has a keyboard, product functions shall be executable from a keyboard where the function itself or the result of performing a function can be discerned textually. Mostly
complete. Caveats: 1) Although sidebar cannot be customized without a mouse, all sidebar functions that come with the browser are available through other means 2) Java and in-page plugins cannot be used with the keyboard, so they must not be installed for keyboard-only users Additional features for the keyboard: 1) Find as you type allows for quick navigation to l...
...s cannot be used with the keyboard, so they must not be installed for keyboard-only users Additional features for the keyboard: 1) Find as you type allows for quick navigation to links and convenient text searching 2) Browse with caret (F7 key toggles) allows users to select arbitrary content with the keyboard and move through content as if inside a readonly editor. In
complete. Inadequate attention paid to Mac keyboard bugs. Needs more investigation. (b) Applications shall not disrupt or disable activated features of other products that are identified as accessibility features, where those features are developed and documented according to industry standards. Applications also shall not disrupt or disable activated features of any operating system...
... features are developed and documented according to industry standards. Applications also shall not disrupt or disable activated features of any operating system that are identified as accessibility features where the application programming interface for those accessibility features has been documented by the manufacturer of the operating system and is available to the product developer.
Complete. (c) A well-defined on-screen indication of the current focus shall be provided that moves among interactive interface elements as the input focus changes. The focus shall be programmatically exposed so that assistive technology can track focus and focus changes.
Complete. We expose focus programmatically via MSAA (Windows) and ATK (Linux/UNIX). In
complete, w...
...And 13 more matches
passwords - Archive of obsolete content
n brackets after the URL. So: if a web server at http://www.example.com requested authentication with a response code like this: HTTP/1.0 401 Authorization Required Server: Apache/1.3.27 WWW-Authenticate: Basic realm="ExampleCo Login" The corresponding values for the credential (excluding username and password) should be: url: "http://www.example.com" realm: "ExampleCo Login" on
Complete and onError This API is explicitly asynchronous, so all its functions take two callback functions as additional options: on
Complete and onError. on
Complete is called when the operation has
completed successfully and onError is called when the function encounters an error. Because the search function is expected to return a list of matching credentials, its on
Complete option is mandatory. Becau...
... take two callback functions as additional options: on
Complete and onError. on
Complete is called when the operation has
completed successfully and onError is called when the function encounters an error. Because the search function is expected to return a list of matching credentials, its on
Complete option is mandatory. Because the other functions don't return a value in case of success their on
Complete options are optional. For all functions, onError is optional. Globals Functions search(options) This function is used to retrieve a credential, or a list of credentials, stored in the Password Manager. You pass it any subset of the possible properties a credential can contain. Credentials which match all the properties you supplied are returned as an argument to the on
Complete callback. So...
...ist 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 on
Complete callback. ...
...And 12 more matches
sslfnc.html
unctions This chapter describes the core SSL functions. SSL Initialization Functions SSL Export Policy Functions SSL Configuration Functions SSL Communication Functions SSL Functions Used by Callbacks SSL Handshake Functions NSS Shutdown Function Deprecated Functions SSL Initialization Functions This section describes the initialization functions that are specific to SSL. For a
complete list of NSS initialization functions, see Initialization. Note that at least one of the functions listed in SSL Export Policy Functions must also be called during NSS initialization. NSS_Init NSS_InitReadWrite NSS_NoDB_Init SSL_OptionSetDefault SSL_OptionGetDefault SSL_CipherPrefSetDefault SSL_CipherPrefGetDefault SSL_ClearSessionCache SSL_ConfigServerSessionIDCache SSL_ConfigMPServe...
...a particular socket: Enabling the SSL_REQUIRE_CERTIFICATE option is not recommended. If the client has no certificate and this option is enabled, the client's connection terminates with an error. The user is likely to think something is wrong with either the client or the server, and is unlikely to realize that the problem is the lack of a certificate. It is better to allow the SSL handshake to
complete and then have your application return an error message to the client that informs the user of the need for a certificate. As mentioned in Communication, when an application imports a socket into SSL after the TCP connection on that socket has already been established, it must call SSL_ResetHandshake to determine whether the socket is for a client or server. At first glance this may seem unnec...
...y, since SSL_Enable can set SSL_HANDSHAKE_AS_CLIENT or SSL_HANDSHAKE_AS_SERVER. However, these settings control the behavior of PR_Connect and PR_Accept only; if you don't call one of those functions after importing a non-SSL socket with SSL_Import (as in the case of an already established TCP connection), SSL still needs to know whether the application is functioning as a client or server. For a
complete discussion of the use of SSL_HANDSHAKE_AS_CLIENT and SSL_HANDSHAKE_AS_SERVER with SSL_EnableDefault and SSL_Enable, see SSL_OptionSet. The SSL protocol is defined to be able to handle simultaneous two-way communication between applications at each end of an SSL connection. Two-way simultaneous communication is also known as "Full Duplex", abbreviated FDX. However, most application protocols tha...
...And 12 more matches
OS.File for the main thread
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 text "This is some text" to a string "file.txt", using the default encoding (utf-8). It uses an atomic write to ensu...
... 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 text "This is some text" to a string "file.txt", using the default encoding (utf-8). ...
...pos, chunkSize)); // Write a subset of |data| return promise.then(function onSuccess(bytes) { return loop(pos + bytes); // ... and loop. }); }; let promise = loop(0); // Enter the loop. promise = promise.then(function onSuccess() { // Once loop is
complete, finalize. file.close(); }, function onError(reason) { file.close(); throw reason; }); return promise; } Or a variant using Task.js (or at least the subset already present on mozilla-central): let writeStream = function writeStream(data, outFile, chunkSize) { return Task.spawn(function() { let view = new Uint8Array(data); let pos = 0; while (pos < view.byteLengt...
...And 11 more matches
L10n Checks
hon setup.py install Running it Mercurial source (source) mode L10n Checks gathers the directories to compare from an ini file, usually found in $APP/locales/l10n.ini. You pass both the path to the ini file and the parent directory of the localizations as first arguments, followed by the locale codes of the locales you want to compare. ...
.... If you want to test the localization for de, run: check-l10n-
completeness browser/locales/l10n.ini ../l10n/ de Add-ons (xpi) mode L10n Checks gathers the locales to compare from the chrome.manifest file inside the xpi file. You pass the path to the xpi file (optionally) followed by the locale codes of the locales you want to compare. If you want to test the localization for de, run: check-l10n-
completeness -i xpi my-extension.xpi de To check all locales in an extension: check-l10n-
completeness -i xpi my-extension.xpi Language packs (xpis) mode L10n Checks can compare two locales found in different xpi files. ...
...want to compare. If you want to test the localization for de, run: check-l10n-
completeness -i xpi my-extension.xpi de To check all locales in an extension: check-l10n-
completeness -i xpi my-extension.xpi Language packs (xpis) mode L10n Checks can compare two locales found in different xpi files. You pass both paths to the xpi file and both paths to the locales inside the files, e.g.: check-l10n-
completeness -i xpis en-US-langpack.xpi my-langpack.xpi jar:chrome/en-US.jar!locale/ jar:chrome/my.jar!locale/my/ Jar/Zip File (jar) mode L10n Checks can compare two locales found in different jar files. ...
...And 11 more matches
How to turn off form autocompletion - Web security
By default, browsers remember information that the user submits through <input> fields on websites. This enables the browser to offer autocompletion (that is, suggest possible completions for fields that the user has started typing in) or autofill (that is, pre-populate certain fields upon load). These features are usually enabled by default, but they can be a privacy concern for users, so browsers can let users disable them. However, some data submitted in forms either are not useful in the future (for example, a one-time pin) or contain sensitive information (for example, a unique government identifier or credit card security code). ...
...privacy concern for users, so browsers can let users disable them. However, some data submitted in forms either are not useful in the future (for example, a one-time pin) or contain sensitive information (for example, a unique government identifier or credit card security code). ...
...in the future (for example, a one-time pin) or contain sensitive information (for example, a unique government identifier or credit card security code). As website author, you might prefer that the browser not remember the values for such fields, even if the browser's auto
complete feature is enabled. Note that the WCAG 2.1 Success Criterion 1.3.5: Identify Input Purpose does not require that auto
complete/autofill actually work - merely that form fields that relate to specific personal user information are programmatically identified. This means that the criterion can be passed (by adding the relevant auto
complete attributes to individual form fields) even when autocompletion for the form itself has been turned off. Disabling autocompletion To disable autocompletion in forms, you can set the aut...
...And 11 more matches
Table Reflow Internals - Archive of obsolete content
to be given no size constraints. desired size - the size it would like to be given the avail size. This is equivalent to preferred size if the avail size is not constrained. Review of Reflow The reflowee sets various sizes in the reflow metrics after (possibly) reflowing some or all of its children which reflows it children, etc. The reflowee returns a reflow status which indicates if it is
complete, and thus not have to continue (split) breaking status (in the case of some inline frames) if there is truncation (it can't fit in the space and can't split). This is just a convience mechanism. Kinds of reflows Initial - reflowee's first reflow must be of this type (reflower's responsibility). Resize - reflowee gets a change in available space only. Similar to initial, except it can reoccur.
...3rd pass could also be inside a cell which is an observer Special height reflow Optimizations only frames needing 3rd pass actually get it frames gettting a 3rd pass only get it once Intro to paginated reflow When a reflowee's available height is constrained, it may not fit and need to either split/continue on the next page, or start on the next page. If it can continue, it returns an in
complete status. If it can't continue it returns a
complete status. A continuation may also need to be continued Continuations are linked together by prevInFlow and nextInFlow pointers Pagination Illustration nsSimplePageSequence nsPageFrame nsPageContentFrame areaFrame (html) blockFrame (body) nsTableOuterFrame nsTableOute...
...ence nsPageFrame nsPageContentFrame areaFrame (html) blockFrame (body) nsTableOuterFrame nsTableOuterFrame blockFrame (body) areaFrame (html) nsPageContentFrame continued nsPageFrame continued Intro to paginated reflow The page sequence starts with one page and reflows it. ...
...And 10 more matches
Client-side storage - Learn web development
long time. Since the early days of the web, sites have used cookies to store information to personalize user experience on websites. They're the earliest form of client-side storage commonly used on the web. These days, there are easier mechanisms available for storing client-side data, therefore we won't be teaching you how to use cookies in this article. However, this does not mean cookies are
completely useless on the modern-day web -- they are still used commonly to store data related to user personalization and state, e.g. session IDs and access tokens. For more information on cookies see our Using HTTP cookies article. New school: Web Storage and IndexedDB The "easier" features we mentioned above are as follows: The Web Storage API provides a very simple syntax for storing and retrievi...
...s we mentioned above are as follows: The Web Storage API provides a very simple syntax for storing and retrieving smaller, data items consisting of a name and a corresponding value. This is useful when you just need to store some simple data, like the user's name, whether they are logged in, what color to use for the background of the screen, etc. The IndexedDB API provides the browser with a
complete database system for storing complex data. This can be used for things from
complete sets of customer records to even complex data types like audio or video files. You'll learn more about these APIs below. The future: Cache API Some modern browsers support the new Cache API. This API is designed for storing HTTP responses to specific requests, and is very useful for doing things like storing w...
...re is another, slightly more complex example to explore at Using the Web Storage API. Note: In the line <script src="index.js" defer></script> of the source for our finished version, the defer attribute specifies that the contents of the <script> element will not execute until the page has finished loading. Storing complex data -- IndexedDB The IndexedDB API (sometimes abbreviated IDB) is a
complete database system available in the browser in which you can store complex related data, the types of which aren't limited to simple values like strings or numbers. You can store videos, images, and pretty much anything else in an IndexedDB instance. However, this does come at a cost: IndexedDB is much more complex to use than the Web Storage API. In this section, we'll really only scratch the surf...
...And 10 more matches
Componentizing our React app - Learn web development
an> </button> <button type="button" className="btn btn__danger"> Delete <span className="visually-hidden">Eat</span> </button> </div> </li> ); } Note: Components must always return something. If at any point in the future you try to render a component that does not return anything, React will display an error in your browser. Our Todo component is
complete, at least for now; now we can use it. In App.js, add the following line near the top of the file to import Todo: import Todo from "./components/Todo"; With this component imported, you can replace all of the <li> elements in App.js with <Todo /> component calls. Your <ul> should read like this: <ul role="list" className="todo-list stack-large stack-exception" aria-labelledby="list-headin...
...ent calls render unique content. Make a unique <Todo /> Components are powerful because they let us re-use pieces of our UI, and refer to one place for the source of that UI. The problem is, we don't typically want to reuse all of each component; we want to reuse most parts, and change small pieces. This is where props come in. What's in a name? In order to track the names of tasks we want to
complete, we should ensure that each <Todo /> component 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 ...
...btn"> Edit <span className="visually-hidden">{props.name}</span> </button> <button type="button" className="btn btn__danger"> Delete <span className="visually-hidden">{props.name}</span> </button> </div> </li> ); } Now your browser should show three unique tasks. Another problem remains though: they're all still checked by default. ...
...And 10 more matches
Using IndexedDB - Web APIs
es of objects used by IndexedDB, as well as the methods of the asynchronous API (the synchronous API was removed from spec). Basic pattern The basic pattern that IndexedDB encourages is the following: Open a database. Create an object store in the database. Start a transaction and make a request to do some database operation, like adding or retrieving data. Wait for the operation to
complete by listening to the right kind of DOM event. Do something with the results (which can be found on the request object). With these big concepts under our belts, we can get to more concrete stuff. Creating and structuring the store Using an experimental version of IndexedDB In case you want to test your code in browsers that still use a prefix, you can use the following code: // In ...
...Therefore, it is not recommended to use it in production code. It may be preferable to not support a browser than to claim to support it and fail: if (!window.indexedDB) { console.log("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available."); } Opening a database We start the whole process...
... // Create an index to search customers by name. We may have duplicates // so we can't use a unique index. objectStore.createIndex("name", "name", { unique: false }); // Create an index to search customers by email. We want to ensure that // no two customers have the same email, so use a unique index. objectStore.createIndex("email", "email", { unique: true }); // Use transaction on
complete to make sure the objectStore creation is // finished before adding data into it. objectStore.transaction.on
complete = function(event) { // Store values in the newly created objectStore. var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers"); customerData.forEach(function(customer) { customerObjectStore.add(customer); }); }; }; As ...
...And 10 more matches
Event reference
traversed from. pageshow A session history entry is being traversed to. popstate A session history entry is being navigated to (in certain cases). CSS Animation events Event Name Fired When animationstart A CSS animation has started. animationcancel A CSS animation has aborted. animationend A CSS animation has
completed. animationiteration A CSS animation is repeated. CSS Transition events Event Name Fired When transitionstart A CSS transition has actually started (fired after any delay). transitioncancel A CSS transition has been cancelled. transitionend A CSS transition has
completed. transitionrun A CSS transition has beg...
...ext Composition events Event Name Fired When compositionstart The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition). compositionupdate A character is added to a passage of text being composed. compositionend The composition of a passage of text has been
completed or canceled. View events Event Name Fired When fullscreenchange An element was toggled to or from fullscreen mode. fullscreenerror It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied. resize The document view has been resized. scroll The document view or an element ha...
...ss The input buffer of a ScriptProcessorNode is ready to be processed. canplay The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. canplaythrough 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. ...
...And 10 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
We'll look at conditional UI rendering along the way. ...
...We'll look at conditional UI rendering along the way. ...
...We're going to do some refactoring. A UI for editing In order to allow users to edit a task, we have to provide a user interface for them to do so. First, import useState into the Todo component like we did before with the App componen...
...And 8 more matches
IDBTransaction - Web APIs
ncaught exception in the request's success/error handler. An I/O error (e.g. an actual failure to write to disk, or other OS/hardware failure). Quota exceeded. A user agent crash. ...
...te to disk, or other OS/hardware failure). Quota exceeded. A user agent crash. Firefox durability guarantees Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702.) Previously in a readwrite transaction IDBTransaction.on
complete was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the
complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The
complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, m...
... transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further. If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the
complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction. Properties IDBTransaction.db Read only The database connection with which this transaction is associated. IDBTransaction.error Read only Returns a DOMException indicating the type of error that occured when there is an unsuccessful transaction. This property is null if ...
...And 7 more matches
PaymentRequest.show() - Web APIs
to return one; this object contains the fields in the PaymentResponse which have been or need to be changed. ...
...aymentResponse which have been or need to be changed. ...
... I...
...And 7 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
n ordered collection of data (either primitive or object depending upon the language). Arrays are used to store multiple values in a single variable. This is compared to a variable that can store only one value. 24 Asynchronous Glossary, Web, WebMechanics, asynchronous The term asynchronous refers to or multiple related things happening without waiting for the previous one to
complete). 25 Attribute CodingScripting, Glossary, HTML An attribute extends an element, changing its behavior or providing metadata. 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-...
...) to keep track of its place in a script that calls multiple functions -- what function is currently being run and what functions are called from within that function, etc. 63 Callback function Callback, Callback function, CodingScripting, Glossary A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to
complete some kind of routine or action. 64 Canonical order Canonical order, CodingScripting, Glossary In CSS, canonical order is used to refer to the order in which separate values need to be specified (or parsed) or are to be serialized as part of a CSS property value. It is defined by the formal syntax of the property and normally refers to the order in which longhand values should...
...ate (e.g., Mozilla Corporation) is authorized to request a certificate for the subject named in the certificate (e.g., mozilla.org). 69 Certified Apps, B2G, Firefox OS, Glossary, Security, Trustworthy Certified means that an application, content or data transmission has successfully undergone evaluation by professionals with expertise in the relevant field, thereby indicating
completeness, security and trustworthiness. 70 Challenge-response authentication Security In security protocols, a challenge is some data sent to the client by the server in order to generate a different response each time. Challenge-response protocols are one way to fight against replay attacks where an attacker listens to the previous messages and resends them at a later time to get...
...And 6 more matches
Graceful asynchronous programming with Promises - Learn web development
This is useful for setting up a sequence of async operations to work correctly. This article shows you how promises work, how you'll see them in use with web APIs, and how to write your own. Prerequisites: Basic computer literacy, a reasonable understanding of JavaScript fundamentals. Objective: To understand promises and how to use them. ...
...to use them. What are promises? We looked at Promises briefly in the first article of the course, but here we'll look at them in a lot more depth. Essentially, a Promise is an object that represents an intermediate state of an operation -- in effect, a promise that a result of some kind will be returned at some point in the future. There is no guarantee of exactly when the operation will
complete and the result will be returned, but there is a guarantee that when the result is available, or the promise fails, the code you provide will be executed in order to do something else with a successful result, or to gracefully handle a failure case. Generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!)...
...allButton() function has already returned to the code that called it, when getUserMedia() has finished working, it calls the handler you provide. As long as the app doesn't assume that streaming has begun, it can just keep on running. Note: You can learn more about this somewhat advanced topic, if you're interested, in the article Signaling and video calling. Code similar to this, but much more
complete, is used in that example. The trouble with callbacks To fully understand why promises are a good thing, it helps to think back to old-style callbacks and to appreciate why they are problematic. Let's talk about ordering pizza as an analogy. There are certain steps that you have to take for your order to be successful, which doesn't really make sense to try to execute out of order, or in order...
...And 6 more matches
Starting our Svelte Todo list app - Learn web development
ample app: a todo list. In this article we will first have a look at the desired functionality of our app, then we'll create a Todos.svelte component and put static markup and styles in place, leaving everything ready to start developing our To-Do list app features, which we'll go on to in subsequent articles. We want our users to be able to browse, add and delete tasks, and also to mark them as
complete. This will be the basic functionality that we'll be developing in this tutorial series, plus we'll look at some more advanced concepts along the way too. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to com...
...-starting-our-todo-app Remember to run npm install && npm run dev to start your app in development mode. REPL To code along with us using the REPL, start at https://svelte.dev/repl/b7b831ea3a354d3789cefbc31e2ca495?version=3.23.2 Todo list app features This is how our Todo list app wil look like once it's ready: Using this UI our user will be able to: Browse their tasks. Mark tasks as
completed/pending without deleting them. Remove tasks. Add new tasks. Filter tasks by status: all tasks, active tasks, or
completed tasks. Edit tasks. Mark all tasks as active/
completed. Remove all
completed tasks. Building our first component Let's create a Todos.svelte component -- this will contain our list of todos. Create a new folder -- src/components. Note: you can put your com...
...app, so you can see what it will look like. ...
...And 6 more matches
Working with Svelte stores - Learn web development
In this article we will show another way to handle state management in Svelte -- Stores. Stores are global global data repositories that hold values. Components can subscribe to stores and receive notifications when their values change. ...
...ng less error-prone code. Writing to our store Writing to our store is just a matter of importing it and executing $store = 'new value'. Let's use it in our Todos component. ...
... t.id !== todo.id) todosStatus.focus() // give focus to status heading $alert = `Todo '${todo.name}' has been deleted` } Update the updateTodo() function to this: function updateTodo(todo) { const i = todos.findIndex(t => t.id === todo.id) if (todos[i].name !== todo.name) $alert = `todo '${todos[i].name}' has been renamed to '${todo.name}'` if (todos[i].
completed !== todo.
completed) $alert = `todo '${todos[i].name}' marked as ${todo.
completed ? '
completed' : 'active'}` todos[i] = { ...todos[i], ...todo } } Add the following reactive block beneath the block that starts with let filter = 'all': $: { if (filter === 'all') $alert = 'Browsing all todos' else if (filter === 'active') $alert = 'Browsing active todos' else i...
...And 6 more matches
Application cache implementation overview
bed 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 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...
...tion of the selection algorithm refer to the spec or to the code. ...
...But this time the entry is not selected to load the top level document from. We search another, if available, potentially even in a different offline cache group. ...
...And 6 more matches
Download
ty may be populated or changed while the download is in progress, using the MIME type provided by the server. currentBytes Read only number Number of bytes currently transferred. This value starts at zero, and may be updated regardless of the value of hasProgress. Note: You shouldn't rely on this property being equal to totalBytes to determine whether the download is
completed. You should use the individual state properties instead, since this value may not be updated after the last piece of data is transferred. error Read only DownloadError When the download fails, this is set to a DownloadError instance indicating the cause of the failure. If the download has been
completed successfully or has been canceled, this property is null. This property ...
... null. This property is reset to null when a failed download is restarted. hasPartialData Read only boolean Indicates whether, at this time, there is any partially downloaded data that can be used when restarting a failed or canceled download. This property is relevant while the download is in progress, and also if it failed or has been canceled. If the download has been
completed successfully, this property is not relevant anymore. Whether partial data can actually be retained depends on the saver and the download source, and may not be known before the download is started. hasProgress Read only boolean Indicates whether this download's progress property is able to report partial progress while the download proceeds, and whether the value in tota...
...function that is called after other properties change. Warning: This property cannot be used if the download is part of a DownloadList. progress Read only number Progress percent, from 0 to 100. Intermediate values are reported only if hasProgress is true. Note: You shouldn't rely on this property being equal to 100 to determine whether the download is
completed. You should use the individual state properties (for example, the succeeded property) instead. saver Read only DownloadSaver Saver object associated with this download. source Read only DownloadSource Source of this download. startTime Read only Date Indicates the start time of the download. When the download starts, this property is set to a v...
...And 6 more matches
Index
individual data items, and the code might be required to abort a task at many positions in the logic. An arena is requested once processing of a task starts, and all memory allocations that are logically associated to that task are requested from the associated arena. The implementation of arenas makes sure that all individual memory blocks are tracked. Once a task is done, regardless whether it
completed or was aborted, the programmer simply needs to release the arena, and all individually allocated blocks will be released automatically. Often freeing is combined with immediately erasing (zeroing, zfree) the memory associated to the arena, in order to make it more difficult for attackers to extract keys from a memory dump. NSS uses many C data structures. Often NSS has multiple implementation...
... NSS Code Coverage NSS No summary! 163 NSS Config Options No summary! 164 NSS Developer Tutorial NSS, Tutorial No summary! 165 NSS FAQ NSS, NeedsUpdate NSS is set of libraries, APIs, utilities, and documentation designed to support cross-platform development of security-enabled client and server applications. It provides a
complete open-source implementation of the crypto libraries used by Mozilla and other companies in the Firefox browser, AOL Instant Messenger (AIM), server products from Red Hat, and other products. 166 NSS Key Log Format Key logs can be written by NSS so that external programs can decrypt TLS connections. Wireshark 1.6.0 and above can use these log files to decrypt packets. You can ...
...essfully parsed installation script Current platform is Linux:5.4.08:x86 Using installation parameters for platform Linux:5.4.08:x86 Installed file crypto.so to /tmp/crypto.so Installed file setup.sh to ./pk11inst.dir/setup.sh Executing "./pk11inst.dir/setup.sh"... "./pk11inst.dir/setup.sh" executed successfully Installed module "Example PKCS #11 Module" into module database Installation
completed successfully Adding Module Spec Each module has information stored in the security database about its configuration and parameters. These can be added or edited using the -rawadd command. For the current settings or to see the format of the module spec in the database, use the -rawlist option. modutil -rawadd modulespec Deleting a Module A specific PKCS #11 module can ...
...And 6 more matches
Priority Content - Archive of obsolete content
If you would like to sign up to do the migration of any of these works, just "Edit" this page and add your name to the "Migrators" list for the piece. If there is DevEdge content you think should be migrated that isn't currently on this list, feel free to add it. Note: Use example at Sample:Original Document Information to credit original authors. DevEdge DevEdge Mirror Note: If you're digging around the mirror and see anything there that you think should be migrated to Devmo that isn't on this list, feel free to add it below. ...
...ML: Netscape and XSLT 1.0 Original: Transforming XML: Netscape and XSLT 1.0 Wiki Location: Transforming XML with XSLT Migrators: Serge K. Keller In progress: Rapid Application Development With Mozilla Original: Author's page and planned host, Ben's temporary host Wiki Location: TOC and links page still under construction. ...
...They are dependant on some code that cannot be integrated in the page. ...
...And 5 more matches
Front-end web developer - Learn web development
or example, if you already know HTML, you can skip ahead to the CSS section. Prerequisites You don't need any previous knowledge to start this course. All you need is a computer that can run modern web browsers, an internet connection, and a willingness to learn. If you are not sure if front-end web development is for you, and/or you want a gentle introduction before starting a longer and more
complete course, work through our Getting started with the web module first. Getting help We have tried to make learning front-end web development as comfortable as possible, but you will probably still get stuck because you don't understand something, or some code is just not working. Don't panic. We all get stuck, whether we are beginner or professional web developers. The Learning and getting help a...
...or some code is just not working. Don't panic. We all get stuck, whether we are beginner or professional web developers. The Learning and getting help article provides you with a series of tips for looking up information and helping yourself. If you are still stuck, feel free to post a question on our Discourse forum. Let's get started. Good luck! The learning pathway Getting started Time to
complete: 1.5-2 hours Prerequisites Nothing except basic computer literacy. How will I know I'm ready to move on? There are no assessments in this part of the course. But make sure you don't skip. It is important to get you set up and ready to do work for exercises later on in the course. Guides Installing basic software -- basic tool setup (15 min read) Background on the web and web standards (4...
...o move on? There are no assessments in this part of the course. But make sure you don't skip. It is important to get you set up and ready to do work for exercises later on in the course. Guides Installing basic software -- basic tool setup (15 min read) Background on the web and web standards (45 min read) Learning and getting help (45 min read) Semantics and structure with HTML Time to
complete: 35-50 hours Prerequisites Nothing except basic computer literacy, and a basic web development environment. How will I know I'm ready to move on? The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module. Modules Introduction to HTML (15-20 hour read/exercises) Multimedia...
...And 5 more matches
Getting started with Svelte - Learn web development
e it. Note: recently Svelte has added official TypeScript support, one of its most requested features. We'll look at it later on in this tutorial series. We encourage you to go through the Svelte tutorial for a really quick introduction to the basic concepts, before returning to this tutorial series to learn how to build something slightly more in-depth. It should take you about 30 minutes to
complete. Use cases Svelte can be used to develop small pieces of an interface or whole applications. You can either start from scratch letting Svelte drive your UI or you can incrementally integrate it into an existing application. Nevertheless, Svelte is particularly appropriate to tackle the following situations: Web applications intended for low power devices: Applications built with Svelte have...
...torials. See Package management basics for more information on npm and yarn. If you're using Windows, you will need to install some software to give you parity with Unix/macOS terminal in order to use the terminal commands mentioned in this tutorial. Gitbash (which comes as part of the git for Windows toolset) or Windows Subsystem for Linux (WSL) are both suitable. Cmder is another very good and
complete alternative. See Command line crash course for more information on these, and on terminal commands in general. Also see the following for more information: "What is npm" on nodejs.org "Introducing npx" on the npm blog "The easiest way to get started with Svelte" on the svelte blog Creating your first Svelte app The easiest way to create a starter app template is to just download the star...
...o create your starter app template, run the following terminal commands: npx degit sveltejs/template moz-todo-svelte cd moz-todo-svelte npm install npm run dev Note: degit doesn't do any kind of magic -- it just lets you download and unzip the latest version of a git repo's contents. This is much quicker than using git clone because it will not download all the history of the repo, or create a
complete local clone. After running npm run dev, Svelte will compile and build your application. It will start a local server at localhost:5000. Svelte will watch for file updates, and automatically recompile and refresh the app for you when changes are made to the source files. Your browser will display something like this: Application structure The starter template comes with the following structu...
...And 5 more matches
Fun With XBL and XPConnect
Introduction This article describes an application of XBL in which a simple XPCOM interface is made accessible to a XUL widget. The interface definition feature of XBL is used to define an interface through XPConnect to a C++ object that does auto completion. Once the regular XUL textfield widget is bound to this interface, it calls the auto
complete function of the object using regular JavaScript. ...
...erface definition feature of XBL is used to define an interface through XPConnect to a C++ object that does auto completion. Once the regular XUL textfield widget is bound to this interface, it calls the auto
complete function of the object using regular JavaScript. The basic model of interaction is as follows: Binding to the XPCOM Object The widget holds onto an XPCOM object that is the auto
complete engine that will perform our auto
complete lookups. <binding name="auto
complete" extends="xul:box"> <content> <xul:textfield class="addressingWidget"/> <xul:menupopup/> </content> <implementation> <property name="auto
CompleteSession"> <![CDATA[ Components.classes['component://netscape/messenger/auto
complete&type=addrbook']. getService(Components.interfaces...
...that will perform our auto
complete lookups. <binding name="auto
complete" extends="xul:box"> <content> <xul:textfield class="addressingWidget"/> <xul:menupopup/> </content> <implementation> <property name="auto
CompleteSession"> <![CDATA[ Components.classes['component://netscape/messenger/auto
complete&type=addrbook']. getService(Components.interfaces.nsIAuto
CompleteSession); ]]> </property> So we've defined a property on the widget called auto
CompleteSession. The initial value of this property evaluates to an xp-connect object. Now accesses to auto
CompleteSession will return the xp-connect object. Exposing the XPCOM Interfaces One somewhat nasty trick you need to do is to manually expose the interfaces of the XPCOM object that you want your wid...
...And 5 more matches
WebGL best practices - Web APIs
And to a lesser degree, VAO attachments (vertexAttribPointer, disable/enableVertexAttribArray) Drawing from static, unchanging VAOs is faster than mutating the same VAO for every d...
...ther systems don't, and content that works for you will not work for them! Avoid invalidating FBO attachment bindings Almost any change to an FBO's attachment bindings will invalidate its framebuffer
completeness. Set up your hot framebuffers ahead of time. In Firefox, setting the pref webgl.perf.max-warnings to -1 in about:config will enable performance warnings that include warnings about FB
completeness invalidations. And to a lesser degree, VAO attachments (vertexAttribPointer, disable/enableVertexAttribArray) Drawing from static, unchanging VAOs is faster than mutating the same VAO for every draw call. For unchanged VAOs, browsers can cache the fetch limits, whereas when VAOs change, browsers must revalidate and recalculate limits. The overhead for this is relatively low, but re-using VA...
...shed 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 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 command...
...And 5 more matches
<input type="password"> - HTML: Hypertext Markup Language
essed, especially on virtual keyboards. Note: Any forms involving sensitive information like passwords (e.g. login forms) should be served over HTTPS; Many browsers now implement mechanisms to warn against insecure login forms; see Insecure passwords. Value A DOMString representing a password, or empty Events change and input Supported Common Attributes auto
complete, 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 t...
...ype, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored
completely. Tip: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. Use of a pattern is strongly recommended for password inputs, in order to help ensure that valid passwords using a wide assortment of character classes are selected and used by your users.
...input boxes generally work just like other textual input boxes; the main difference is the obscuring of the content to prevent people near the user from reading the password. A simple password input Here we see the most basic password input, with a label established using the <label> element. <label for="userPassword">Password: </label> <input id="userPassword" type="password"> Allowing auto
complete To allow the user's password manager to automatically enter the password, specify the auto
complete attribute. For passwords, this should typically be one of the following: on Allow the browser or a password manager to automatically fill out the password field. This isn't as informative as using either current-password or new-password. off Don't allow the browser or password manager to auto...
...And 5 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
the global attributes. Those with extra importance as it relates to <input> are highlighted. Attributes for the <input> element include global HTML attributes and: Attribute Type or Types Description accept file Hint for expected file type in file upload controls alt image alt attribute for the image type. ...
...Whether to allow multiple values ...
...ttributes accept Valid for the file input type only, the accept attribute defines which file types are selectable in a file upload control. See the file input type. alt Valid for the image button only, the alt attribute provides alternative text for the image, displaying the value of the attribute if the image src is missing or otherwise fails to load. See the image input type. auto
complete (Not a Boolean attribute!) The auto
complete attribute takes as its value a space-separated string that describes what, if any, type of auto
complete functionality the input should provide. A typical implementation of auto
complete simply recalls previous values entered in the same input field, but more complex forms of auto
complete can exist. For instance, a browser could integrate with a device...
...And 5 more matches
Understanding client-side JavaScript frameworks - Learn web development
ut its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app, learning a bit about how React works in the process. 2. Beginning our React todo list Let's say that we've been tasked with creating a proof-of-concept in React - an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as
complete without deleting them. This article will walk you through putting the basic App component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. 3. Componentizing our React app At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn't have an...
...Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn't have any hard rules for what is and isn't a component - that's up to you! In this article, we will show you a sensible way to break our app up into components. 4. React interactivity: Events and state With our component plan worked out, it's now time to start updating our app from a
completely static UI to one that actually allows us to interact and change things. In this article we'll do this, digging into events and state along the way. 5. React interactivity: Editing, filtering, conditional rendering As we near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to ed...
...nge things. In this article we'll do this, digging into events and state along the way. 5. React interactivity: Editing, filtering, conditional rendering As we near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to edit existing tasks and filtering the list of tasks between all,
completed, and in
complete tasks. We'll look at conditional UI rendering along the way. 6. Accessibility in React In our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users. 7. React resources Our final article provides you with a list of React resources ...
...And 4 more matches
nsIContentPrefService2
llback2 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 preferences to observe. Pass null to observe all preference changes regardless of name. observer Th...
...e handleResult is not called at all. removeAllDomains() Removes all non-global preferences -- in other words, all preferences that have a domain. void removeAllDomains( in nsILoadContext context, in nsIContentPrefCallback2 callback Optional ); Parameters context The private-browsing context, if any. callback Optional HandleCompletion is called when the operation
completes. removeAllGlobals() Removes all global preferences -- in other words, all preferences that have no domain. void removeAllGlobals( in nsILoadContext context, in nsIContentPrefCallback2 callback Optional ); Parameters context The private-browsing context, if any. callback Optional HandleCompletion is called when the operation
completes. removeByDomain() Removes ...
... removeByDomainAndName() Removes the preference with the given domain and name. void removeByDomainAndName( in AString domain, in AString name, in nsILoadContext context, in nsIContentPrefCallback2 callback Optional ); Parameters domain The preference's domain. name The preference's name. context The private-browsing context, if any. ...
...And 4 more matches
Streams - Plugins
eter type to one of these transmission modes: NP_NORMAL: (Default): The plug-in can process the data progressively as it arrives from the network or file system through a series of calls to NPP_WriteReady and NPP_Write. NP_ASFILEONLY: This plug-in gets full random access to the data using platform-specific file operations. The browser saves stream data to a local file, and, when the stream is
complete, delivers the path of the file through a call to NPP_StreamAsFile. NP_ASFILE: This mode is like NP_ASFILEONLY except that data is delivered to the plug-in as it is saved to the file, through a series of calls to NPP_Write. You should use NP_ASFILEONLY whenever possible in preference to NP_ASFILE, which is less efficient because it uses successive calls to NPP_Write to send the data. NP_SEEK: Th...
...n written to the plug-in, the stream is destroyed. To do this, either the browser can call NPP_DestroyStream or the plug-in can call NPN_DestroyStream. This applies to all plug-in modes except NP_SEEK. NOTE: A plug-in can also use the NPN_GetURL method to request a stream for an arbitrary URL. Telling the Plug-in When a Stream Is Deleted The browser calls the NPP_DestroyStream method when it
completes the stream sent to the plug-in, either successfully or abnormally. Once the plug-in returns from this method, the browser deletes the NPStream object. The plug-in can terminate the stream itself by calling NPN_DestroyStream. You should delete any private data allocated in the plug-in's stream->pdata field when you destroy a stream. The plug-in can store private data associated with the stream i...
...ocess of pushing data to the plug-in. If the user now requests a specific page of the document, the plug-in calls NPN_RequestRead with a list of byte ranges. The open stream is converted from normal mode to seek mode in an effort to pass the plug-in data that was already on the way, rather than just discarding it. All NPP_Write calls for streaming data eventually stop, and NPP_Write calls will be
completed only for data requested with NPN_RequestRead. The browser does not create a new stream for each byte range it requests. Instead, additional NPP_WriteReady and NPP_Write calls occur on the same stream. An individual call to NPN_RequestRead can request discontiguous ranges, and you can have many outstanding NPN_RequestRead calls. There is no guarantee that NPP_Write will receive requests for rang...
...And 4 more matches
Signaling and video calling - Web APIs
need to exchange ICE candidates to negotiate the actual connection between them. Every ICE candidate describes a method that the sending peer is able to use to communicate. Each peer sends candidates in the order they're discovered, and keeps sending candidates until it runs out of suggestions, even if media has already started streaming. An icecandidate event is sent to the RTCPeerConnection to
complete the process of adding a local description using pc.setLocalDescription(offer). Once the two peers agree upon a mutually-compatible candidate, that candidate's SDP is used by each peer to construct and open a connection, through which media then begins to flow. If they later agree on a better (usually higher-performance) candidate, the stream may change formats as needed. Though not currently su...
...You can learn more about the codecs which WebRTC requires browsers to support, which additional codecs are supported by which browsers, and how to choose the best codecs to use in the guide Codecs used by WebRTC. Optionally, see RFC 8445: Interactive Connectivity Establishment, section 2.3 ("Negotiating Candidate Pairs and Concluding ICE") if you want greater understanding of how this process is
completed inside the ICE layer. You should note that candidates are exchanged and media starts to flow as soon as the ICE layer is satisfied. This is all taken care of behind the scenes. Our role is to simply send the candidates, back and forth, through the signaling server. The client application The core to any signaling process is its message handling. It's not necessary to use WebSockets for signali...
...ce the element is configured to automatically play incoming video, the stream begins playing in our local preview box. We then iterate over the tracks in the stream, calling addTrack() to add each track to the RTCPeerConnection. Even though the connection is not fully established yet, you can begin sending data when you feel it's appropriate to do so. Media received before the ICE negotiation is
completed may be used to help ICE decide upon the best connectivity approach to take, thus aiding in the negotiation process. Note that for native apps, such as a phone application, you should not begin sending until the connection has been accepted at both ends, at a minimum, to avoid inadvertently sending video and/or audio data when the user isn't prepared for it. As soon as media is attached to the ...
...And 4 more matches
filter - CSS: Cascading Style Sheets
<svg style="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg"> <filter id="svgBlur" x="-5%" y="-5%" width="110%" height="110%"> <feGaussianBlur in="SourceGraphic" stdDeviation="5"/> </filter> </svg> brightness() The brightness() function applies a linear multiplier to the input image, making it appear more or less bright. 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="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg"> <filter id="brightness"> <feComponentTransfer> <feFuncR type="li...
...round: none repeat scroll 0% 0% rgb(238, 238, 238); text-align: left; font-weight: bold; } table.standard-table td { padding: 5px; border: 1px solid rgb(204, 204, 204); text-align: left; vertical-align: top; width:25%; height:auto; } #img3 { height:100%; } contrast() The contrast() function adjusts the contrast of the input image. A value of 0% will create an image that is
completely gray. A value of 100% leaves the input unchanged. Values of an amount over 100% are allowed, providing results with more contrast. The lacuna value for interpolation is 1. filter: contrast(200%) <svg style="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg"> <filter id="contrast"> <feComponentTransfer> <feFuncR type="linear" slope="[amount]" intercept="-(0.5 * ...
...lign: left; font-weight: bold; } table.standard-table td { padding: 5px; border: 1px solid rgb(204, 204, 204); text-align: left; vertical-align: top; width:25%; height:auto; } #img3, #img13 { width:100%; height:auto; } grayscale() The grayscale() function converts the input image to grayscale. The value of amount defines the proportion of the conversion. A value of 100% is
completely grayscale. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. The lacuna value for interpolation is 0. filter: grayscale(100%) <table class="standard-table"> <thead> <tr> <th style="text-align: left;" scope="col">Original image</th> <th style="text-align: left;" scope="col">Live example</th> <th style="text-align...
...And 4 more matches
Navigation and resource timings - Web Performance
loading process was reached. As displayed in the image below, the navigation process goes from navigationStart, unloadEventStart, unloadEventEnd, redirectStart, redirectEnd, fetchStart, domainLookupStart, domainLookupEnd, connectStart , connectEnd, secureConnectionStart, requestStart, responseStart, responseEnd, domLoading, domInteractive, domContentLoadedEventStart, domContentLoadedEventEnd, dom
Complete, loadEventStart, and loadEventEnd. With the metrics above, and a little bit of math, we can calculate many important metrics like time to first byte, page load time, dns lookup, and whether the connection is secure. To help measure the time it takes to
complete all the steps, the Performance Timing API provides read only measurements of navigation timings. To view and capture our app's timin...
...e the same as PerformanceTiming.fetchStart. secureConnectionStart When the secure connection handshake starts. If no such connection is requested, it returns 0. redirectStart When the first HTTP redirect starts. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. redirectEnd When the last HTTP redirect is
completed, that is when the last byte of the HTTP response has been received. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. connectEnd When the connection is opened network. If the transport layer reports an error and the connection establishment is started again, the last connection establishment end time is given. If a persistent ...
...sponding readystatechange event is thrown. domContentLoadedEventStart Right before the parser sent the DOMContentLoaded event, that is right after all the scripts that need to be executed right after parsing have been executed. domContentLoadedEventEnd Right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. dom
Complete When the parser finished its work on the main document, that is when its Document.readyState changes to '
complete' and the corresponding readystatechange event is thrown. loadEventStart When the load event was sent for the current document. If this event has not yet been sent, it returns 0. loadEventEnd When the load event handler terminated, that is when the load event...
...And 4 more matches
request - Archive of obsolete content
ect that can be used to make network requests. The constructor takes a single parameter options which is used to set several properties on the resulting Request. Parameters options : object Optional options: Name Type url string,url This is the url to which the request will be made. Can either be a String or an instance of the SDK's URL. on
Complete function This function will be called when the request has received a response (or in terms of XHR, when readyState == 4). The function is passed a Response object. headers object An unordered collection of name/value pairs representing headers to send with the request. content string,object The content to send to the server. If content i...
...xt content which was encoded as ISO-8859-1 (Latin 1), it will be given a content type 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", on
Complete: 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 c...
... 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 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...
...And 3 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
<< PreviousNext >> This document was authored by Taiga (Gomita) Gomibuchi and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Gomita-san won "Most Useful Upgraded Extension" award in Mozilla's 2006 "Extend Firefox" competition for ScrapBook, and was runner-up in the "Extend Firefox 2" contest for FireGestures. ...
..., and invokes the cross-package overlay. Developing a Simple Extension: Hello World In this section, we will write an extremely simple "hello world" extension that only displays the time.3 Phase 1: test install Our first step will be to perform a test installation consisting of the minimum code needed to add a new menu item to the Tools menu (Figure 3). FIXME: Figure 3: Menu after Phase 1
complete Source file structure First set up the work folders you'll use to organize your extension's source files. The folder can be wherever you want, but for the purposes of this guide, we'll assume it's at C:\extensions\helloworld . Create folders and files in your work folder as shown in Figure 4. The purpose of each file created during Phase 1 is explained in Table 2. Figure 4: Folder structure us...
... name purpose icon.png The full-size toolbar button icon file icon-small.png the small toolbar button icon file overlay.css Style sheet that defines the toolbar buttons to use. Overlays both the browser window and the "customize toolbar" window. Phase 5: XPI packaging We actually
completed our Hello World extension in Phase 4, but you can't distribute the source files in this state to other users. So we need to create an xpi-formatted installer. XPI file directory structure XPI is basically just a zip archive, but the directory structure inside an xpi file is generally different from your development directory structure (Figure 11). FIXME: Figure 11: Directory structure inside ...
...And 3 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
d is the foremost consideration, we provide C++ libraries with multi-language interfaces for comprehensive, performant access to networking, filesystem, content, rendering, and much more. What this means to you as the developer is this: you can take advantage of skills you already have with XML or web technologies to design and implement anything from a simple text editor to a comprehensive IDE -
complete with all of the interface widgets that you would find in virtually any major application framework. Another benefit of this standards-based approach to UI development is that your application is cross-platform "out of the box". Imagine not having to re-write your application 3 times, or not supporting a less popular platform simply because you do not have the resources for parallel development! ...
... map these to images and application logic. This is very powerful since you could make improvements to the underlying application logic without having to rewrite the higher level code. Our platform also can take advantage of other internet standards such as XSLT and RDF. RDF, a core element to the framework, allows you to define dynamic elements in your UI (elements that may change after you have
completed the application, such as a "history" menu item). XSLT could be used to translate information from Web Services, RSS, SOAP, or other XML-based languages and convert them into a form that you might display in your user interface. The Gecko Rendering Engine Gecko is the revolutionary rendering engine that offers advanced features for Internet browsing anywhere across applications, computing platfo...
...b content, applications and services on any computing platform or device. Open source and freely available, Gecko is small in size and modular and achieves rendering speed superior to all other browser engines - which makes it perfect for embedding into both desktop applications such as browsers and new devices such as browsing appliances and set top boxes. Supporting Gecko Technologies provide a
complete set of resources for efficient development, including full support of web standards, a cross-platform/cross-device user interface language, an extensible architecture and embedding technologies. With its unprecedented power, speed and standards support, the Gecko browser engine represents a major advance for developers. With Gecko, developers seeking a streamlined way to create and distribute web...
...And 3 more matches
Introduction to XUL - Archive of obsolete content
alog buttons will require some platform-specific work. A single XUL specification can only cross-platform to a degree. UI designers and build engineers will need to maintain separate, platform-specific versions of at least some XUL documents. "XPToolkit" is rather synonymous with XPFE. Though the former term seems more concrete than the other, and therefore is not an exact replacement, no one is
completely certain why we have both. "XUL" already introduced, is an application of XML used to describe the layout of most windows in the Mozilla browser, including and especially the main, browser window. Scope This paper makes no attempt to explain requirements. We don't have a current "requirements" document. XPToolkit Architecture is a better place to gain an understanding of such things. This pap...
... Mozilla browser, including and especially the main, browser window. Scope This paper makes no attempt to explain requirements. We don't have a current "requirements" document. XPToolkit Architecture is a better place to gain an understanding of such things. This paper contains a short introduction to Mozilla front-end architecture, concentrating on the task of building UIs. It is, as always, in
complete. Mozilla applications will be built of "small" components like dialog buttons and mail inbox folders, which we collectively term "widgets." Within a widget, drawing and user interactions are
completely under control of the individual widget, and set when the widget was built. Relative placement of widgets, their interactions with each other, and optionally some of their configuration, will be co...
...ove example is using an implicit XUL namespace. This is optional; other examples in this document will on occasion belabor the namespace issue by declaring each use explicitly. The chrome protocol is another Mozilla extension allowing the exact location of files involved in the chrome description to be moved without affecting the XUL source. So it's just an indirection. Someday, there will be a
complete description of this mechanism at packages, but for now there's a good but somewhat out of date document at Configurable Chrome available for more information. Scripting A XUL interface is only a collection of disconnected widgets until it has been programmed. "Programming" can be as simple as some JavaScript to tie the widgets together and perhaps to give them extra functionality, or as complex...
...And 3 more matches
nsIDownloadManager
This interface is deprecated as of Firefox 26. Please use Downloads.jsm instead. toolkit/components/downloads/public/nsIDownloadManager.idlScriptable This interface lets applications and extensions communicate with the Download Manager, adding and removing files to be downloaded, fetching information about downloads, and being notified when downloads are
completed. Inherits from: nsISupports Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Implemented by: @mozilla.org/download-manager;1. To get the service, use: var downloadManager = Components.classes["@mozilla.org/download-manager;1"] .getService(Components.interfaces.nsIDownloadManager); Method overview nsIDownload addDownload(in short aDownloadType, in nsIURI aSource, in ...
...ko 1.9.1 Attributes Attribute Type Description activeDownloadCount long The number of files currently being downloaded. 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 downloads that have
completed, have failed or have been canceled. Read only. datasource nsIRDFDataSource Read only. Obsolete since Gecko 1.8 DBConnection mozIStorageConnection The database connection to the downloads database. Read only. defaultDownloadsDirectory nsILocalFile Returns the platform default downloads directory. Read only. listener nsIDownloadProgressLis...
...r.download.dir preference. If this preference is invalid, the download directory falls back to the default. Read only. Constants Constant Value Description DOWNLOAD_NOTSTARTED -1 The download has not been started yet. DOWNLOAD_DOWNLOADING 0 The download is in the process of being downloaded. DOWNLOAD_FINISHED 1 Download
completed including any processing of the target file. DOWNLOAD_FAILED 2 The download failed due to error. DOWNLOAD_CANCELED 3 The user canceled the download. DOWNLOAD_PAUSED 4 The download is currently paused. DOWNLOAD_QUEUED 5 The download is in the queue but is not presently downloading. DOWNLOAD_BLOCKED_PARENTAL 6 The download...
...And 3 more matches
Using the Payment Request API - Web APIs
g the payment process Once the PaymentRequest object has been created, you call the PaymentRequest.show() method on it to initiate the payment request. This returns a promise that fulfills with a PaymentResponse object if the payment is successful: request.show().then(function(paymentResponse) { // Here we would process the payment. For this demo, simulate immediate success: paymentResponse.
complete('success') .then(function() { // For demo purposes: introPanel.style.display = 'none'; successPanel.style.display = 'block'; }); }) This object provides the developer with access to details they can use to
complete the logical steps required after the payment
completes, such as an email address to contact the customer, a shipping address for mailing goods out to them, etc. In the...
... introPanel.style.display = 'none'; successPanel.style.display = 'block'; }); }) This object provides the developer with access to details they can use to
complete the logical steps required after the payment
completes, such as an email address to contact the customer, a shipping address for mailing goods out to them, etc. In the code above, you'll see that we've called the PaymentResponse.
complete() method to signal that the interaction has finished -- you'd use this to carry out finishing steps, like updating the user interface to tell the user the transaction is
complete, etc. Other useful payment request methods There are some other useful payment request methods worth knowing about. PaymentRequest.canMakePayment() can be used to check whether the PaymentRequest object is capable of ...
...ue: '0.01'}}}) .canMakePayment() .then(function(result) { if(result) { // Real payment request var request = new PaymentRequest(buildSupportedPaymentMethodData(), checkoutObject); request.show().then(function(paymentResponse) { // Here we would process the payment. paymentResponse.
complete('success') .then(function() { // Finish handling payment }); }) } }) PaymentRequest.abort() can be used to abort the payment request if required. Detecting availability of the Payment Request API You can effectively detect support for the Payment Request API by checking if the user's browser supports PaymentRequest, i.e. if (wi...
...And 3 more matches
RTCPeerConnection - Web APIs
en the state of the ICE connection changes, such as when it disconnects. Also available using the oniceconnectionstatechange event handler property. icegatheringstatechange Sent to the RTCPeerConnection when the ICE layer's gathering state, reflected by iceGatheringState, changes. This indicates whether ICE negotiation has not yet begun (new), has begun gathering candidates (gathering), or has
completed (
complete). Also available using the onicegatheringstatechange event handler property. isolationchange Sent to the RTCPeerConnection when the isolated property on one of the MediaStreamTrack objects associated with the connection changes value. A track is isolated if its content cannot be accessed by the owning document due to lack of authentication or if the track comes from a cross-origin s...
...hering of candidates is also still underway. "connected" A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use. "
completed" The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components. "failed" The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for som...
...eturned using the RTCPeerConnection.iceGatheringState property. You can detect when this value changes by watching for an event of type icegatheringstatechange. Constant Description "new" The peer connection was just created and hasn't done any networking yet. "gathering" The ICE agent is in the process of gathering candidates for the connection. "
complete" The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to "gathering" to gather those candidates. RTCIceTransportPolicy enum The RTCIceTransportPolicy enum defines string constants which can be used to limit the transport policies of th...
...And 3 more matches
Using XMLHttpRequest - Web APIs
In this guide, we'll take a look at how to use XMLHttpRequest to issue HTTP requests 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...
...ss notifications, error notifications, and so forth. Support for DOM progress event monitoring of XMLHttpRequest transfers follows the specification for progress events: these events implement the ProgressEvent interface. The actual events you can monitor to determine the state of an ongoing transfer are: progress The amount of data that has been retrieved has changed. load The transfer is
complete; all data is now in the response var oReq = new XMLHttpRequest(); oReq.addEventListener("progress", updateProgress); oReq.addEventListener("load", transfer
Complete); oReq.addEventListener("error", transferFailed); oReq.addEventListener("abort", transferCanceled); oReq.open(); // ... // progress on transfers from the server to the client (downloads) function updateProgress (oEvent) { if (o...
...Req = new XMLHttpRequest(); oReq.addEventListener("progress", updateProgress); oReq.addEventListener("load", transfer
Complete); oReq.addEventListener("error", transferFailed); oReq.addEventListener("abort", transferCanceled); oReq.open(); // ... // progress on transfers from the server to the client (downloads) function updateProgress (oEvent) { if (oEvent.lengthComputable) { var percent
Complete = oEvent.loaded / oEvent.total * 100; // ... ...
...And 3 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
piration comes from http://www.alain.knaff.lu/howto/MozillaCustomization/ and http://mit.edu/~firefox/www/maintain...utoconfig.html. For history, I've kept Mozilla and Netscape chapters, as certain points are complementary to the web-based AutoConfig file. This MCD (aka autoconfig here), is not to be confused with https://wiki.mozilla.org/Thunderbird...oconfiguration . It's Mission is to enable
completely automatic configuration of mozilla's apps preferences based on users properties either retrieved from system environement variables or on an organisation ldap directory. Situation INT-Evry manages about 3000 users (mostly students) who share computers in labs and "self service" computer rooms. Hence a single computer might connect many different users all day long. Computers are dual-boot (Wi...
...docs/manuals/deploymt/config.htm. AutoConfig Directives Here we want to set users central mail preferences: Create one account from their login name, get their email address from an LDAP request and set the enterprise IMAP and SMTP servers. Hence, when working on multiuser workstations, each user gets automatically Thunderbird configured for his profile. ...
...use a Linux or Windows environment variable for the USER / USERNAME. ...
...And 2 more matches
Download Manager preferences - Archive of obsolete content
wnload.manager.alertOnEXEOpen A boolean value that indicates whether the UI Should alert the user about the dangers of opening (executing) an EXE. The user may check a "don't ask" box on the UI to toggle this. Default value is true. browser.download.manager.closeWhenDone A boolean value indicating whether or not the Downloads window should close automatically when downloads are
completed. In Thunderbird the default value is true. In Other Applications the default value is false. browser.download.manager.flashCount Indicates the number of times the appropriate user interface element should be "flashed" to get the user's attention when a download
completes. Default value is 2. browser.download.manager.focusWhenStarting A boolean value that indic...
... Default value is 0 (resume on next launch). browser.download.manager.resumeOnWakeDelay An integer value indicating the number of milliseconds to wait after the system wakes up from sleep before resuming downloads. Default value is 10000. browser.download.manager.retention Indicates how long downloads are retained in the Download Manager's queue after the download is
completed successfully. 0 indicates that the download should be removed upon completion; 1 indicates that
completed and canceled downloads should be removed on quit; 2 indicates that downloads should never be removed automatically. In Firefox and SeaMonkey the default value is 2. In Thunderbird the default value is 1; If the preference is missing, the value 0 is used. browser.download...
...nceled downloads should be removed on quit; 2 indicates that downloads should never be removed automatically. In Firefox and SeaMonkey the default value is 2. In Thunderbird the default value is 1; If the preference is missing, the value 0 is used. browser.download.manager.scanWhenDone A boolean value that indicates whether or not to perform virus scans after downloads are
complete. On Windows XP SP2 and Windows Vista, this value also indicates whether downloaded files trigger a security warning upon launch. Default value is true. browser.download.manager.showAlertInterval The minimum number of milliseconds that must elapse between download
complete alerts; if two downloads
complete within this amount of time, only one alert is displayed. Default value i...
...And 2 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
ages are rendered under this mode. Mozilla uses quirks mode for the following conditions: When no doctype is specified For doctypes without a system identifier (for example, <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">) For further reading, check out: Mozilla Quirks Mode Behavior and Mozilla's DOCTYPE sniffing. Event differences Mozilla and Internet Explorer are almost
completely different in the area of events. The Mozilla event model follows the W3C and Netscape model. In Internet Explorer, if a function is called from an event, it can access the event object through window.event. Mozilla passes an event object to event handlers. They must specifically pass the object on to the function called through an argument. A cross-browser event handling example follows (note ...
...pRequest object. Since version 7 IE also supports the "native" XMLHttpRequest object. After instantiating the object using new XMLHttpRequest(), you can use the open method to specify what type of request (GET or POST) you use, which file you load, and if it is asynchronous or not. If the call is asynchronous, then give the onload member a function reference, which is called once the request has
completed. Synchronous request: var myXMLHTTPRequest = new XMLHttpRequest(); myXMLHTTPRequest.open("GET", "data.xml", false); myXMLHTTPRequest.send(null); var myXMLDocument = myXMLHTTPRequest.responseXML; Asynchronous request: var myXMLHTTPRequest; function xmlLoaded() { var myXMLDocument = myXMLHTTPRequest.responseXML; } function loadXML(){ myXMLHTTPRequest = new XMLHttpRequest(); myXMLHTT...
... string getAllResponseHeaders() Returns all response headers as one string. string getResponseHeader(string headerName) Returns the value of the specified header. functionRef onerror If set, the references function will be called whenever an error occurs during the request. functionRef onload If set, the references function will be called when the request
completes successfully and the response has been received. Use when an asynchronous request is used. void open (string HTTP_Method, string URL) void open (string HTTP_Method, string URL, boolean async, string userName, string password) Initializes the request for the specified URL, using either GET or POST as the HTTP method. To send the request, call the send() method after initializ...
...And 2 more matches
Mozilla Crypto FAQ - Archive of obsolete content
relating to encryption functionality in Mozilla, and general questions on U.S. regulation of encryption technology. Cryptographic functionality in Mozilla Have all the issues with Mozilla and crypto now been resolved? Almost. Now that the RSA patent is in the public domain, Mozilla crypto development can proceed with minimal restrictions. In the near future the Mozilla code base will include a
complete open source cryptographic library, and Mozilla will include SSL support as a standard feature. After the U.S. government relaxed U.S. export regulations in January 2000 to allow export of source code for open source software implementing encryption, the major remaining legal obstacle to Mozilla crypto development was the fact that RSA Security, Inc., held a U.S. patent on the RSA public key algo...
...ion of the RSA algorithm; that code, together with code previously developed for other cryptographic algorithms, will be included in a new version 3.1 of the NSS open source cryptographic and PKI library. This new RSA-capable version of NSS will then be included in a future version of the open source PSM software, which will provide SSL support for Mozilla. At that point both NSS and PSM will be
completely buildable using the open source code available from the mozilla.org site, and NSS and PSM will be included in the Mozilla binary releases distributed by mozilla.org. For more information on the RSA patent see the RSA Security press release announcing release of the patent into the public domain, and the RSA patent itself. For information on new US encryption export regulations, see the U.S. D...
...Alliance press release on the release of PKI source code and the corresponding mozilla.org press release. What functionality is implemented by the Mozilla crypto code released so far? When will Mozilla get full support for SSL and S/MIME? The Mozilla crypto code will shortly include a full implementation of the RSA and other cryptographic algorithms; that implementation will form the basis of a
complete open source SSL implementation for Mozilla. S/MIME support is also under development, but may not be available in Mozilla until after the 1.0 release. Version 3.1 of the Network Security Services library will include a
complete open source implementation of the cryptographic algorithms needed for Mozilla SSL support, including the RSA public key algorithm (now in the public domain). NSS 3.1 will...
...And 2 more matches
textbox.type - Archive of obsolete content
In addition, arrow buttons appear next to the textbox to let the user step through values. ...
...In addition, arrow buttons appear next to the textbox to let the user step through values. ...
...In addition, arrow buttons appear next to the textbox to let the user step through values. ...
...And 2 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
mail, txt_message, btn_comments ], renderTo: "form-comments" }); }); </script> The code in Listing 6 starts by hooking in the Ext JS library which is used to produce the UI elements of the form. Next a script named validateComments.js is hooked in with the runat attribute set to both. The function defined within this file checks the form to make sure it is
complete, returning a boolean. The both context it operates within is a very powerful concept as we are able to use this code to check values entered in the form on both the client and server side. No custom validation libraries for each environment makes for rapid development with less risk for error. Towards the bottom of the code are two div tags with ids form-comments and out...
...ered in the form on both the client and server side. No custom validation libraries for each environment makes for rapid development with less risk for error. Towards the bottom of the code are two div tags with ids form-comments and out-logger. The form-comments div is used to render the form and the out-logger will be used as a log display as each comment is added. The
completed user interface is shown in Figure 1. Figure 1 - The user interface Server-Side DOM Processing Another powerful concept of Jaxer is the ability to access the DOM server-side with JavaScript. This gives you added control to interrogate and manage the document structure before it's pushed to the client. Listing 7 contains the code which demonstrates this concept. ...
...monstrates this concept. Listing 7 - Manipulating the DOM server-side <script runat="server"> window.onserverload = function() { document.getElementById( "out-logger" ).innerHTML = Jaxer.File.read( "dump.txt" ); } </script> The code in listing 7 is executed server-side and takes advantage of the onserverload event which ensures that we have a
complete DOM before trying to access it. This code is simple in that it updates the innerHTML of the logging div with the contents of a text file. The contents of this file are obtained through the file I/O capabilities exposed by Jaxer which is what we'll examine next. File I/O Jaxer ships with a comprehensive filesystem I/O capability that is very useful. There are numerous met...
...And 2 more matches
2D maze game with device orientation - Game development
g desktop and mobile HTML5 games. It's quite new, but growing rapidly thanks to the passionate community involved in the development process. You can check it out on GitHub where it's open sourced, read the online documentation and go through the big collection of examples. The Phaser framework provides you with a set of tools that will speed up development and help handle generic tasks needed to
complete the game, so you can focus on the game idea itself. Starting with the project You can see Cyber Orb source code on GitHub. The folder structure is quite straightforward: the starting point is the index.html file where we initialize the framework and set up an <canvas> to render the game on. You can open the index file in your favourite browser to launch the game and try it. There are also th...
...pauses and resumes the game. manageAudio turns the audio on and off. wallCollision is executed when the ball hits the walls or other objects. handleOrientation is the function bound to the event responsible for the Device Orientation API, providing the motion controls when the game is running on a mobile device with appropriate hardware. finishLevel loads a new level when the current level is
completed, or finished the game if the final level is
completed. Adding the ball and its motion mechanics First, let's go to the create() function, initialize the ball object itself and assign a few properties to it: this.ball = this.add.sprite(this.ballStartPos.x, this.ballStartPos.y, 'ball'); this.ball.anchor.set(0.5); this.physics.enable(this.ball, Phaser.Physics.ARCADE); this.ball.body.setSize(18,...
...shown and the styling applied to the text. We have this printed out on the screen, but it would be good to update the values every second: this.time.events.loop(Phaser.Timer.SECOND, this.updateCounter, this); This loop, also in the create function, will execute the updateCounter function every single second from the beginning of the game, so we can apply the changes accordingly. This is how the
complete updateCounter function looks: updateCounter: function() { this.timer++; this.timerText.setText("Time: "+this.timer); this.totalTimeText.setText("Total time: "+(this.totalTimer+this.timer)); }, As you can see we're incrementing the this.timer variable and updating the content of the text objects with the current values on each iteration, so the player sees the elapsed time. Finishin...
...And 2 more matches
Introducing asynchronous JavaScript - Learn web development
<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 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 JavaScri...
...ermediate state, as it were. In essence, it's the browser's way of saying "I promise to get back to you with the answer as soon as I can," hence the name "promise." This concept can take practice to get used to; it feels a little like Schrodinger's cat in action. Neither of the possible outcomes have happened yet, so the fetch operation is currently waiting on the result of the browser trying to
complete the operation at some point in the future. We've then got three further code blocks chained onto the end of the fetch(): Two then() blocks. Both contain a callback function that will run if the previous operation is successful, and each callback receives as input the result of the previous successful operation, so you can go forward and do something else to it. Each .then() block returns anoth...
...ith async/await, as you'll learn later on. Note: You'll learn a lot more about promises later on in the module, so don't worry if you don't understand them fully yet. The event queue Async operations like promises are put into an event queue, which runs after the main thread has finished processing so that they do not block subsequent JavaScript code from running. The queued operations will
complete as soon as possible then return their results to the JavaScript environment. Promises versus callbacks Promises have some similarities to old-style callbacks. They are essentially a returned object to which you attach callback functions, rather than having to pass callbacks into a function. However, promises are specifically made for handling async operations, and have many advantages over old...
...And 2 more matches
A first splash into JavaScript - Learn web development
Here you'll build up a simple "Guess the number" game, step by step. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is. ...
...er they are wrong. Allow them to enter another guess. Increment the turn number by 1. If it is wrong and the player has no turns left: Tell the player it is game over. Stop the player from being able to enter more guesses (this would mess the game up). Display control allowing the player to restart the game. Once the game restarts, make sure the game logic and UI are
completely reset, then go back to step 1. Let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring JavaScript features as we go. Initial setup To begin this tutorial, we'd like you to make a local copy of the number-guessing-game-start.html file (see it live here). Open it in both your text editor and your web browser. At the moment you'll see a ...
... specify the parentheses when writing it inside addEventListener(). Try saving and refreshing your code now, and your example should work -- to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setGameOver() function that is supposed to be run once the game is over. Let's add our missing code now and
complete the example functionality. Finishing the game functionality Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript: function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Start new game'; document.body...
...And 2 more matches
Silly story generator - Learn web development
d units in the story into UK equivalents if the UK radio button is checked before the generate button is pressed. Will generate another random silly story if you press the button again (and again...) The following screenshot shows an example of what the finished program should output: 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. Basic setup: Create a new file called main.js, in the same directory as your index.html file. Apply the external JavaScript file to your HTML by inserting a <script> element into your HTML referencing main.js. Put it just before the closing </body> tag. Initial variables and functions: In the raw text file, copy all of the code under...
...ns describe what you need to do. Basic setup: Create a new file called main.js, in the same directory as your index.html file. Apply the external JavaScript file to your HTML by inserting a <script> element into your HTML referencing main.js. Put it just before the closing </body> tag. Initial variables and functions: In the raw text file, copy all of the code underneath the heading "1.
COMPLETE VARIABLE 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 randomValueFro...
... 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 set of three strings inside an array called insertX. Store the second set of three strings inside an array called insertY. Store the third set of three strings inside an array called insertZ. ...
...And 2 more matches
Handling common accessibility problems - Learn web development
devices. Users on alternative browsing devices such as TVs, watches, etc. Users of older devices that might not have the latest browsers. Users of lower spec devices that might have slow processors. In a way, this whole module is about accessibility -- cross browser testing makes sure that your sites can be used by as many people as possible. What is accessibility? defines accessibility more
completely and thoroughly than this article does. That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as responsive design and performance in other places in the module. Note: Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility ...
...f the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a <label> to link it unambiguously to its partner form input (each <label> for attribute value needs to match the form element id value), and it will make sense even if the source order is not
completely logical (which to be fair it should be). Note: For more information about link text and form labels, read Meaningful text labels. Finally, a quick word about data tables. A basic data table can be written with very simple markup (see bad-table.html live, and source), but this has problems -- there is no way for a screen reader user to associate rows or columns together as groupings of data ...
...able can be written with very simple markup (see bad-table.html live, and source), but this has problems -- there is no way for a screen reader user to associate rows or columns together as groupings of data -- to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table. If you instead look at our punk-bands-
complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers (<th> and scope attributes), <caption> element, etc. Note: For more information about accessible tables, read Accessible data tables. CSS CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectl...
...And 2 more matches
Handling common JavaScript problems - Learn web development
to define a function to add the handler separately, calling it on each iteration and passing it the current value of para and i each time (or something similar). See good-for-loop.html (see the source code also) for a version that works. Making sure asynchronous operations have returned before trying to use the values they return. For example, this Ajax example checks to make sure the request is
complete and the response has been returned before trying to use the response for anything. This kind of operation has been made easier to handle by the introduction of Promises to the JavaScript language. Note: Buggy JavaScript Code: The 10 Most Common Mistakes JavaScript Developers Make has some nice discussions of these common mistakes and more. Linters As with HTML and CSS, you can ensure better...
...ent versions of the specs (ECMAScript 6 / ECMAScript Next) that simply won't work in older browsers. Some of these are syntactic sugar (basically an easier, nicer way of writing what you can already do using existing features), and some offer interesting new possibilities. For example: Promises are a great new feature for performing asynchronous operations and making sure those operations are
complete before code that relies on their results is used for something else. As an example, the Fetch API (a modern equivalent to XMLHTTPRequest) uses promises to fetch resources across the network and make sure that the response has been returned before they are used (for example, displaying an image inside an <img> element). They are not supported in IE at all but are supported across all modern browse...
...at would otherwise be challenging to implement and get working cross browser, for example Foundation, Bootstrap, and Material-UI (the latter is a set of components for use with the React framework). These tend to be used as the basis of an entire site layout; it is often difficult to drop them in just for one UI feature. Normalization libraries: Give you a simple syntax that allows you to easily
complete a task without having to worry about cross browser differences. The library will manipulate appropriate APIs in the background so the functionality will work whatever the browser (in theory). For example, LocalForage is a library for client-side data storage, which provides a simple syntax for storing and retrieving data. In the background, it uses the best API the browser has available for stori...
...And 2 more matches
Setting up your own test automation environment - Learn web development
at this time we've wrapped it inside a function, searchTest(). We've created new browser instances for multiple browsers, then passed each one to the function so the test is performed on all three browsers! Fun huh? Let's move on, look at the basics of WebDriver syntax, in a bit more detail. WebDriver syntax crash course Let's have a look at a few key features of the webdriver syntax. For more
complete details, you should consult the selenium-webdriver JavaScript API reference for a detailed reference, and the Selenium main documentation's Selenium WebDriver and WebDriver: Advanced Usage pages, which contain multiple examples to learn from written in different languages. Starting a new test To start up a new test, you need to include the selenium-webdriver module like this: const webdriver =...
...y.id('name')); input.sendKeys('Filling in my form'); You can submit key presses that can't be represented by normal characters using properties of the webdriver.Key object. For example, above we used this construct to tab out of the form input before submitting it: driver.sleep(1000).then(function() { driver.findElement(By.name('q')).sendKeys(webdriver.Key.TAB); }); Waiting for something to
complete There are times where you'll want to make WebDriver wait for something to
complete before carrying on. For example if you load a new page, you'll want to wait for the page's DOM to finish loading before you try to interact with any of its elements, otherwise the test will likely fail. In our google_test.js test for example, we included this block: driver.sleep(2000).then(function() { driver.
...ened, to make sure that you don't end up with loads of rogue browser instances open on your machine! This is done using the quit() method. Simply call this on your driver instance when you are finished with it. Add this line to the bottom of your quick_test.js test now: driver.quit(); When you run it, you should now see the test execute and the browser instance shut down again after the test is
complete. This is useful for not cluttering up your computer with loads of browser instances, especially if you have so many that it is causing the computer to slow down. Test best practices There has been a lot written about best practices for writing tests. You can find some good background information at Test Design Considerations. In general, you should make sure that your tests are: Using good l...
...And 2 more matches
Eclipse CDT
Therefore, it is not recommended for use if your machine only has 4 GB of RAM. ...
...Therefore, it is not recommended for use if your machine only has 4 GB of RAM. Installing Eclipse Regarding llvm4eclipsecdt, do not install or select this toolchain for Mozilla development. ...
...se.ini that lives alongside the eclipse binary. Set an initial heap space of 1 GB and max heap space of 5 GB, say, by modifying the values of the following two lines in eclipse.ini: -Xms1G -Xmx5G If you fail to increase these limits, then you will likely find that Eclipse either hangs when it tries to index the Mozilla source or else that the code intelligence is very broken after the indexing "
completes". Express setup For the Eclipse indexer to work well you must first build Mozilla, so that it includes headers from the objdir etc. These can be found and processed by Eclipse. Note: Your MOZ_OBJDIR must be outside the Mozilla source directory. Once your build is
complete, mach can then generate a useful Eclipse project on your behalf. First, make sure that the directory of Eclipse's eclip...
...And 2 more matches
NSS FAQ
For an overview of NSS, see Overview of NSS. For detailed information on the open-source NSS project, see NSS Project Page. ...
...s from Red Hat, and other products. For an overview of NSS, see Overview of NSS. For detailed information on the open-source NSS project, see NSS Project Page. What can I do with NSS? Is NSS appropriate for my application? If you want add support for SSL, S/MIME, or other Internet security standards to your application, you can use Network Security Services (NSS) to do so. Because NSS provides
complete support for all versions of SSL and TLS, it is particularly well-suited for applications that need to communicate with the many clients and servers that already support the SSL protocol. The PKCS #11 interface included in NSS means that your application can use hardware accelerators on the server and smart cards for two-factor authentication. How does NSS compare to OpenSSL? OpenSSL is an op...
...bugs that were never fixed, doesn't support TLS or or the new 56-bit export cipher suites, and does not contain the fix to the Bleichenbacher attack on PKCS#1. Netscape no longer maintains SSLRef or makes it available. It was built as an example of an SSL implementation, not for creating production applications. NSS was designed from the ground up for use by commercial developers. It provides a
complete software development kit that uses the same architecture used to support security features in many client and server products from Netscape and other companies. What platforms and development environments are supported? This section is out of date iPlanet E-Commerce Solutions has certified NSS 3.1 on 18 platforms, including AIX 4.3, HP-UX 11.0, Red Hat Linux 6.0, Solaris (2.6 or later), Window...
...And 2 more matches
Animated PNG graphics
riate. Structure An APNG stream is a normal PNG stream as defined in the PNG Specification, with three additional chunk types describing the animation and providing additional frame data. To be recognized as an APNG, an 'acTL' chunk must appear in the stream before any 'IDAT' chunks. The 'acTL' structure is described below. Conceptually, at the beginning of each play the output buffer must be
completely initialized to a fully transparent black rectangle, with width and height dimensions from the 'IHDR' chunk. The default image may be included as the first frame of the animation by the presence of a single 'fcTL' chunk before 'IDAT'. Otherwise, the default image is not part of the animation. Subsequent frames are encoded in 'fdAT' chunks, which have the same structure as 'IDAT' chunks, except...
...G_DISPOSE_OP_PREVIOUS The frame's region of the output buffer is to be reverted to the previous contents before rendering the next frame. If the first 'fcTL' chunk uses a dispose_op of APNG_DISPOSE_OP_PREVIOUS it should be treated as APNG_DISPOSE_OP_BACKGROUND. blend_op<code> specifies whether the frame is to be alpha blended into the current output buffer content, or whether it should
completely replace its region in the output buffer. Valid values for <code>blend_op are: Value Constant Description 0 APNG_BLEND_OP_SOURCE All color components of the frame, including alpha, overwrite the current contents of the frame's output buffer region. 1 APNG_BLEND_OP_OVER The frame should be composited onto the output buffer based on its alpha, using ...
... frame the two blend modes are functionally equivalent due to the clearing of the output buffer at the beginning of each play. The 'fcTL' chunk corresponding to the default image, if it exists, has these restrictions: The x_offset and y_offset fields must be 0. The width and height fields must equal the corresponding fields from the 'IHDR' chunk. As noted earlier, the output buffer must be
completely initialized to fully transparent black at the beginning of each play. This is to ensure that each play of the animation will be identical. Decoders are free to avoid an explicit clear step as long as the result is guaranteed to be identical. For example, if the default image is included in the animation, and uses a blend_op of APNG_BLEND_OP_SOURCE, clearing is not necessary because the entire o...
...And 2 more matches
Embedded Dialog API
it must be allowed to create additional windows at times perhaps unexpected by the containing appliction. These new windows can be entire new browser windows opened in response to web page script, or dialogs or alerts which may arise from script or merely during normal operation of the browser. Part of Gecko's embedding API is callbacks into the embedding application for creating new windows. The
complete windowing portion of the API is large and complex, but it need not be entirely implemented. Its simplest requirements are that the app must allow Gecko to create new browser windows and new simple, empty windows. Gecko can use the latter to pose dialogs built from XUL. XUL dialogs are part of the Gecko package; they are the default dialog posing mechanism. Many embedding applications will find th...
... XUL dialogs are very configurable, they will not behave and probably not look precisely like dialogs which the application builds for itself, independently of Gecko. Applications which implement merely the simplest, base Gecko windowing API will then have a mixture of XUL and native windows. Applications concerned with presenting a consistent dialog appearance have the option of implementing the
complete dialog posing API. Responsibilities of the embedding application Basic Windowing API To be able to respond to script requests to open new windows, an embedded Gecko browser must have a way of opening new windows. This is accomplished using a callback into the embedding application. This basic API will by itself provide the minimal functionality Gecko needs to create new windows, and an embedding...
...mbedded Gecko browser must have a way of opening new windows. This is accomplished using a callback into the embedding application. This basic API will by itself provide the minimal functionality Gecko needs to create new windows, and an embedding application must implement at least this much. Applications concerned with a consistent overall dialog appearance will probably choose to implement the
complete API as well. An embedding application must implement the nsIWindowCreator nsIWindowCreator interface and hand off a reference to the implementation to the WindowCreator service during application initialization. An example of this can be found in the MFC embedding testbed application, in the method CMfcEmbedApp::InitializeWindowCreator (lxr link accurate at revision 1.20 of that file; search for...
...And 2 more matches
Using the Places history service
ocshell when visiting and rendering pages. nsIGlobalHistory3: Adds extra functions for dealing with redirects and hints for rendering (gecko flags). nsIBrowserHistory: Adds functions used by the basic browser like marking pages as typed in the URL bar, and removing pages as from the history interface. nsINavHistoryService: Complex query functions, more fine-grained getters and setters. nsIAuto
CompleteSearch: URL-bar auto
complete from history From 1.9.1 (Firefox3.1) on, don't use any Places service on (or after) quit-application has been notified, since the database connection will be closed to allow the last sync, and changes will most likely be lost. Use quit-application-granted instead. Differences from previous implementations The previous nsGlobalHistory service stored one entry for ea...
...es in the history view to be easily computed. ...
...e easily computed. ...
...And 2 more matches
Observer Notifications
e missing. Use only if your observer must be called before asyncOpen returns. http-on-examine-response Called after a response has been received from the web server. Headers are available on the channel. The response can be accessed and modified via nsITraceableChannel. http-on-examine-cached-response Called instead of http-on-examine-response when a response will be read
completely from the cache. Headers are available on the channel. http-on-examine-merged-response Called instead of http-on-examine-response when a response will be read partially from cache, and partially from the network (HTTP 206 or 304 response). Headers are available on the channel. Cookies These topics indicate whenever a cookie has been changed (added, changed, cleared, or delete...
...ification null Sent when the computer is waking up. Login Manager This topic indicates when actions related to the Login Manager occur. Topic Data Description passwordmgr-found-form noAutofillForms A login is available for this form, but autofill of forms is disabled, so the form was not automatically filled out. passwordmgr-found-form auto
completeOff A login is available for this form, but auto
complete is disabled. passwordmgr-storage-changed addLogin A login has been added to the Login Manager's database. The notification's subject is the login that was added to the database. passwordmgr-storage-changed removeLogin A login was removed from the Login Manager's database. The notification's subject is the log...
...en removed from the Login Manager's database. passwordmgr-storage-changed hostSavingEnabled Host saving has been enabled. passwordmgr-storage-changed hostSavingDisabled Host saving has been disabled. Places This topic indicates when actions related to Places (the history and bookmarks database) occur. Topic Data Description places-auto
complete-feedback-updated Sent when Places updates the location bar's autocompletion display. places-connection-closed Sent after Places has closed its database connection. Once this has been sent, no Places features will work. places-connection-closing Sent as the last notification before the Places service closes its database connection. Warning: This is ...
...And 2 more matches
IAccessibleText
passed, [out] value is null. S_OK. textAfterOffset() Returns a text() portion after the given position. Returns the substring of the specified text() type that is located after the given character and does not include it. The result of this method should be same as a result for textAtOffset() with a suitably increased index value. For example, if text() type is ::IA2_TEXT_BOUNDARY_WORD, then the
complete word that is closest to and located after offset is returned. If the index is valid, but no suitable word (or other text() type) is found, a null pointer is returned. [propget] HRESULT textAfterOffset( [in] long offset, [in] enum IA2TextBoundaryType boundaryType, [out] long startOffset, [out] long endOffset, [out] BSTR text ); Parameters offset Index of the character for which to retu...
...long offset, [in] enum IA2TextBoundaryType boundaryType, [out] long startOffset, [out] long endOffset, [out] BSTR text ); Parameters offset Index of the character for which to return the text() part before it. The index character will not be part of the returned string. The valid range is 0..length. boundaryType The type of the text() portion to return. See ::IA2TextBoundaryType for the
complete list. startOffset 0 based offset of first character. endOffset 0 based offset of one past the last character. text Returns the requested text() portion. This portion may be empty or invalid when no appropriate text() portion is found or text() type is invalid. Return value E_INVALIDARG if bad [in] passed, [out] values are 0s and null respectively. S_FALSE if the requested boundary type is not im...
...long offset, [in] enum IA2TextBoundaryType boundaryType, [out] long startOffset, [out] long endOffset, [out] BSTR text ); Parameters offset Index of the character for which to return the text() part before it. The index character will not be part of the returned string. The valid range is 0..length. boundaryType The type of the text() portion to return. See ::IA2TextBoundaryType for the
complete list. startOffset 0 based offset of first character. endOffset 0 based offset of one past the last character. text Returns the requested text() portion. This portion may be empty or invalid when no appropriate text() portion is found or text() type is invalid. Return value E_INVALIDARG if bad [in] passed, [out] values are 0s and null respectively. S_FALSE if the requested boundary type is not im...
...And 2 more matches
nsILoginManager
nderbird 3.1 / Fennec 1.0) Replaces nsIPasswordManager which was used in older versions of Gecko. Implemented by: @mozilla.org/login-manager;1. ...
...ec 1.0) Replaces nsIPasswordManager which was used in older versions of Gecko. Implemented by: @mozilla.org/login-manager;1. ...
...d in older versions of Gecko. Implemented by: @mozilla.org/login-manager;1. ...
...And 2 more matches
nsIWebProgressListener
ag 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 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 ...
...r example images and stylesheets) are considered normal requests. STATE_IS_DOCUMENT 0x00020000 This flag indicates that the state transition is for a document request. This flag is set in addition to STATE_IS_REQUEST. A document request supports the nsIChannel interface and its loadFlags attribute includes the nsIChannel::LOAD_DOCUMENT_URI flag. A document request does not
complete until all requests associated with the loading of its corresponding document have
completed. This includes other document requests (for example corresponding to HTML <iframe> elements). The document corresponding to a document request is available via the DOMWindow attribute of onStateChange()'s aWebProgress parameter. STATE_IS_NETWORK 0x00040000 This flag indicates that the s...
...indows, starts and stops. STATE_IS_WINDOW 0x00080000 This flag indicates that the state transition corresponds to the start or stop of activity in the indicated nsIWebProgress instance. This flag is accompanied by either STATE_START or STATE_STOP, and it may be combined with other State Type Flags. This flag is similar to STATE_IS_DOCUMENT. However, when a document request
completes, two onStateChange() calls with STATE_STOP are generated. The document request is passed as aRequest to both calls. The first has STATE_IS_REQUEST and STATE_IS_DOCUMENT set, and the second has the STATE_IS_WINDOW flag set (and possibly the STATE_IS_NETWORK flag set as well -- see above for a description of when the STATE_IS_NETWORK flag may be set). This second STATE_STOP event may be useful as ...
...And 2 more matches
Mail composition back end
the appropriate locations after delivery (i.e. a "Sent" folder) as well as the ability to store messages for features like "Drafts" and "Templates". Several (but not all) of these interfaces are specified in IDL. This will change in the coming weeks and allow for developers to write JavaScript to take advantage of the back end services. Also, I will talk about some features though they may not be
complete as of yet. I will try to make comments for these exceptions. Sending Messages The primary responsibility of the back end is for the creation and sending of RFC822 messages. The interface that accomplishes this task is the nsIMsgSend interface. The feedback mechanism is provided by a nsIMsgSendListener which is implemented by the caller. The caller has the ability to add or ...
...o implement the nsIMsgCopyServiceListener interface if it wants to be notified of the progress 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 o...
... OnStatus The OnStatus gives the listener status updates for the current operation. NS_IMETHOD OnStatus(const char *aMsgID, - the message ID for the message being sent const PRUnichar *aMsg) = 0; - a message concerning the status of the send operation OnStopSending The OnStopSending interface is called when the sending operation has
completed. This will be called in the case of both success and failure. NS_IMETHOD OnStopSending(const char *aMsgID, - the message ID for the message being sent nsresult aStatus, - the resulting status for the send operation const PRUnichar *aMsg, - a message concerning the status of the send operation nsIFileSpec *r...
...And 2 more matches
Debugger.Frame - Firefox Developer Tools
gger.Frame instances.) Push a "debugger" frame on the stack, witholder as its older property. Invoke the debuggee code as appropriate for the given invocation function, with the "debugger" frame as its continuation. For example, Debugger.Frame.prototype.eval pushes an "eval" frame for code it runs, whereas Debugger.Object.prototype.call pushes a "call" frame. When the debuggee code
completes, whether by returning, throwing an exception or being terminated, pop the "debugger" frame, and return an appropriate completion value from the invocation function to the debugger. When a debugger calls an invocation function to run debuggee code, that code's continuation is the debugger, not the next debuggee code frame. Pushing a "debugger" frame makes this continuation explicit, and makes...
...preter. "baseline": a frame running in the unoptimizing, baseline JIT. "ion": a frame running in the optimizing JIT. "wasm": a frame running in WebAssembly baseline JIT. this The value of this for this frame (a debuggee value). For a wasmcall frame, this property throws a TypeError. older The next-older visible frame, in which control will resume when this frame
completes. If there is no older frame, this is null. depth The depth of this frame, counting from oldest to youngest; the oldest frame has a depth of zero. live True if the frame this Debugger.Frame instance refers to is still on the stack; false if it has
completed execution or been popped in some other way. script The script being executed in this frame (a Debugger.Script instance), or null on fra...
...maining debuggers' onStep handlers do not run. This property is ignored on frames that are not executing debuggee code, like "call" frames for calls to host functions and "debugger" frames. onPop This property must be either undefined or a function. If it is a function, SpiderMonkey calls it just before this frame is popped, passing a completion value indicating how this frame's execution
completed, and providing this Debugger.Frame instance as the this value. The function should return a resumption value indicating how execution should proceed. On newly created frames, this property's value is undefined. When this handler is called, this frame's current execution location, as reflected in its offset and environment properties, is the operation which caused it to be unwound. In frames re...
...And 2 more matches
All keyboard shortcuts - Firefox Developer Tools
Esc Step forward through properties and values Tab Tab Tab Step backward through properties and values Shift + Tab Shift + Tab Shift + Tab Start editing property or value (Rules view only, when a property or value is selected, but not already being edited) Enter or Space Return or Space Enter or Space Cycle up and down through auto-
complete suggestions (Rules view only, when a property or value is being edited) Up arrow , Down arrow Up arrow , Down arrow Up arrow , Down arrow Choose current auto-
complete suggestion (Rules view only, when a property or value is being edited) Enter or Tab Return or Tab Enter or Tab Increment selected value by 1 Up arrow Up arrow Up arrow Decrement ...
...nitiating reverse search) Shift + F9 Ctrl + S Shift + F9 Move to the beginning of the line Home Ctrl + A Ctrl + A Move to the end of the line End Ctrl + E Ctrl + E Execute the current expression Enter Return Enter Add a new line, for entering multiline expressions Shift + Enter Shift + Return Shift + Enter Auto
complete popup These shortcuts apply while the auto
complete popup is open: Command Windows macOS Linux Choose the current auto
complete suggestion Tab Tab Tab Cancel the auto
complete popup Esc Esc Esc Move to the previous auto
complete suggestion Up arrow Up arrow Up arrow Move to the next auto
complete suggestion Down arro...
...is open: Command Windows macOS Linux Choose the current auto
complete suggestion Tab Tab Tab Cancel the auto
complete popup Esc Esc Esc Move to the previous auto
complete suggestion Up arrow Up arrow Up arrow Move to the next auto
complete suggestion Down arrow Down arrow Down arrow Page up through auto
complete suggestions Page up Page up Page up Page down through auto
complete suggestions Page down Page down Page down Scroll to start of auto
complete suggestions Home Home Home Scroll to end of auto
complete suggestions End End End Style Editor Command Windows macOS Linux Open the Style Editor Shift + F7 ...
...And 2 more matches
HTMLInputElement - Web APIs
ng the files selected for upload. webkitdirectory Boolean: Returns the webkitdirectory attribute; if true, the file system picker interface only accepts directories instead of files. webkitEntries Array of FileSystemEntry objects: Describes the currently selected files or directories. ...
...ctory Boolean: Returns the webkitdirectory attribute; if true, the file system picker interface only accepts directories instead of files. webkitEntries Array of FileSystemEntry objects: Describes the currently selected files or directories. ...
...icker interface only accepts directories instead of files. webkitEntries Array of FileSystemEntry objects: Describes the currently selected files or directories. Properties that apply only to text/number-containing or elements auto
complete string: Returns / Sets the element's auto
complete attribute, indicating whether the value of the control can be automatically
completed by the browser. ...
...And 2 more matches
IDBDatabase.transaction() - Web APIs
ed to open the object store in readwrite mode to change data, you would use the following: var transaction = db.transaction('my-store-name', "readwrite"); As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702), which is the same behaviour as other IndexedDB-supporting browsers. ...
...ction = db.transaction('my-store-name', "readwrite"); As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702), which is the same behaviour as other IndexedDB-supporting browsers. Previously in a readwrite transaction IDBTransaction.on
complete was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the
complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The
complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare mo...
...st if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further. Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the
complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config. details Optional Dictionary of other settings, supported only by Chrome: Return value An IDBTransaction object. Exceptions This method may rais...
...And 2 more matches
PaymentResponse.retry() - Web APIs
will vary depending on the payment used. For example, if the user chose to pay by credit card using the basic-card payment method, this is a BasicCardErrors object. shippingAddress Optional An AddressErrors object which contains error messages for any of the fields in the shipping address that failed validation. Return value A Promise which is resolved when the payment is successfully
completed. The promise is rejected with an appropriate exception value if the payment fails again. Typically you will use this by calling show(), then entering a loop or recursive function that checks the PaymentResponse for errors or other reasons to retry the payment request. If a retry is needed, the loop calls retry(), then loops back to check the response when it comes in. The loop exits only when t...
...e, 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 and acceptable, call
complete("success") to finalize the payment and proces it. If show() is rejected, the payment request failed, usually because either there's already one being processed, because the user agent doesn't support any of the specified payment methods, or because of a security issue. See t...
... the response's data is valid and acceptable, call
complete("success") to finalize the payment and proces it. If show() is rejected, the payment request failed, usually because either there's already one being processed, because the user agent doesn't support any of the specified payment methods, or because of a security issue. See the list of exceptions for show() for further details. Call
complete("fail") to close the payment request. ...
...And 2 more matches
RTCPeerConnection: icegatheringstatechange event - Web APIs
ler on an RTCPeerConnection when the state of the ICE candidate gathering process changes. This signifies that the value of the connection's iceGatheringState property has changed. When ICE firststarts to gather connection candidates, the value changes from new to gathering to indicate that the process of collecting candidate configurations for the connection has begun. ...
...This also indicates that collection of candidates is finished. ...
...transports that make up the RTCPeerConnection have finished gathering ICE candidates. Bubbles No Cancelable No Interface Event Event handler onicegatheringstatechange Note: While you can determine that ICE candidate gathering is
complete by watching for icegatheringstatechange events and checking for the value of iceGatheringState to become
complete, you can also simply have your handler for the icecandidate event look to see if its candidate property is null. This also indicates that collection of candidates is finished. Examples This example creates a handler for icegatheringstatechange events. pc.onicegatheringstatechange = ev => { let connection = ev.target; switch(connection.iceGatheringState) { case "gathering": /* c...
...And 2 more matches
Inputs and input sources - Web APIs
pads in WebXR applications for more detailed information. Profile strings Each input source can have zero or more input profile name strings, found in the array profiles, each of which describes a preferred visual representation of the input source within the 3D world as well as how the input source functions. The use of these profiles is briefly described under Input profiles below, and a more
complete guide may be found in our article Using WebXR input profiles. Transient input sources Some devices may create transient input sources to be used in tandem with an action which doesn't really come from that device, but is being presented as if it is. For example, if an XR device provides a mode in which the mouse is used to simulate events on the device, a new XRInputSource object might be creat...
...The event is delivered as an XRInputSourceChangeEvent, which includes three properties of interest: session The XRSession for which the input sources have changed. added An array of zero or more XRInputSource objects indicating the input sources that have been newly added to the XR system...
...ou might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when selectstart arrives and stopping when selectend is received. The select event, on the other hand, is the event that tells your code that the user has
completed the action they want to
complete. This might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing an object that they were dragging around the world back down again in a new location. If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the selectstart and selecten...
...And 2 more matches
ARIA Test Cases - Accessibility
If the currently selected option is changed the new option should be spoken whether the list is open or closed. When the combo box is opened or closed, the new open/closed state should be spoken. Markup used: Notes: Results: AT Firefox IE Opera Saf...
... to distinguish it from others that may be draggable, but are currently not selected for the operation. (AL) I'm not sure if there is a way for the screen reader to know when something has been marked for drag & drop. Target nodes where the item can be dropped should be indicated from now on when they receive focus or arrowing onto them with the virtual cursor. After drag and drop operation has
completed, the new location of the item should be indicated in the virtual buffer representation. If the drag and drop operation caused a menu to open, focus should be tracked in that menu, and the user should be able to
complete further interaction via the keyboard as usual. Optional but desired: AT should provide simple method to navigate only among the current drop targets. Markup used: aria-grab...
...oiceOver (Leopard) n/a n/a - fail Window-Eyes - - - - NVDA - n/a - - Zoom (Leopard) pass n/a pass pass ZoomText - - - - Orca - - - - Property-Only Test Cases These testcases involve ARIA properties used to enhance HTML controls (as opposed to JavaScript-built widgets). auto
complete Dojo auto
complete Expected AT Behavior: Screen reader should announce the fact that this is a control supporting auto
complete. When suggestions appear, if the AT supports it elsewhere in the operating system (e. g. the Run dialog), suggestions should be supported inside the web app as well. Screen magnifiers should indicate Auto
Completes as they do elsewhere in the operating system. Opt...
...And 2 more matches
Cognitive accessibility - Accessibility
es, such as depression and schizophrenia. It also includes people with learning disabilities, such as dyslexia and attention deficit hyperactivity disorder (ADHD). Though there is a lot of diversity within clinical definitions of cognitive impairments, people with them experience a common set of functional problems. These problems include difficulty with understanding content, remembering how to
complete tasks, and confusion caused by inconsistent or non-traditional web page layouts. In this document, we focus on steps developers should take to improve the cognitive accessibility of their web sites and applications. Overview Cognitive and intellectual disabilities cover a large spectrum, and may be momentary, temporary, or permanent conditions. For example, dementia and Alzheimer's are permanen...
... WCAG Guidelines WCAG, Web Content Accessibility Guidelines, includes several guidelines to improve cognitive accessibility. These guidelines are published by the Web Accessibility Initiative (WAI) of the World Wide Web Consortium (W3C), the main international standards organization for the Internet. This group is also responsible fo...
...onveyed through the presentation, should be available in a form that can be perceived by all users to achieve this goal. For example, the information could be spoken aloud via a narration tool. Making your content capable of being understood by the software is a good way to help ensure it can be used by alternate presentational modes. Time It is important to allow users the time they require to
complete tasks. Guideline 2.2 states "provide users enough time to read and use content." A time limit is any process that happens without user initiation after a set time or on a periodic basis, such as being logged out after 30 minutes or having 15 minutes to make a purchase. People with cognitive disabilities may require more time to read content, or to perform functions such as filling out forms. Sol...
...And 2 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
drawn list items, so that you can change the highlight color when an item doesn't have focus. For listboxes that are not focused, use a different highlight color, to give the appearance that the listbox is no longer focused -- a lighter color for unfocused lists will also make the listbox state more visually obvious and thus more usable for everyone. For popup listboxes used for dropdowns in auto
complete text fields, change the color value by 1 when the user is typing in the textfield as opposed to arrowing through the list. The listbox will still visually appear to be active, but the screen reader behavior is improved by not echoing too much spoken information for each keypress. One downside to this solution is that means that you cannot use "client data" for the list items, because Windows won'...
... Unfortunately, the MSAA implementation often lags. For example, tree views will probably not be accessible with most assistive technologies even if you have a perfect MSAA implementation. Automatic screen reading of dialog boxes and status bars will often not work just because you're using the wrong class name, even if your MSAA implementation is perfect, and everything else about the objects is
completely normal. Solution: There are three things you can do: 1) try to use the standard class names, 2) pressure the screen reader vendor to fix their MSAA implementation or use better heuristics, and 3) get around the problem with 3rd party scripts for those AT's that can use them. Not all MSAA features utilized by 3rd party vendors Problem: The assistive technology does not use 50% of what's avail...
...t by assistive technology manufacturers. Contact the the top vendors early and often as you plan and implement your architecture, to see what's important to them. Implement only what's needed -- supporting everything would take too long for zero results. Vendor quirks Problem: Because assistive technology tends to utilize MSAA as an additional solution resting on top of old hacks, rather than a
completely clean and separate way to deal with an application, and because of the quirky nature of MSAA and of the inflexible heuristics that screen readers use, we do not have a "plug and play solution". In addition, assistive technology vendors are tiny companies, often scrambling to keep up with changes in the applications they already support, or new products other than yours which they need to suppor...
...And 2 more matches
<input type="email"> - HTML: Hypertext Markup Language
ses are automatically applied as appropriate to visually denote whether the current value of the field is a valid e-mail address or not. On browsers that don't support inputs of type email, a email input falls back to being a standard text input. Value A DOMString representing an e-mail address, or empty Events change and input Supported Common Attributes auto
complete, list, maxlength, minlength, multiple, name,pattern, placeholder, readonly, required, size, and type IDL attributes list and value Methods select() Value The <input> element's value attribute contains a DOMString which is automatically validated as conforming to e-mail syntax. More specifically, there are three possible value formats that will pass validation: A...
...Validation for details on how e-mail addresses are validated to ensure that they're formatted properly. ...
...ype, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored
completely. Tip: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section Pattern validation for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is ...
...And 2 more matches
<textarea> - HTML: Hypertext Markup Language
the form is submitted. rows and cols attributes to allow you to specify an exact size for the <textarea> to take. Setting these is a good idea for consistency, as browser defaults can differ. Default content entered between the opening and closing tags. <textarea> does not support the value attribute. The <textarea> element also accepts several attributes common to form <input>s, such as auto
complete, autofocus, disabled, placeholder, readonly, and required. Attributes This element includes the global attributes. autocapitalize This is a non-standard attribute supported by WebKit on iOS (therefore nearly all browsers running on iOS, including Safari, Firefox, and Chrome), which controls whether and how the text value should be automatically capitalized as it is entered/edited by the u...
...he global attributes. autocapitalize This is a non-standard attribute supported by WebKit on iOS (therefore nearly all browsers running on iOS, including Safari, Firefox, and Chrome), which controls whether and how the text value should be automatically capitalized as it is entered/edited by the user. The non-deprecated values are available in iOS 5 and later. Possible values are: none:
Completely disables automatic capitalization. sentences: Automatically capitalize the first letter of sentences. words: Automatically capitalize the first letter of words. characters: Automatically capitalize all characters. on: Deprecated since iOS 5. off: Deprecated since iOS 5. auto
complete This attribute indicates whether the value of the control can be automatically
completed by t...
...ze all characters. on: Deprecated since iOS 5. off: Deprecated since iOS 5. auto
complete This attribute indicates whether the value of the control can be automatically
completed by the browser. Possible values are: off: The user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically
complete the entry. on: The browser can automatically
complete the value based on values that the user has entered during previous uses. If the auto
complete attribute is not specified on a <textarea> element, then the browser uses the auto
complete attribute value of the <textarea> element's form owner. The form owner is either the <form> element that this <textarea> element is a descendant of or the...
...And 2 more matches
HTTP Index - HTTP
alternative. 2 A typical HTTP session HTTP In client-server protocols, like HTTP, sessions consist of three phases: 3 An overview of HTTP HTML, HTTP, Overview, WebMechanics, l10n:priority HTTP isthe foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A
complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more 4 Basics of HTTP Guide, HTTP, Overview HTTP is a pretty extensible protocol. It relies on a few basic concepts like the notion of resources and URIs, a simple structure of messages, and a client-server structure for the communication flo...
...fying resources. 9 MIME types (IANA media types) Content-Type, Guide, HTTP, MIME Types, Meta, Request header, Response Header, application/javascript, application/json, application/xml A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) is a standard that indicates the nature and format of a document, file, or assortment of bytes. 10 In
complete list of MIME types Audio, File Types, Files, HTTP, MIME, MIME Types, PHP, Reference, Text, Types, Video Here is a list of MIME types, associated by type of documents, ordered by their common extensions. 11 Resource URLs Guide, HTTP, Intermediate, Resource Resource URLs, URLs prefixed with the resource: scheme, are used by Firefox and Firefox browser extensions to lo...
...icy header unoptimized-images directive controls whether the current document is allowed to download and display unoptimized images. 146 Feature-Policy: unsized-media Directive, Feature-Policy, HTTP, Reference The HTTP Feature-Policy header unsized-media directive controls whether the current document is allowed to change the size of media elements after the initial layout is
complete. 147 Feature-Policy: usb Directive, Feature-Policy, HTTP, Reference, Vibration API, Web USB The HTTP Feature-Policy header usb directive controls whether the current document is allowed to use the WebUSB API. 148 Feature-Policy: vibrate Directive, Feature-Policy, HTTP, Reference, Vibration API The HTTP Feature-Policy header vibrate directive controls whet...
...And 2 more matches
Codecs used by WebRTC - Web media technologies
d 68 and later do not support AVC (H.264) anymore. This is due to a change in Google Play store requirements that prevent Firefox from downloading and installing the OpenH264 codec needed to handle H.264 in WebRTC connections. See this article on SUMO for details. For details on WebRTC-related considerations for each codec, see the sub-sections below by following the links on each codec's name.
Complete details of what video codecs and configurations WebRTC is required to support can be found in RFC 7742: WebRTC Video Processing and Codec Requirements. It's worth noting that the RFC covers a variety of video-related requirements, including color spaces (sRGB is the preferred, but not required, default color space), recommendations for webcam processing features (automatic focus, automatic white ...
...r retransmission (RTX), redundant coding (RED), and forward error correction (FEC). If the connection is in the process of starting up, you can use the icegatheringstatechange event to watch for the completion of ICE candidate gathering, then fetch the list. ...
...The method RTCPeerConnection.getSenders() is called to get a list of all the RTCRtpSender objects used by the connection. ...
...And 2 more matches
SVG documentation index - SVG: Scalable Vector Graphics
ry! 10 Replaced Element SVG This page was auto-generated because a user created a sub-page to this page. 11 SVG 1.1 Support in Firefox Firefox, SVG You can find some basic examples of SVG syntax and usage in the W3C SVG test suite. 12 SVG 2 support in Mozilla Firefox, SVG SVG 2 is the next major version of the SVG standard, which is a
complete rework of the SVG 1.2 draft. 13 SVG Attribute reference Drawing, Landing, NeedsHelp, Overview, Responsive Design, SVG, SVG Attribute, SVG Reference, Vector Graphics SVG elements can be modified using attributes that specify details about exactly how the element should be handled or rendered. 14 SVG Conditional Processing Attributes Intermediate, NeedsExample, P...
...r Graphics, SVG, is a W3C XML dialect to mark up graphics. It is partially implemented in Firefox, Opera, WebKit browsers, Internet Explorer and other browsers. 271 Basic Transformations Intermediate, SVG, SVG:Tutorial Now we're ready to start distorting our beautiful images. But first, let's formally introduce the <g> element. ...
...However, since they're used in most SVG documents, it's necessary to give them some sort of introduction. 273 Clipping and masking Advanced, SVG, SVG:Tutorial Erasing part of what one has created might at first sight look contradictory. ...
...And 2 more matches
Examples and demos from articles - Archive of obsolete content
[article] Typewriter 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. ...
...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
completely scrolled an element or not. [article] CSS Pure-CSS dropdown menu [html] With the :hover pseudo-class you can create complex cascade algorithms. This is a common technique used, for example, in order to create pure-CSS dropdown menus (that is only CSS, without using JavaScript). .[article] Pure-CSS web gallery based on the :hover pseudoclass [zip] You can use the :hover pseudo-class in o...
... [html] This example shows how it's possible to simulate an editable <select> through a fieldset of radioboxes and textboxes. [article] Expandable elements [html] This example shows how it is possible to show/hide classes of elements in pure CSS. In this demo there is also an example of a "toggle button" rendered through a <label> element. [article] Code snippets and tutorials JavaScript
Complete cookies reader/writer with full unicode support This little framework consists of a
complete cookies reader/writer with unicode support. XML to JSON conversion snippets (JXON) JXON (lossless JavaScript XML Object Notation) is a generic name by which is defined the representation of JavaScript Objects using XML. There are no real standards for this conversion, but some conventions begin to appe...
...changed since last visit Here is a possible example of how to show an alert message when current document changes. Do something if an external page has changed since last visit Here is a possible example of how to show an alert message when an external page changes. Import scripts Here is a possible example of how to dynamically import scripts with JavaScript. CSS CSS Tutorial Aimed at
complete beginners, this CSS tutorial for beginners introduces you to Cascading Style Sheets (CSS). It guides you through the basic features of the language with practical examples that you can try for yourself on your own computer and illustrates the standard features of CSS that work in modern browsers. Dropdown menus rules How to create pure-CSS dropdown menus. ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
in dist/bin/extensions/myextension@mycompany.com/. A lot of this stuff won't get created on this first pass since make will gag when it doesn't find the source files for your components. Don't worry about this; all you need are the generated header files that contain the C++ implementation stubs. Go back and flesh out the C++ implementation of your components so that the build can
complete next time. Remember that you should never, ever modify any of these generated files. Always modify the files used to generate them and rerun make. If you're changing the generated files directly, you're probably doing something wrong. The process of walking the entire Mozilla tree takes a long time. If you already have a Mozilla build, you can avoid this by creating a makefile for your ext...
...e manifest file called chrome.manifest instead of creating separate manifests with goofy names for each package. Now launch make again, and you should see a chrome subdirectory appear in your extension (/mozilla/$(MOZ_OBJDIR)/dist/bin/extensions/myextension@mycompany.com/). Note that the chrome directory contains a JAR (i.e. ZIP) file with all the chrome files listed in jar.mn as well as a
complete directory structure mirroring that of the JAR file. The directory structure, however, is empty. Why? I don't know. Don't worry about this, the files in the JAR are the ones that are actually used. Keeping it Complex If you're developing a really complex extension with lots of XPCOM components, you'll probably want to divide your code up into smaller modules. Kinda, Sorta Comp...
... your code up into smaller modules. Kinda, Sorta Complex Extensions For a moderately complex extension, it's probably enough just to subdivide the code into a single level of modules. Let's assume that you have a base/ module that defines a bunch of basic XPCOM components and an advanced/ module that defines some chrome as well as other components that use the basic components. Your
complete directory structure will look something like this: myextension/ base/ public/ src/ advanced/ content/ locale/ en-US/ ...other locales.../ public/ skin/ classic/ ...other skins.../ src/ Other than that, nothing really changes. The makefiles in the base/ and advanced/ direct...
...ced.cpp \ $(NULL) include $(topsrcdir)/config/rules.mk LOCAL_INCLUDES += \ -I$(srcdir)/../intricate/src \ -I$(srcdir)/../multifarious/src \ $(NULL) The makefile in the advanced/ directory should list the intricate/, multifarious/ and build/ directories in its DIRS variable. Make sure that build/ comes last since it can't create the component library until the other makefiles have
completed. Other Topics Adding Data Files to Your Extensions In some cases, you may wish to include additional files in your extension that don't belong in the chrome/ subdirectory. Examples might be database files or XML schemas. This can be achieved by adding a custom step to your makefile that copies the files from the source tree into the extension's target directory. Copyi...
Enhanced Extension Installation - Archive of obsolete content
ension so that the Component Manager, Preferences System and Chrome Registry can locate additional files on the next start. The finalization process then notifies the startup process that finalization has changed this manifest, and that the application must be restarted to pick up changes specified therein. The startup process receives this "needsRestart" bit when the Extension manager's startup
completes, shuts down XPCOM and relaunches the application. On the next restart, the XREDirProvider now supplies a list of directories to requesting systems listing the new item's components, defaults and chrome manifests. Uninstallation, Disabling, Enabling These functions work on the same principle as installation - the user requests an action through the UI while the application is running and metada...
...above, e.g. when an item is being installed from a XPI file from the web or from a drop in) the Extension System checks to see if there is an existing version installed, and if so a special routine is called which sets a toBeUpgraded flag on the configured item instead of the usual toBeInstalled flag. On the subsequent startup, this function causes metadata about the old version of the item to be
completely removed from the Extensions datasource and the new data from the Install Manifest of the upgrade copied in, to avoid duplicate assertions. After the Upgrade finalization routine executes, it unsets the toBeUninstalled flag and sets the toBeInstalled flag to trigger the item's files to be replaced from the staged XPI. When an item's files are extracted, a special extraction routine known as a s...
...pecify that their item does not show up in the Extensions UI by using the <em:hidden>true<em:hidden> property in their Install Manifests. This property is ignored for Extensions installed into unrestricted locations, such as the profile location, to prevent abuse. There is more logging for failures in the installation and update process. The set of error logs written is still neither perfect nor
complete, but it's a very good start. Log strings are written to the application's error console (in anticipation of that API automatically logging to a file) and to the terminal window. We now check more effectively for system integrity during startup. We ask each Install Location if it is functioning (for a Directory Install location such as app-profile or app-global the location is functioning if it t...
...Firefox 1.0 which could leave the user in bogus states. The nsIExtensionManager interface now has a single, unified set of installation/enabling interfaces: void installItemFromFile(in nsIFile file, in string locationKey); void uninstallItem(in string id); void enableItem(in string id); void disableItem(in string id); Uninstall logs are no longer written, since the item folder is removed
completely on uninstall. Benjamin Smedberg's recent Chrome Registry changes made it unnecessary to have log entries for chrome registration, so the Uninstall log was only being used for file additions. This allows for the removal of the InstallLogReader/Writer objects in the Extension Manager. It is possible to order Install Locations using the priority property on an Install Location object. This determ...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
art (top or left), center, end (bottom or right), or stretch (extend this element to match the element with the greatest height or width). The align attribute is defined as operating in the axis perpendicular to the orient attribute, while the pack attribute operates along the same axis as the orient attribute. Figure 2 shows how setting align="center" pack="start" on two elements will result in
completely different output with the only difference being the value for orient. <box flex="1" align="end" pack="end"> <button label="Happy"/> <button label="Sad"/> </box> Listing 2: How align and pack respond to orient Figure 2: Output from listing 2 flex Elements ordinarily have fixed height and width. The flex attribute indicates that an element should be expanded to take up all of a window'...
...ord-entry field, in which characters are hidden as they're typed. Every character entered into a textbox generates an input event. If you use the oninput event handler, you can implement commands that reflect user input in real time. <vbox align="start"> <textbox/> <textbox multiline="true" rows="5" cols="15"/> </vbox> Listing 16: textbox examples Figure 13: Output from Listing 16 Auto
complete Adding type="auto
complete" to a textbox element enables an automatic completion function for it. Note that to actually use this function, you must also specify a search target for the auto
complete text using the auto
completesearch attribute. If you want to use the Location Bar history, set the value for this to history; if you want it to be the Search Bar history, use search-history; and if you...
... Menu List Use the menulist element to create a control for making selections from a drop-down list. As shown in Listing 17, this is implemented in combination with the menupopup element; it produces output as shown in Figure 14. ...
...and includes the ability to prevent scripts in embedded frames from accessing outside the frame. For building applications linked to external web pages, this is a more secure and more convenient approach. The tabbrowser element is even more capable than the browser element because it includes the basic tab-handling features from Firefox. To use this requires XPConnect privileges, the same as auto
complete does; this will be covered in Chapter 4. Opening a page If you specify a URI value for the src attribute in the browser element, that URI will be opened by default. If the src attribute's value changes, you can dynamically open a different web page or XUL document. Functions like Back, Forward, Reload can all be called using the goBack(), goForward(), and reload() methods. Using the stop() met...
jspage - Archive of obsolete content
d=true; window.fireEvent("domready");document.fireEvent("domready");};window.addEvent("load",b);if(Browser.Engine.trident){var a=document.createElement("div"); (function(){($try(function(){a.doScroll();return document.id(a).inject(document.body).set("html","temp").dispose();}))?b():arguments.callee.delay(50);})(); }else{if(Browser.Engine.webkit&&Browser.Engine.version<525){(function(){(["loaded","
complete"].contains(document.readyState))?b():arguments.callee.delay(50); })();}else{document.addEvent("DOMContentLoaded",b);}}})();var JSON=new Hash(this.JSON&&{stringify:JSON.stringify,parse:JSON.parse}).extend({$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(a){return JSON.$specialChars[a]||"\\u00"+Math.floor(a.charCodeAt()/16).toStrin...
...ions.duration.toInt();var b=this.options.wait;if(b===false){this.options.link="cancel"; }},getTransition:function(){return function(a){return -(Math.cos(Math.PI*a)-1)/2;};},step:function(){var a=$time();if(a<this.time+this.options.duration){var b=this.transition((a-this.time)/this.options.duration); this.set(this.compute(this.from,this.to,b));}else{this.set(this.compute(this.from,this.to,1));this.
complete();}},set:function(a){return a;},compute:function(c,b,a){return Fx.compute(c,b,a); },check:function(){if(!this.timer){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.bind(this,arguments)); return false;}return false;},start:function(b,a){if(!this.check(b,a)){return this;}this.from=b;this.to=a;this.time=0;this.transition=this.getTrans...
...{return Fx.compute(c,b,a); },check:function(){if(!this.timer){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.bind(this,arguments)); return false;}return false;},start:function(b,a){if(!this.check(b,a)){return this;}this.from=b;this.to=a;this.time=0;this.transition=this.getTransition(); this.startTimer();this.onStart();return this;},
complete:function(){if(this.stopTimer()){this.on
Complete();}return this;},cancel:function(){if(this.stopTimer()){this.onCancel(); }return this;},onStart:function(){this.fireEvent("start",this.subject);},on
Complete:function(){this.fireEvent("
complete",this.subject);if(!this.callChain()){this.fireEvent("chain
Complete",this.subject); }},onCancel:function(){this.fireEvent("cancel",this.subject).clearChain();}...
...nse={text:null,xml:null};this.failure();}},isSuccess:function(){return((this.status>=200)&&(this.status<300)); },processScripts:function(a){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return $exec(a);}return a.stripScripts(this.options.evalScripts); },success:function(b,a){this.onSuccess(this.processScripts(b),a);},onSuccess:function(){this.fireEvent("
complete",arguments).fireEvent("success",arguments).callChain(); },failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("
complete").fireEvent("failure",this.xhr);},setHeader:function(a,b){this.headers.set(a,b); return this;},getHeader:function(a){return $try(function(){return this.xhr.getResponseHeader(a);}.bind(this));},check:function(){if(!this.running){return true; }switch(this.opt...
Monitoring downloads - Archive of obsolete content
If the download's state, indicated by the aDownload.state field, is Components.interfaces.nsIDownloadManager.DOWNLOAD_DOWNLOADING, the file has begun to download. The aDownload object is an nsIDownload object. In that case, we create a new row in our database for the new file by opening the database and building a REPLACE INT...
...he new file by opening the database and building a REPLACE INTO sqlite command. The first three rows are set to the values of the source URI, file size, and start time fields from the download object. The remaining rows are set to zeroes since that's not information we have at the moment. If the download's state indicates that the download is finished, canceled, or failed, we call our logTransfer
Completed routine to update the log to indicate that state change. That code looks like this: logTransfer
Completed: function(aDownload) { var endTime = new Date(); // Current time is the end time // Issue the REPLACE sqlite command to update the record. We find a // record for the same source URI and start time, then update the end // time, size, and speed entries in...
...By looking for a record with both the same URI and start time, we properly support the case where the user downloads the same file multiple times. Displaying the download log The download log window's code is encapsulated in an object called downloadlogger_dlwindow. Since this is a simple example, it's a one-shot log window; it doesn't monitor for further changes t...
....toFixed(1) + "KB/sec"); cell.setAttribute("style", "text-align:right"); row.appendChild(cell); var status = statement.getInt32(5); var style = "color:black"; cell = document.createElement('listcell'); var statusStr; switch(status) { case 0: statusStr = "Downloading"; break; case 1: statusStr = "
Complete"; style = "color:green"; break; case 2: statusStr = "Failed"; style = "color:red"; break; case 3: statusStr = "Canceled"; style = "color:purple"; break; case 4: statusStr = "Paused"; style = "color:blue"; break; case 5: statusStr =...
Attribute (XUL) - Archive of obsolete content
<< XUL Reference home acceltext accessible accesskey activetitlebarcolor afterselected align allowevents allownegativeassertions alternatingbackground alwaysopenpopup attribute autoCheck auto
completeenabled auto
completepopup auto
completesearch auto
completesearchparam autoFill autoFillAfterMatch autoscroll beforeselected buttonaccesskeyaccept buttonaccesskeycancel buttonaccesskeydisclosure buttonaccesskeyextra1 buttonaccesskeyextra2 buttonaccesskeyhelp buttonalign buttondir buttondisabledaccept buttonlabelaccept buttonlabelcancel buttonlabeldisclosure buttonlabelextra1 buttonlabelextra2 buttonlabelhelp buttonorient buttonpack buttons checked checkState clicktoscroll class closebutton closemenu coalesceduplicatearcs collapse collapsed color ...
...eyextra1 buttonaccesskeyextra2 buttonaccesskeyhelp buttonalign buttondir buttondisabledaccept buttonlabelaccept buttonlabelcancel buttonlabeldisclosure buttonlabelextra1 buttonlabelextra2 buttonlabelhelp buttonorient buttonpack buttons checked checkState clicktoscroll class closebutton closemenu coalesceduplicatearcs collapse collapsed color cols command commandupdater
completedefaultindex container containment contentcontextmenu contenttooltip context contextmenu control crop curpos current currentset customindex customizable cycler datasources decimalplaces default defaultButton defaultset description dir disableAuto
complete disableautoselect disableclose disabled disablehistory disableKeyNavigation disablesecurity dlgtype dragging edita...
... defaultButton defaultset description dir disableAuto
complete disableautoselect disableclose disabled disablehistory disableKeyNavigation disablesecurity dlgtype dragging editable editortype element empty emptytext Deprecated since Gecko 2 enableColumnDrag enablehistory equalsize eventnode events expr firstdayofweek firstpage first-tab fixed flags flex focused force
Complete grippyhidden grippytooltiptext group handleCtrlTab height helpURI hidden hidechrome hidecolumnpicker hideheader hideseconds hidespinbuttons highlightnonmatches homepage href icon id ignoreBlurWhileSearching ignorecase ignoreincolumnpicker ignorekeys image inactivetitlebarcolor increment index inputtooltiptext insertafter insertbefore instantApply inverted iscontai...
...rves onbeforeaccept onbookmarkgroup onchange onclick onclosetab oncommand oncommandupdate ondialogaccept ondialogcancel ondialogclosure ondialogextra1 ondialogextra2 ondialoghelp onerror onerrorcommand onextra1 onextra2 oninput onload onnewtab onpageadvanced onpagehide onpagerewound onpageshow onpaneload onpopuphidden onpopuphiding onpopupshowing onpopupshown onsearch
complete onselect ontextcommand ontextentered ontextrevert ontextreverted onunload onwizardback onwizardcancel onwizardfinish onwizardnext open ordinal orient pack pageid pageincrement pagestep parent parsetype persist persistence phase pickertooltiptext placeholder popup position predicate preference preference-editable primary priority properties querytype readonly re...
XBL Inheritance - Archive of obsolete content
/handler> </handlers> </binding> The XBL here extends from the XUL textbox element. The URL given in the extends attribute above is the URL of the textbox binding. This means that we inherit all of the content and behavior provided by the textbox binding. In addition, we add a handler which responds to the keypress event. ...
...he XUL textbox element. The URL given in the extends attribute above is the URL of the textbox binding. This means that we inherit all of the content and behavior provided by the textbox binding. In addition, we add a handler which responds to the keypress event. Autocompleting TextBoxes The example above is similar to how the URL auto
complete feature works in Mozilla. A textbox that supports auto
complete is just one with a XBL binding that extends the basic textbox. ...
...of the textbox binding. This means that we inherit all of the content and behavior provided by the textbox binding. In addition, we add a handler which responds to the keypress event. Autocompleting TextBoxes The example above is similar to how the URL auto
complete feature works in Mozilla. A textbox that supports auto
complete is just one with a XBL binding that extends the basic textbox. The auto
complete textbox adds extra event handling so that when a URL is typed, a menu will pop up with possible completions. You can use it in your own applications too. Just create a textbox with two extra attributes. <textbox type="auto
complete" searchSessions="history"/> Set the type to auto
complete to add the auto
complete feature to an existing textbox. Set the searchSessions to indicate what type of data t...
...es. <textbox type="auto
complete" searchSessions="history"/> Set the type to auto
complete to add the auto
complete feature to an existing textbox. Set the searchSessions to indicate what type of data to look up. In this case, the value history is used, which looks up URLs in the history. (You can also use the value addrbook to look up addresses in the address book.) Firefox uses a different auto
complete mechanism than the Mozilla suite, see XUL:textbox (Firefox auto
complete) In the next section, we'll see an example XBL-defined widget. << PreviousNext >> ...
The Implementation of the Application Object Model - Archive of obsolete content
from some remote downloadable RDF file), and can then be combined into a single graph. Ok, so after that paragraph many of you probably still don't understand what RDF does, so here's the short and sweet version. RDF can suck up data from different places (like your bookmarks and history or another web site), and it can combine them. This gives you a feature called aggregation, the ability to put
completely different kinds of data into the same place. For example, the traditional bookmarks tree view could contain anything from mail messages to local files to maps of other sites. This same ability to aggregate data leads to another capability of RDF. Because RDF can suck up data from a remote location (e.g., from a downloadable RDF file), and also suck up data from a local source, it can take the r...
...gation of data, a content node implementation cannot make any assumptions about what kind of children it holds. It can only refer to its child nodes through the various content tree interfaces. What we run into now is the problem of how one local content node knows how to instantiate other kinds of content nodes. The only way that one content node would know how to instantiate a content node of a
completely different type is if it had additional information stored for every child content node that it contained. It would have to consult the registry of data sources in order to instantiate each of its children. If all content nodes are of the same type this problem can be solved in a cleaner fashion. A single content node could be initialized with its URI by its parent node, it could store its URI i...
...d obtain its information. Statement #2 All content nodes that reside in the AOM and that implement the content tree interfaces must be the same class of object. So now we're on the right track, but there are still some flaws in our architecture. Let's consider another required feature that has heretofore gone unmentioned in this document: the need to take the same set of data and present it as
completely different content models. The perfect example of this requirement is the Personal Toolbar. The Personal Toolbar must show up in a tree widget (in which case it has to be faking a tree content model,
complete with <tt><treeitem></tt> and <tt><treecell></tt> nodes), or it must be able to show up on a toolbar (
complete with <tt><button></tt> nodes and popup trees attached to folder buttons). In ou...
...d graph is fed into the XUL content model builder. This code is responsible for lazily presenting content nodes based on the RDF graph structure to the application that requests those nodes. Since this presentation happens "on demand", no content node is instantiated until the application specifically requests it, or demands an operation that requires the instantiation of the node to successfully
complete, e.g., asking for the number of children of a content node. When the application makes changes to the DOM, those changes percolate down into RDF, which can then decide what it should do with the changes in question. The most common options that RDF has to choose from are as follows: The change is really occurring in some RDF store. Handling of the change is the responsibility of the data source...
browser - Archive of obsolete content
urrently displayed page. Are you here looking for information about the Firefox web browser, or because you'd like to download the latest version of Firefox? Get Firefox Most of the properties and methods of the browser will rarely be used and can only be called from chrome URLs. Other URLs will need to use the document and history objects to change the displayed document. ...
...ge. Are you here looking for information about the Firefox web browser, or because you'd like to download the latest version of Firefox? Get Firefox Most of the properties and methods of the browser will rarely be used and can only be called from chrome URLs. Other URLs will need to use the document and history objects to change the displayed document. ...
... autoscroll Type: boolean Set to false to disable autoscroll for this browser. If this attribute is set to true or omitted, autoscroll will be enabled or depending on the user preference gene...
..., goHome, gotoIndex, loadURI, loadURIWithFlags, reload, reloadWithFlags, removeProgressListener, stop, swapDocShells Examples <!-- shows Mozilla homepage inside a groupbox --> <groupbox flex="1"> <caption label="Mozilla homepage"/> <browser type="content" src="http://www.mozilla.org" flex="1"/> </groupbox> Attributes auto
completeenabled Type: boolean Set to true to enable auto
complete of fields. auto
completepopup Type: id The id of a popup element used to hold auto
complete results for the element. autoscroll Type: boolean Set to false to disable autoscroll for this browser. If this attribute is set to true or omitted, autoscroll will be enabled or depending on the user preference general.autoScroll. disablehistory Type: boolean Disables...
tabbrowser - Archive of obsolete content
Related ] This element is used for holding a set of read-only views of Web documents. It is similar to the browser element, except that multiple documents can be displayed, each in a separate tab. Note: Starting in Firefox 3 (XULRunner/Gecko 1.9), this is only used in the main Firefox window and cannot be used in other XUL windows by third-party applications or extensions. ...
...ent is used for holding a set of read-only views of Web documents. It is similar to the browser element, except that multiple documents can be displayed, each in a separate tab. Note: Starting in Firefox 3 (XULRunner/Gecko 1.9), this is only used in the main Firefox window and cannot be used in other XUL windows by third-party applications or extensions. ...
... autoscroll Type: boolean Set to false to disable autoscroll for this browser. If this attribute is set to true or omitted, autoscroll will be enabled or depending on the user preference genera...
...ome, gotoIndex, loadGroup, loadOneTab, loadTabs, loadURI, loadURIWithFlags, moveTabTo, pinTab, reload, reloadAllTabs, reloadTab, reloadWithFlags, removeAllTabsBut, removeCurrentTab, removeProgressListener, removeTab, removeTabsProgressListener,replaceGroup, selectTabAtIndex, setIcon, showOnlyTheseTabs, stop, unpinTab Attributes auto
completeenabled Type: boolean Set to true to enable auto
complete of fields. auto
completepopup Type: id The id of a popup element used to hold auto
complete results for the element. autoscroll Type: boolean Set to false to disable autoscroll for this browser. If this attribute is set to true or omitted, autoscroll will be enabled or depending on the user preference general.autoScroll. contentcontextmenu Type: i...
textbox - Archive of obsolete content
/textarea> <div contenteditable="true" spellcheck="true">I am some content</div> <!-- spellcheck nothing! --> <input type="text" spellcheck="false" /><br /> <textarea spellcheck="false"></textarea> <div contenteditable="true" spellcheck="false">I am some content</div> You can use spellcheck on INPUT, TEXTAREA, and contenteditable elements. ...
...The default is 50 milliseconds. For search textboxes, the number of milliseconds before the timer fires a command event. The default is 500 milliseconds. For timed textboxes, the number of milliseconds before the timer fires a command event. There is no default. ...
...e number of milliseconds before the timer fires a command event. There is no default. The timer starts after the user types a character. If the user types another character, the timer resets. type Type: one of the values below You can set the type attribute to one of the values below for a more specialized type of textbox. Don't set the type if you wish to use a regular textbox. auto
complete A textbox that supports auto
complete. For more information about auto
complete textboxes, see the auto
complete documentation (XPFE [Thunderbird/SeaMonkey]) (Firefox) number A textbox that only allows the user to enter numbers. In addition, arrow buttons appear next to the textbox to let the user step through values. There are several attributes that allow the number textbox to be configured...
...ment. label Type: string Sets the label attribute. Gets the label attribute if it is present and not empty. Otherwise it returns the value of the associated label element, if applicable. Otherwise it returns the placeholder or emptyText property. The getter is mostly useful for screen readers. Note: Prior to Firefox 3, and always in Thunderbird and SeaMonkey, the label property of an auto
complete textbox returns its value, for compatibility with the menulist element. max Type: integer Gets and sets the value of the max attribute. maxLength Type: integer The maximum number of characters that the textbox allows to be entered. min Type: integer Gets and sets the value of the min attribute. placeholder Type: string Gets and sets a...
What XULRunner Provides - Archive of obsolete content
Firefox and Thunderbird), as well as providing an embedding mechanism. ...
...See the wikimo:XUL:Installation Story. Extension Manager File picker (uses native OS filepicker as appropriate) Find toolbar Help...
...XUL:Installation Story. ...
...er as appropriate) Find toolbar Helper app dialog/UI Security UI (maintenance of SSL keychains, etc) Embedding APIs The following embedding APIs are provided by XULRunner: Cross-platform embedding (XRE_InitEmbedding) JavaXPCOM embedding gtkmozembed (Linux only) ActiveX control (Windows only) (not yet
complete) Obsolete since Gecko 7.0 NSView-based-widget (Mac OS X only) (not yet
complete) The "Maybe" List The following features have been discussed and may be included if developer time permits and code size is controlled: LDAP support Spellchecking support (with or without dictionaries provided) see bug 285977 Core support for profile roaming (with application-specific extensibility) PyXPCOM embedding (not yet
complete) - but it does work, if you compile a custom build t...
Introduction to Public-Key Cryptography - Archive of obsolete content
been authenticated, the client and server use techniques of symmetric-key encryption, which is very fast, to encrypt all the information they exchange for the remainder of the session and to detect any tampering that may have occurred. Servers may optionally be configured to require client authentication as well as server authentication. In this case, after server authentication is successfully
completed, the client must also present its certificate to the server to authenticate the client's identity before the encrypted SSL session can be established. For an overview of client authentication over SSL and how it differs from password-based authentication, see "Authentication Confirms an Identity". For more detailed information about SSL, see "Introduction to SSL." Signed and Encrypted Email S...
...s authorized to use-without sending any passwords over the network. This approach simplifies access for users, because they don't need to enter passwords for each new server. It also simplifies network management, since administrators can control access by controlling lists of certificate authorities (CAs) rather than much longer lists of users and passwords. In addition to using certificates, a
complete single-sign on solution must address the need to interoperate with enterprise systems, such as the underlying operating system, that rely on passwords or other forms of authentication. Object Signing Communicator supports a set of tools and technologies called object signing. Object signing uses standard techniques of public-key cryptography to let users get reliable information about code they...
..., your UNIX or Windows login and password may be sufficient. At the other end of the scale, for certificates that identify people who can authorize large expenditures or make other sensitive decisions, the issuing process may require notarized documents, a background check, and a personal interview. Depending on an organization's policies, the process of issuing certificates can range from being
completely transparent for the user to requiring significant user participation and complex procedures. In general, processes for issuing certificates should be highly flexible, so organizations can tailor them to their changing needs. Issuing certificates is one of several managements tasks that can be handled by separate Registration Authorities. Certificates and the LDAP Directory The Lightweight Di...
...period of time during which it is valid. Attempts to use a certificate for authentication before or after its validity period will fail. Therefore, mechanisms for managing certificate renewal are essential for any certificate management strategy. For example, an administrator may wish to be notified automatically when a certificate is about to expire, so that an appropriate renewal process can be
completed in plenty of time without causing the certificate's subject any inconvenience. The renewal process may involve reusing the same public-private key pair or issuing a new one. A driver's license can be suspended even if it has not expired-for example, as punishment for a serious driving offense. Similarly, it's sometimes necessary to revoke a certificate before it has expired-for example, if an e...
Browser Detection and Cross Browser Support - Archive of obsolete content
uct == 'Gecko' or look for the string 'Gecko/' in the navigator.userAgent. Note that some other browsers such as Safari are reporting (like Gecko) in their user agent strings and can confuse simple tests. Introduction In an ideal world, we could author HTML, XML, CSS and JavaScript and only worry about the W3C and ECMA standards. However, we don't quite live in such a world yet. Due to bugs, in
complete implementations of the standards and legacy browsers, web developers must be able to determine which browser a visitor is using and provide the appropriate content and scripting code path. Although browser detection is perhaps the most common scripting task that every web developer faces, it seems that the variety of different strategies in use for detecting browsers is unlimited. As a member of...
...enerations of browsers such as Netscape Navigator 4 as well as features which provide compatibility with Internet Explorer 5 and 6. Unlike other browsers, Gecko is truly cross platform and provides consistent behavior across all supported operating systems. The easiest way to support Gecko is to create content which follows web standards. ...
...rts web standards as
completely as Gecko. This means web developers and authors are forced to continue to support other browsers which do not comply with the standards as fully. Fortunately, other browsers such as Opera (versions 7 & later) and to a lesser extent, Internet Explorer (versions 5.5 & later) also support the standards to a degree. These other browsers appear to be moving towards more
complete support for the standards and there is hope that in the future web developers and authors will be able to dispense with browser detection at least with regard to features governed by standards. We are still faced with the question of how to develop standards based content while supporting the differing implementations of modern browsers while at the same time supporting (to a lesser degree) olde...
...gs in specific releases of a browser. However, this can quickly become a maintenance nightmare if you are not careful. I recommend that you only provide work arounds for bugs on a temporary basis and as soon as bugs are corrected in newer releases of the browser that you require your visitors to upgrade their browser. Provide downlevel pages for older browsers No commercial web site today makes
complete support for Netscape Navigator versions 1, 2 or 3 or Microsoft Internet Explorer 3 a requirement. The reasons are that the capabilities of such browsers are far too limited compared to more modern browsers, the added development and quality assurance requirements add too much to the development cost of web sites and the market share of such browsers does not justify the expense of supporting them...
Mobile accessibility - Learn web development
, CSS, and JavaScript, and an understanding of the previous articles in the course. Objective: To understand what problems exist with accessibility on mobile devices, and how to overcome them. Accessibility on mobile devices The state of accessibility -- and support for web standards in general -- is good in modern mobile devices. Long gone are the days when mobile devices ran
completely different web technologies to desktop browsers, forcing developers to use browser sniffing and serve them
completely separate sites (although quite a few companies still detect usage of mobile devices and serve them a separate mobile domain). These days, mobile devices can usually handle fully-featured websites, and the main platforms even have screenreaders built in to enable visually impaire...
... turn TalkBack off: Navigate back to the TalkBack menu screen (using the different gestures that are currently enabled.) Navigate to the slider switch and activate it to turn it off. Note: You can get to your home screen at any time by swiping up and left in a smooth motion. If you have more than one home screen, you can move between them by swiping two fingers left and right. For a more
complete list of TalkBack gestures, see Use TalkBack gestures. Unlocking the phone When TalkBack is turned on, unlocking the phone is a bit different. You can do a two-finger swipe up from the bottom of the lock screen. If you've set a passcode or pattern for unlocking your device, you will then be taken to the relevant entry screen to enter it. You can also explore by touch to find the Unlock button ...
...cal content menu. Swipe right until you find the "Headings and Landmarks" option. Double-tap to select it. Now you'll be able to swipe left and right to move between headings and ARIA landmarks. To go back to the default mode, enter the local context menu again by swiping up and right, select "Default", and then double-tap to activate. Note: See Get started on Android with TalkBack for more
complete documentation. iOS VoiceOver A mobile version of VoiceOver is built into the iOS operating system. To turn it on, go to Your Settings app and select Accessibility > VoiceOver. Press the VoiceOver slider to enable it (you'll also see a number of other options related to VoiceOver on this page). Note: Some older iOS devices have the VoiceOver menu at Settings app > General > Accessibility > V...
...: Move between different semantic containers on the page. Headings: Move between headings on the page. Links: Move between links on the page. Form Controls: Move between form controls on the page. Language: Move between different translations, if they are available. Select Headings. Now you'll be able to swipe up and down to move between headings on the page. Note: For a more
complete reference covering the VoiceOver gestures available and other hints on accessibility testing on iOS, see Test Accessibility on Your Device with VoiceOver. Control mechanisms In our CSS and JavaScript accessibility article, we looked at the idea of events that are specific to a certain type of control mechanism (see Mouse-specific events). To recap, these cause accessibility issues because othe...
Advanced form styling - Learn web development
the options when you click on the <select> box to open it. You'll notice that the options don't inherit the font set on the parent. You also can't consistently set things like spacing and colors. For example, Firefox will apply color and background-color when set on the <option> elements, Chrome won't. Neither of them will apply any kind of spacing (e.g. padding). The same is also true of the auto
complete list that appears for the datalist. If you really need full control over the option styling, you'll have to either use some kind of library to generate a custom control, or build your own custom control, or in the case of select use the multiple attribute, which makes all the options appear on the page, sidestepping this particular problem: <select id="select" name="select" multiple> ... </se...
...values, so potentially suffers from the same problem. However, in the case of the number type the data being collected is simpler, and it is easy to just use a text input type instead if desired (or tel if you want mobile browsers to show the numeric keypad). Range input types <input type="range"> is annoying to style. ...
..., it is fairly easy to create something that fits in OK with the rest of the page -- the output line that is part of the control will inherit the parent font if you tell the input to do so, and you can style the custom list of file names and sizes in any way you want; we created it after all. The only problem with file pickers is that the button provided that you press to open the file picker is
completely unstyleable -- it can't be sized or colored, and it won't even accept a different font. One way around this is to take advantage of the fact that if you have a label associated with a form control, clicking the label will activate the control. So you could hide the actual from input using something like this: input[type="file"] { height: 0; padding: 0; opacity: 0; } And then style the ...
...ries out there that can help you: Uni-form is a framework that standardizes form markup, styling it with CSS. It also offers a few additional features when used with jQuery, but that's optional. Formalize is an extension to common JavaScript frameworks (such as jQuery, Dojo, YUI, etc.) that helps to normalize and customize your forms. Niceforms is a standalone JavaScript method that provides
complete customization of web forms. You can use some of the built in themes, or create your own. The following libraries aren't just about forms, but they have very interesting features for dealing with HTML forms: jQuery UI offers customizable widgets such as date pickers (with special attention given to accessibility). Twitter Bootstrap can help normalize your forms. WebShim is a huge tool that ...
Tips for authoring fast-loading HTML pages - Learn web development
onents of the page Download page content first, along with any CSS or JavaScript that may be required for its initial display, so that the user gets the quickest apparent response during the page loading. This content is typically text, and can, therefore, benefit from text compression in transit, thus providing an even quicker response to the user. Any dynamic features that require the page to
complete loading before being used, should be initially disabled, and then only enabled after the page has loaded. This will cause the JavaScript to be loaded after the page contents, which will improve the overall appearance of the page load. Reduce the number of inline scripts Inline scripts can be expensive for page loading since the parser must assume that an inline script could modify the page stru...
...ls such as Photoshop, or using a specialized tool such as Compress Jpeg or Tiny PNG,. Specify sizes for images and tables If the browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. This not only speeds the display of the page but prevents annoying changes in a page's layout when the page
completes loading. For this reason, height and width should be specified for images, whenever possible. Tables should use the CSS selector: property combination: table-layout: fixed; and should specify widths of columns using the <col> and the <colgroup> elements. Use lazy loading for images By default, imags are loaded eagerly; that is, the image is fetched and rendered as soon as it's processed ...
...the visual viewport. To mark an image for lazy loading, specify its loading attribute with a value of lazy. With this set, the image will only be loaded when it's needed. <img href="./images/footerlogo.jpg" loading="lazy"> Note that lazily-loaded images may not be available when the load event is fired. You can determine if a given image is loaded by checking to see if the value of its Boolean
complete property is true. Choose your user-agent requirements wisely To achieve the greatest improvements in page design, make sure that reasonable user-agent requirements are specified for projects. Do not require your content to appear pixel-perfect in all browsers, especially not in down-version browsers. Ideally, your basic minimum requirements should be based on the consideration of modern browse...
...of files for performance while keeping unrelated JavaScript in separate files for maintenance. . <body> . User visible page content in small chunks ( <header>/ <main>/ <table>) that can be displayed without waiting for the full page to download. . <script> ... Any scripts which will be used to perform interactivity. Interaction scripts typically can only run after the page has
completely loaded and all necessary objects have been initialized. There is no need to load these scripts before the page content. That only slows down the initial appearance of the page load. Minimize the number of files for performance while keeping unrelated JavaScript in separate files for maintenance. If any images are used for rollover effects, you should preload them here after the page content...
Choosing the right approach - Learn web development
Basic computer literacy, a reasonable understanding of JavaScript fundamentals. Objective: To be able to make a sound choice of when to use different asynchronous programming techniques. Asynchronous callbacks Generally found in old-style APIs, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been
completed, so that the callback can in turn do something with the result. This is the precursor to promises; it's not as efficient or flexible. Use only when necessary. Useful for... Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations No Yes (recursive callbacks) Yes (nested callbacks) No Code example...
...ntation notes.Requires a vendor prefix or different name for use.Requires a vendor prefix or different name for use. Further information Cooperative asynchronous JavaScript: Timeouts and intervals, in particular requestAnimationFrame() requestAnimationFrame() reference Promises Promises are a JavaScript feature that allows you to run asynchronous operations and wait until it is definitely
complete before running another operation based on its result. Promises are the backbone of modern asynchronous JavaScript. Useful for... Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations No No Yes See Promise.all(), below Code example The following code fetches an image from the server and displays it...
....get(...); }).then(function (resultOfGet) { return localdb.put(...); }).catch(function (err) { console.log(err); }); or even: remotedb.allDocs(...) .then(resultOfAllDocs => { return localdb.put(...); }) .then(resultOfPut => { return localdb.get(...); }) .then(resultOfGet => { return localdb.put(...); }) .catch(err => console.log(err)); That covers a lot of the basics. For a much more
complete treatment, see the excellent We have a problem with promises, by Nolan Lawson. Browser compatibility DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.jsPromiseChrome Full support 32Edge Full support ...
... Full support Full support No support No supportSee implementation notes.See implementation notes. Further information Graceful asynchronous programming with Promises Using promises Promise reference Promise.all() A JavaScript feature that allows you to wait for multiple promises to
complete before then running a further operation based on the results of all the other promises. Useful for... Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations No No No Yes Code example The following example fetches several resources from the server, and uses Promise.all() to wait for all of them to b...
Looping code - Learn web development
Here we'll look at the loop structures available in JavaScript that handle such needs. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps. Objective: To understand how to use loops in JavaScript. ...
...derstand the high-level concepts behind loops, but you are probably thinking "OK, great, but how does this help me write better JavaScript code?" As we said earlier, loops are all to do with doing the same thing over and over again, which is great for rapidly completing repetitive tasks. Often, the code will be slightly different on each successive iteration of the loop, which means that you can
complete a whole load of tasks that are similar but slightly different -- if you've got a lot of different calculations to do, you want to do each different one, not the same one over and over again! Let's look at an example to perfectly illustrate why loops are such a good thing. Let's say we wanted to draw 100 random circles on a <canvas> element (press the Update button to run the example again and ag...
...ops -- you must make sure that the initializer is incremented or, depending on the case, decremented, so that it eventually reaches the point where the condition is not true. If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an infinite loop. Exiting loops with break If you want to exit a loop before all the iterations have been
completed, you can use the break statement. We already met this in the previous article when we looked at switch statements -- when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves onto the code after it. It's the same with loops -- a break statement will immediately exit the loop and make the browser move on to an...
...le keyword rather than for. The same three items are still present, and they are still defined in the same order as they are in the for loop -- this makes sense, as you still have to have an initializer defined before you can check whether it has reached the point where the condition is no longer true; the final-expression is then run after the code inside the loop has run (an iteration has been
completed), which will only happen if the condition is still true. Let's have a look again at our cats list example, but rewritten to use a while loop: let i = 0; while (i < cats.length) { if (i === cats.length - 1) { info += 'and ' + cats[i] + '.'; } else { info += cats[i] + ', '; } i++; } Note: This still works just the same as expected -- have a look at it running live on GitHub (...
Fetching data from the server - Learn web development
s responseType property -- as text. This isn't strictly necessary here -- XHR returns text by default -- but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future. Add this next: request.responseType = 'text'; Fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to
complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown. XHR allows you to handle this using its onload event handler -- this is run when the load event fires (when the response has returned). When this has occurred, the response data will be available in the response property of the XHR request object. Add the followi...
...d event handler we are setting the textContent of the poemDisplay (the <pre> element) to the value of the request.response property. request.onload = function() { poemDisplay.textContent = request.response; }; The above is all set up for the XHR request -- it won't actually run until we tell it to, which is done using the send() method. Add the following below your previous addition to
complete the function. This line should rest just above the closing curly brace of your updateDisplay() function. request.send(); One problem with the example as it stands is that it won't show any of the poem when it first loads. To fix this, add the following two lines at the bottom of your code (just above the closing </script> tag) to load verse 1 by default, and make sure the <select> elemen...
...t.js). We will however explain the Fetch code. The first block that uses Fetch can be found at the start of the JavaScript: fetch('products.json').then(function(response) { return response.json(); }).then(function(json) { let products = json; initialize(products); }).catch(function(err) { console.log('Fetch problem: ' + err.message); }); The fetch() function returns a promise. If this
completes successfully, the function inside the first .then() block contains the response returned from the network. Inside this function we run json() on the response, not text(), as we want to return our response as structured JSON data, not plain text. Next, we chain another .then() onto the end of our first one, the success function that contains the json returned from the response.json() promise. W...
...f displaying all the products in the user interface. To handle errors, we chain a .catch() block onto the end of the chain. This runs if the promise fails for some reason. Inside it, we include a function that is passed as a parameter, an error object. This error object can be used to report the nature of the error that has occurred, in this case we do it with a simple console.log(). However, a
complete website would handle this error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't need anything more than a simple console.log(). You can test the fail case yourself: Make a local copy of the example files (download and unpack the can-store ZIP file). Run the code through a web server (as described above, in Servin...
What is JavaScript? - Learn web development
ts of some common programming features that allow you to do things like: Store useful values inside variables. In the above example for instance, we ask for a new name to be entered then store that name in a variable called name. Operations on pieces of text (known as "strings" in programming). In the above example we take the string "Player 1: " and join it to the name variable to create the
complete text label, e.g. ''Player 1: Chris". Running code in response to certain events occurring on a web page. We used a click event in our example above to detect when the button is clicked and then run the code that updates the text label. And much more! What is even more exciting however is the functionality built on top of the client-side JavaScript language. So-called Application Programming I...
...tries to run before the HTML and CSS it is affecting has been loaded, errors can occur. You will learn ways around this later in the article, in the Script loading strategies section. Browser security Each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) -- this means that in most cases the code in each tab is run
completely separately, and the code in one tab cannot directly affect the code in another tab -- or on another website. This is a good security measure -- if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things. Note: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced t...
...in the head of the document, before the HTML body is parsed. This could cause an error, so we've used some constructs to get around it. In the internal example, you can see this structure around the code: document.addEventListener("DOMContentLoaded", function() { ... }); This is an event listener, which listens for the browser's "DOMContentLoaded" event, which signifies that the HTML body is
completely loaded and parsed. The JavaScript inside this block will not run until after that event is fired, therefore the error is avoided (you'll learn about events later in the course). In the external example, we use a more modern JavaScript feature to solve the problem, the defer attribute, which tells the browser to continue downloading the HTML content once the <script> tag element has been reache...
...us. We didn't use the defer solution for the internal JavaScript example because defer only works for external scripts. An old-fashioned solution to this problem used to be to put your script element right at the bottom of the body (e.g. just before the </body> tag), so that it would load after all the HTML has been parsed. The problem with this solution is that loading/parsing of the script is
completely blocked until the HTML DOM has been loaded. On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site. async and defer There are actually two modern features we can use to bypass the problem of the blocking script -- async and defer (which we saw above). Let's look at the difference between these two. Scripts loaded using the async attribute (s...
Beginning our React todo list - Learn web development
This article will walk you through putting the basic App component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. ...
... get the basic App structure and styling in place. Our app's user stories In software development, a user story is an actionable goal from the perspective of the user. Defining user stories before we begin our work will help us focus our work. Our app should fulfill the following stories: As a user, I can read a list of tasks. add a task using the mouse or keyboard. mark any task as
completed, using the mouse or keyboard. delete any task, using the mouse or keyboard. edit any task, using the mouse or keyboard. view a specific subset of tasks: All tasks, only the active task, or only the
completed tasks. We'll tackle these stories one-by-one. Pre-project housekeeping create-react-app has made a few files we won't be using at all for our project. We're not going to write per-...
...turn ( <div className="todoapp stack-large"> <h1>TodoMatic</h1> <form> <h2 className="label-wrapper"> <label htmlFor="new-todo-input" className="label__lg"> What needs to be done? ...
...tton> <button type="button" className="btn toggle-btn" aria-pressed="false"> <span className="visually-hidden">Show </span> <span>Active</span> <span className="visually-hidden"> tasks</span> </button> <button type="button" className="btn toggle-btn" aria-pressed="false"> <span className="visually-hidden">Show </span> <span>
Completed</span> <span className="visually-hidden"> tasks</span> </button> </div> <h2 id="list-heading"> 3 tasks remaining </h2> <ul role="list" className="todo-list stack-large stack-exception" aria-labelledby="list-heading" > <li className="todo stack-small"> <div className="c-cb"> <input id="to...
Deployment and next steps - Learn web development
with the core HTML, CSS, and JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn how to prepare our Svelte app for production, and what learning resources you should visit next. Note that our application is fully functional and porting it to TypeScript is
completely optional. There are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using TypeScript. Even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at diff...
... go and check out, to take your Svelte learning further. Svelte documentation To go further and learn more about Svelte, you should definitely visit the Svelte homepage. There you'll find many articles explaining Svelte's philosophy. If you haven't already done it, make sure you go through the Svelte interactive tutorial. We already covered most of its content, so it won't take you much time to
complete it -- you should consider it as practise! You can also consult the Svelte API docs and the available examples. To understand the motivations behind Svelte, you should read Rich Harris's Rethinking reactivity presentation on YouTube. He is the creator of Svelte, so he has a couple of things to say about it. You also have the interactive slides available here which are, unsurprisingly, built with...
...If you are planning to develop a fairly complex web application you should definitely have a look at this project. Svelte Native: A mobile application framework powered by Svelte. Think of it as React Native for Svelte. Svelte for VS Code: The officially supported VS Code plugin for working with .svelte files, which we looked at in our TypeScript article. Other learning resources There's a
complete course about Svelte and Sapper by Rich Harris, available at Frontend Masters. Even though Svelte is a relatively young project there are lots of tutorials and courses available on the web, so it's difficult to make a recommendation. Nevertheless, Svelte.js -- The
Complete Guide by Academind is a very popular option with great ratings. The Svelte Handbook, by Flavio Copes, is also a useful refe...
...munity-driven repository of recipes, tips, and best practices to solve common problems. Svelte questions on StackOverflow: Questions with the svelte tag at SO. Svelte reddit community: Svelte community discussion and content rating site at reddit. Svelte DEV community: A collection of Svelte-related technical articles and tutorials from the DEV.to community. Finito Congratulations! You have
completed the Svelte tutorial. In the previous articles we went from zero knowledge about Svelte to building and deploying a
complete application. We learned about Svelte philosophy and what sets it apart from other front-end frameworks. We saw how to add dynamic behavior to our web site, how to organize our app in components and different ways to share information among them. We took advantage of th...
Using Vue computed properties - Learn web development
These work similarly to methods, but only re-run when one of their dependencies changes. Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line. Vue components are written as a combination of JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure. ...
...d features of Vue (like Single File Components or render functions), you'll need a terminal with node + npm installed. Objective: To learn how to use Vue computed properties. Using computed properties The aim here is to add a summary count of our to-do list. This can be useful for users, while also serving to label the list for assistive technology. If we have 2 of 5 items
completed in our to-do list, our summary could read "3 items
completed out of 5". While it might be tempting to do something like this: <h2>{{ToDoItems.filter(item => item.done).length}} out of {{ToDoItems.length}} items
completed</h2> It would be recalculated on every render. For a small app like this, that probably doesn't matter too much. For bigger apps, or when the expression is more complicated, ...
...usly. 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> element. Add the described <h2> and update the <ul> inside your App's template as follows: <h2 id="list-summary">{{listSummary}}</h2> <ul aria-labelledby="list-su...
...oItems" :key="item.id"> <to-do-item :label="item.label" :done="item.done" :id="item.id"></to-do-item> </li> </ul> You should now see the list summary in your app, and the total number of items update as you add more todo items! However, if you try checking and unchecking some items, you'll reveal a bug. Currently, we're not actually tracking the "done" data in any fashion, so the number of
completed items does not change. Tracking changes to "done" We can use events to capture the checkbox update and manage our list accordingly. Since we're 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" :che...
Continuous Integration
ross multiple types of infrastructure. This document will help you understand all the pieces that comprise Mozilla's continuous integration systems. TaskCluster and Treeherder TaskCluster, Mozilla's continuous integration (CI) system picks up changes pushed to Hg. TaskCluster generate binary builds for Firefox and Firefox for Android across a variety of operating sytems. After the builds are
completed, they are used to run a series of correctness and performance tests. The results of TaskCluster jobs (both builds and tests) are displayed in Treeherder. There is a group of individuals who are constantly monitoring Treeherder, looking for broken builds and/or tests. These individuals are known as sheriffs. The sheriffs' role is to "keep the tree green", or in other words, to keep the code i...
...nce tests displayed in Treeherder are run using the Talos framework, and denoted by the letter T. These jobs are scheduled at the same time as the correctness jobs. Talos is used to execute several suites for desktop Firefox and Firefox for Android; these suites are denoted using lower-case letters, e.g., T(c d g1 o s tp). The Talos indicators in Treeherder appear green if the job successfully
completed; to see the performance data generated by the jobs, click on the performance tab of the job details panel that pops up when you click on a job in Treeherder. Each Talos suite contains a set of tests or pages, some of these in turn have sub-tests. Each test is executed multiple times to produce a number of data replicates. The Talos harness produces a single number per test (typically the med...
...currently run are primarily startup tests. Games Benchmarking (Firefox) Under development, the games benchmarking harness (aka mozbench) will allow a number of games-related benchmarks to be run against Firefox and Chrome. Eventually, the system will likely be expanded with support for Android. Post-Job Analysis and Alerts There is some analysis of test data that occurs out-of-band after jobs
complete. Perfherder Alerts We track changes to Talos and other performance frameworks inside Perfherder, and try to automatically alert when there is a sustained change exceeding a certain magnitude (specified per test). Performance sheriffs review the list of alerts on a regular basis and file bugs if appropriate. You can view the current set of alerts on the Perfherder Alerts dashboard. Intermitten...
...nges to Talos and other performance frameworks inside Perfherder, and try to automatically alert when there is a sustained change exceeding a certain magnitude (specified per test). Performance sheriffs review the list of alerts on a regular basis and file bugs if appropriate. You can view the current set of alerts on the Perfherder Alerts dashboard. Intermittent failures After functional tests
complete, test log data are combined with Treeherder's failure classification data. The result is the Treeherder Intermittent Failures view. The "Orange Factor" is the average number of intermittent test failures that occur per push. The dashboard can be used to view the most frequent intermittent test failures, as well as to inspect historical trends. ...
Eclipse CDT Manual Setup
a source, and that you have also built the source so that you have a pre-existing object directory. If that is not the case, then get your build going now so that it can be running while you continue with the instructions below. FAQ: Wait, why does Eclipse need an object directory?) Code assistance Out of the box, Eclipse can provide some code assistance for the Mozilla source, but it will be in
complete and often just plain broken. If you set up Eclipse as detailed below, you will experience much better results. Important background To help you make sense of the instructions that follow (and so that you can modify them to meet your own needs if necessary), this section provides some background on what IDEs need in order to provide advanced code assistance, and what Eclipse CDT needs in particu...
...mpiler is invoked from, this will not be possible. If Eclipse can successfully identify which source file was being compiled, then it can associate with that file the resolvable include paths, preprocessor defines, and pre-include files that were passed to the compiler. Note the requirements that this method of build option discovery imposes on us. First, Eclipse needs build console output for a
complete build, so that it can find compiler options for as many source files as possible. The build must be explicitly instructed to output information that allows the directory, where the compiler is being invoked from to be identified (i.e., 'make' must be instructed to output "Entering directory..."/"Leaving directory..." lines). Finally, the build must not be parallelized, since that would result in ...
...General > Editors > Text Editors" have no effect in C/C++ views, since the C/C++ settings are more specific and override those settings. However, you may still want to tweak those settings if you'll be editing other file types in Eclipse.) Select "C/C++ > Editor" and set "Workspace default" to "Doxygen". Select "C/C++ > Editor > Content Assist" and set the Auto-Activation delay to 0 so that auto
complete suggestions don't seem to be laggy. (Sadly, there is no auto-activation option to activate auto
complete suggestion., so as soon as you type any alphabetical character that may begin with a symbol name like there is in other IDEs.) Select "C/C++ > Editor > Save Actions" and deselect "Ensure newline at the end of file". Select "C/C++ > Editor > Scalability" and set "Enable scalability mode when t...
...e Code assistance section above, to provide good code assistance Eclipse CDT needs to collect build information for the source files by processing a build log from a full, clean build made using -j1 -w. Since such a non-parallel, full build would take a very long time, we're going to cheat and set Eclipse's "Build" action to run jwatt's just-print-mozilla-build.py script instead. This script will
complete in about 30 seconds on a warm tree (files cached in RAM) if your object directory is up to date, although Eclipse will take several minutes to process the "build output" that it produces. Download just-print-mozilla-build.py and change its permissions to make it executable ('chmod a+x just-print-mozilla-build.py'). If you don't put just-print-mozilla-build.py somewhere in your PATH, then go bac...
IME handling guide
its composition string as a selected item off the list and commits composition string without any conversion. IME is used by Chinese, Japanese, Korean and Taiwan users for inputting Chinese characters because the number of them is beyond thousands and cannot be input from the keyboard directly. However, especially on mobile devices nowadays, IME is also used for inputting Latin languages like auto
complete. Additionally, IME may be used for handwriting systems or speech input systems on some platforms. If IME is available on focused elements, we call that state "enabled". If IME is not fully available(i.e., user cannot enable IME), we call this state "disabled". If IME is enabled but users use direct input mode (e.g., for inputting Latin characters), we call it "IME is closed". Otherwise, we call...
...looks for a TextComposition instance whose native IME context is same as the widget' which dispatches the widget event. If there is no proper TextComposition instance, it creates the instance. And it sends the event to the TextComposition instance. Note that all instances of TextComposition are managed by IMEStateManager. When an instance is created, it's registered to the list. When composition
completely ends, it's unregistered from the list (and released automatically). mozilla::TextComposition TextComposition manages a composition and dispatches DOM compositionupdate events. When this receives an eCompositionChange, eCompositionCommit or eCompositionCommitAsIs event, it dispatches the event to the stored node which was the event target of eCompositionStart event. Therefore, this class guar...
...pected. If the user uses such old Chinese IME, "intl.ime.remove_placeholder_character_at_commit" pref may be useful but we don't support them anymore in default settings (except if somebody will find a good way to fix this issue). The composition is committed synchronously but with empty string This case may occur on Linux or with some IME on other platforms. If a web application implements auto
complete, committing with different strings especially an empty string it might cause confusion. In this case, TextComposition overwrites the commit string of eCompositionChange event dispatched by widget. However, if the last composition string is only an ideographic space, it shouldn't be committed. See the previous case Note that this case doesn't work as expected when composition is in a remote proc...
...es caused by the dispatched WidgetCompositionEvents (they are notified synchronously in chrome or non-e10s mode, but asynchronously from a remote process in e10s mode). At this time, TSFTextStore may receive notifications which indicates web application changes the content differently from cache in TSFTextStore. However, TSFTextStore ignores such fact temporarily until the composition is finished
completely. The reason is that, notifying unexpected text or selection changes to TSF and/or TIP during composition may behave them odd. When a composition is committed and it receives NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED, TSFTextStore clears the cache of contents and notifying TSF of merged text changes and the last selection change if they are not caused by composition. By this step, TSF and TIP may...
Examples
Now 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. const {Cu} = require("chrome"); const {TextDecoder, TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {}); /* files: An array of file paths */ function readTextFiles(files) { let promises = [], decoder = new TextD...
...y success' but because I commented out the var 2 lines above, it will error out on the alert(myVarIsCommented) and never get to this success line. uncommet the var 2 lines above to see the promise succesfully return } catch(ex) { return Promise.reject(ex); } } Copy and paste this code and the rejection will take place. Uncomment the line `//var myVarIsCommented.....` and the promise will
complete succesfully. Now replace the `alert(myVarIsCommented)` with `throw new Error('i feel like rejecting this promise')` like this: Components.utils.import("resource://gre/modules/Promise.jsm"); var myPromise = myUserDefinedPromise(); myPromise.then( function(aSuccessReason) { alert('myPromise was SUCCESFUL and reason was = "' + aSuccessReason + '"'); }, function(aRejectReason) { alert...
...gger with aSuccessReason being 'yay success' but because I commented out the var 2 lines above, it will error out on the throw and never get to this success line becuase i throw an error on the line before this } catch(ex) { return Promise.reject(ex); } } In this example even though the variable is defined, the proimse is rejected because I threw an error. ...
...If you do not then it will not understand itis a promise. This is improper usage: Components.utils.import("resource://gre/modules/Promise.jsm"); var myPromise = myUserDefinedPromise(); myPromise.then( function(aSuccessReason) { alert('myPromise was SUCCESFUL and reason was = "' + aSuccessReason + '"'); }, function(aRejectReason) { alert('myPromise FAILED for reason = ...
NSS API Guidelines
SS code is layered, and how higher-level functions wrap low-level functions. The Libraries section descibes the NSS libraries, the functionality each provides, and the layer in which the library (mostly) operates. Layering Each separate component of the API should live in its own layer. The functions in these APIs should never call API layers above them. In addition, some low-level APIs may be
completely opaque to higher level layers. That is, access to these functions should only be provided by the API directly above them. The NSS APIs are layered, as shown in this diagram: The boxes in the gray section, towards the center, are exported only through PKCS #11. PKCS #11 is only exported through the Wrappers. The areas which need the most work (both here and throughout the code) is: The re...
...tructure members. Enum members have the same standard as data types. Enum members have the same standard as public macros (minus the '()' of course). Options 2 and 3 are the more preferred options. Option 1, currently the most common used for enums, actually creates namespace pollution. Callback functions, and functions used in function tables, should have a typedef used to define the
complete signature of the given function. Function typedefs should have the following format: LAYERBody(), with the same definitions for LAYER as public functions, and Body is camel case English words. For example: LAYERCapitalizedEnglishWords or SECKEYPrivateKey. Opaque Data Structures There are many data structures in the security library whose definition is effectively private, to the portion of the...
...he entire search. This strategy is best when lists are short, or even better if lists are relatively read only (they don't change very often) and using reader/writer locks. Copy the linked list: Instead of operating on the global list, you can copy the list. This also requires small lists. Lock over single element with retry: For medium sized lists, you can secure the reference to each element,
complete a test, then detect if the given element has been removed from the list. In the case of removal, the search can either be either restarted, or terminated. This method is a more complicated than the other methods: requiring the calling of search code tolerant to often repeated element inspection. Examples of the previous strategies can be found in security/nss/lib/pk11wrap/pk11slot.c. Where pos...
...andle should be created, and the SEC_SetKey() function, above, made on that handle. Fortunately most of the existing API has the correct semantics. The exception to this global effects rule may be functions which set global state for an application at initialization time. Methods/Functions Design Init, Shutdown Functions If a layer has some global initialization tasks, which need to be
completed before the layer can be used, that layer should supply an initialization function of the form LAYER_Init(). If an initialization function is supplied, a corresponding LAYER_Shutdown() function should also be supplied. LAYER_INIT() should increment a count of the number of times it is called, and LAYER_Shutdown() should decrement that count, and shutdown when the count reaches '0'. Open, Clos...
PKCS11 FAQ
n? Example: RSA private key, CA certificate, user's own certificate, user's name. Private keys (RSA and DSA) and the corresponding certificates are read from the token. Other certificates on the token are also loaded (to allow building certificate chains), but it's not necessary to include the full chain, as long as the full chain is available in the regular certificate database. For the sake of
completeness, it's also a good idea to expose public key objects. NSS falls back to looking for for the existance of public keys to determine if the token may have the corresponding private key while the token is not logged in. How are permanent PKCS #11 objects found by NSS? That is, which PKCS #11 attributes are used in the object searches? Labels? Key IDs? Key types? These are the general guidelines:...
...in the installer script. For information on how to do this, see Using the JAR Installation Manager to Install a PKCS #11 Cryptographic Module. Can Mozilla provide a list of all PKCS #11 functions that NSS will use? Your token should expect to implement all the PKCS #11 functions that make sense for your token. NSS continues to evolve, and periodically enhances it's functionality by using a more
complete list of PKCS #11 functions. You should have implementations for all the functions specified in the version of the PKCS #11 spec your token implements. If you do not actually do the operation specified by that function, you can return CKR_FUNCTION_NOT_SUPPORTED. Will NSS get the user's CA certificate via PKCS #11 and push it into the CA certificate database or is the CA certificate database expec...
...ved is currently stored. If the token that has your private keys doesn't also do symmetric operations, for example, it's likely that the internal token will end up doing the symmetric operations. Is the PKCS #11 module supplied with NSS accessible through a shared library? Yes, the token is call softokn3 (softokn3.dll on windows, libsoftokn3.so on most unix platforms). The NSS softokn3 is not a
complete PKCS #11 module, it was implemented only to support NSS, though other products have managed to get it to work in their environment. There are a number of bugs against softoken's non-compliance, but these bugs have lower priority than fixing NSS's non-complient uses of PKCS #11 or adding new features to NSS. If multiple PKCS #11 modules are loaded, how does NSS determine which ones to use for the...
...entifies itself as CKF_LOGIN_REQUIRED, but not CKF_USER_INITIALIZED). It's perfectly valid to reject the password change request with a return value such as CKR_FUNCTION_NOT_SUPPORTED. If you do this, NSS applications display an appropriate error message for the user. If I have my smart card which has initial PIN set at '9999', I insert it into my reader and download with my certificate (keygen
completed), can I issue 'Change Password' from the Firefox to set a new PIN to the smart card? Any scenario that you can give me similar to this process (a way to issue a certificate on an initialized new card)? Yes. First open the Tools/Options/Advanced/Security window in Mozilla and click Security Devices. Then select your PKCS #11 module, click View/Edit, select the token, and click Change Password. F...
SpiderMonkey 31
The Mozilla JavaScript team is pleased to announce the release of SpiderMonkey 31. SpiderMonkey 31 is the JavaScript engine that shipped in Firefox 31. It continues to improve performance over previous SpiderMonkey releases, with a significantly improved garbage collector and other features. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component: JavaScript engine. ...
...sabled; JavaScript code runs in an interpreter, as in previous versions. It's the same language, just not as fast. Migrating to SpiderMonkey 31 The first change most embedders will notice is that SpiderMonkey must now be initialized before it can be used, using the newly-repurposed JS_Init method. After this method is called, normal JSAPI operations are permitted. When all JSAPI operation has
completed, the corresponding JS_ShutDown method (currently non-mandatory, but highly recommended as it may become mandatory in the future) uninitializes SpiderMonkey, cleaning up memory and allocations performed by JS_Init. A major change to SpiderMonkey in 31 is that its APIs support a moving garbage collector. This entailed changing the vast majority of the JSAPI from raw types, such as JS::Value or J...
...tId API changes SpiderMonkey must now be initialized before it can be used. This is performed by calling the new JS_Init method before creating any runtimes or contexts and before compiling, evaluating, or executing any JS script. Once this method has been successfully called, it's okay to call JS_NewRuntime and all the other existing SpiderMonkey APIs as usual. Once all JSAPI operation has
completed, the corresponding JS_ShutDown method uninitializes SpiderMonkey, cleaning up memory and allocations performed by JS_Init. It is not required to call JS_ShutDown at present, but it is strongly recommended: calling it may be required in a future SpiderMonkey release. JavaScript shell changes Detail added/removed methods here... On POSIX platforms, building a threadsafe shell no longer require...
...ctness as primary concerns instead. JS_THREADSAFE is going away, with future versions supporting only thread-safe builds A new debugging API is on the way to replace JSD. Release Notes Errata This is a list of changes which need to be made to the release notes ASAP. Feel free to fix any problems you spot -- this is a Wiki! Don't add anything here -- this is for after the release notes are
completed. :-) ...
Shell global objects
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. ...
...an object o and mark the source as being attached to the DOM element o. If the property is omitted or v is null, don't attribute the source to any DOM element. elementAttributeName if present and not undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns. runOffThreadScript() Wait for off-thread compilation to
complete. If an error occurred, throw the appropriate exception; otherwise, run the script and return its value. offThreadCompileModule(code) Compile code on a helper thread. To wait for the compilation to finish and get the module object, call finishOffThreadModule. finishOffThreadModule() Wait for off-thread compilation to
complete. If an error occurred, throw the appropriate exception; otherwise, r...
...n't close enough to the script's real code, so this function is not fuzzer-safe. The runtime can have only one source retrieval hook active at a time. If fun is not careful, hook could be asked to retrieve the source code for compilations that occurred long before it was set, and that it knows nothing about. The reverse applies as well: the original hook, that we reinstate after the call to fun
completes, might be asked for the source code of compilations that fun performed, and which, presumably, only hook knows how to find. wrapWithProto(obj) Wrap an object into a noop wrapper with prototype semantics. Note: This is not fuzzing safe because it can be used to construct deeply nested wrapper chains that cannot exist in the wild. trackedOpts(fun) Returns an object describing the tracked...
...esetOOMFailure() Remove the allocation failure scheduled by either oomAfterAllocations() or oomAtAllocation() and return whether any allocation had been caused to fail. oomTest(function, [expectExceptionOnFailure = true]) Test that the passed function behaves correctly under OOM conditions by repeatedly executing it and simulating allocation failure at successive allocations until the function
completes without seeing a failure. By default this tests that an exception is raised if execution fails, but this can be disabled by passing false as the optional second parameter. This is also disabled when --fuzzing-safe is specified. Functions available only in DEBUG build if --fuzzing-safe is not specified and parseRegExp(pattern[, flags[, match_only]) Parses a RegExp pattern and returns a tree...
Setting up an update server
Downloading a MAR Prebuilt Nightly MARs can be found here on archive.mozilla.org. Be sure that you use the one that matches your machine's configuration. For example, if you want the Nightly MAR from 2019-09-17 for a 64 bit Windows machine, you probably want the MAR located at https://archive.mozilla.org/pub/firefox/nightly/2019/09/2019-09-17-09-36-29-mozilla-central/firefox-71.0a1.en-US.win64.
complete.mar. Prebuilt MARs for release and beta can be found here. Beta builds are those with a b in the version string. After locating the desired version, the MARs will be in the update directory. You want to use the MAR labelled
complete, not a partial MAR. Here is an example of an appropriate MAR file to use: https://archive.mozilla.org/pub/firefox/releases/69.0b9/update/win64/firefox-69.0b9.complet...
...'s time to build the MAR. First, build Firefox the way you want it to be after updating. If you want it to be the same before and after updating, this step is unnecessary and you can use the same build that you used to create the installation. Then run these commands, substituting <obj dir>, <MAR output path>, <version> and <channel> appropriately: ./mach package touch "<obj dir>/dist/firefox/pre
complete" MAR="<obj dir>/dist/host/bin/mar.exe" MOZ_PRODUCT_VERSION=<version> MAR_CHANNEL_ID=<channel> ./tools/update-packaging/make_full_update.sh <MAR output path> "<obj dir>/dist/firefox" For a local build, <channel> can be default, and <version> can be the value from browser/config/version.txt (or something arbitrarily large like 2000.0a1). Note: It can be a bit tricky to get the make_full_update.
...nd put the MAR file in it. Then, create a file within called update.xml with these contents, replacing <mar name>, <hash> and <size> with the MAR's filename, its sha512 hash, and its file size in bytes. ...
... If you've built your own MAR, you can obtain its sha512 checksum by running the following command, which should work in Linux, macOS, or Win...
History Service Design
This system provides additional performance, flexibility, and querying capabilities over the old one, for both end users and extensions developers. View the service interface definition: nsINavHistoryService.idl. ...
...oiding the overhead due to createstatement calls, before closing the connection these statements need to be finalized though, since not doing that would cause leaking. The internal syncing service takes care of initializing Places, syncing data to disk and finalize statements, so usually that's not a problem. The same pre-compiled statements approach is used in other dependant services and in Auto
complete. Another step to improve performance is mainly dedicated to not locking UI. Since Places is actually not thread-safe and doing most of the work in the main-thread, adding visits (the most common action usually executed on user interaction) could end up locking the UI till the database I/O to save data is
complete. For this reason visits and favicons are added lazily on a timer. In future this wi...
...ecency. Certain scheme are excluded from history, so they will never be added, for example: about, view-source, chrome. If a page can be added we first check if it exists already, then it is added or updated accordingly to the previous check, and common attributes are set based on concurrent visit properties. Typed means the page as a typed visit, hidden means the page should not be shown in auto
complete, while frecency is the relevance the page will have in locationbar queries. Finally observers are notified a new visit has been added. Every visit is identified by its visit date, and a visit type (also known as transition type) that represents how we have come to that page (typed, click, redirect, bookmark, etc.). An additional property of a visit is the visit we have come from, this is used to...
...ned. An implementer working on a UI can then associate a viewer with the result, so that it will be notified when the result tree changes. Queries can act on a variety of datas, coming from all dependant services, so it is possible to query history, bookmarks or both, also with values coming from other services like tags, annotations. Result nodes can be simple uri nodes with page attributes or
complete visit attributes, or can be containers (folders, other queries, dynamic containers and so on). See Querying Places for deeper knowledge on the actual implementation. Expiration Expiration is an important part of data management for two reasons: Privacy: expiring data based on user interaction is important, nothing must be left behind on a page removal Database maintenance: having cleaner a...
nsIContentPrefCallback2
handl...
... handleError() Called when an error o...
... 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. ...
...
COMPLETE_OK 0
COMPLETE_ERROR 1 Methods handleCompletion() Called when the method finishes. This will be called exactly once for each method invocation, and afterward no other callback methods will be called. 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 nsIConten...
nsIDownload
onents/downloads/public/nsIDownload.idlScriptable This interface describes a download object. Download objects are used by the Download Manager (see nsIDownloadManager to manage files that are queued to download, being downloaded, and finished being downloaded.) Inherits from: nsITransfer Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Note: Once the download is
completed, the Download Manager stops updating the nsIDownload object.
Completed states are nsIDownloadManager::DOWNLOAD_FINISHED, nsIDownloadManager::DOWNLOAD_FAILED, and nsIDownloadManager::DOWNLOAD_CANCELED. Attributes Attribute Type Description amountTransferred long long The number of bytes downloaded so far. Read only. cancelable nsICancelable An objec...
...ompleted states are nsIDownloadManager::DOWNLOAD_FINISHED, nsIDownloadManager::DOWNLOAD_FAILED, and nsIDownloadManager::DOWNLOAD_CANCELED. Attributes Attribute Type Description amountTransferred long long The number of bytes downloaded so far. Read only. cancelable nsICancelable An object that can be used to cancel the download. Once the download is
complete, this value is set to null. Read only. displayName AString A user-readable description of the transfer. Read only. id unsigned long The ID by which the download is identified uniquely in the database - not globally unique. For example, a private download and a public one might have identical ids. Can only be safely used for direct database manipulation in the datab...
.... Read only. Deprecated since Gecko 19.0 guid AString The guid of the download that is stored in the database. Has the form of twelve alphanumeric characters. Read only. MIMEInfo nsIMIMEInfo Provides the targets relevant MIME information, including its MIME type, helper application, and whether or not the helper should be executed automatically once the download is
complete. Read only. Optional percent
Complete long The percentage of the file transfer that has been
completed, or -1 if the file's size is unknown. Read only. referrer nsIURI The referrer URI of the download. This is only valid for HTTP downloads, and can be null. Read only. resumable boolean Indicates if the download can be resumed after being paused or no...
...Read only. startTime long long The time at which the transfer was started. Read only. state short The downloads current state. See nsIDownloadManager.Constants. Read only. target nsIURI The target of the transfer. Read only. targetFile nsILocalFile Indicates the location at which the downloaded file will be (or is, if the download is
complete) stored. Read only. See also nsIDownloadManager nsIDownloadProgressListener nsIXPInstallManagerUI ...
nsISelectionController
(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void characterExtendForBackspace(); Native code only! void characterExtendForDelete(); Native code only! ...
... void characterExtendForBackspace(); Native code only! void characterExtendForDelete(); Native code only! ...
...and offsets are actually rendered in the current precontext. boolean checkVisibility( in nsIDOMNode node, in short startOffset, in short endOffset ); Parameters node nsIDOMNode to test. startOffset Offset in DOM to first char of textnode to test. endOffset Offset in DOM to last char of textnode to test. Return value true if visible, false if not.
completeMove() Will move page view to the top or bottom of the document this will also have the effect of collapsing the selection if the extend = PR_FALSE the "point" of selection that is extended is considered the "focus" point, or the last point adjusted by the selection. void
completeMove( in boolean forward, in boolean extend ); Parameters forward Forward or backward if PR_FALSE. ...
...will also have the effect of collapsing the selection if the extend = PR_FALSE the "point" of selection that is extended is considered the "focus" point, or the last point adjusted by the selection. void
completeMove( in boolean forward, in boolean extend ); Parameters forward Forward or backward if PR_FALSE. extend Should it collapse the selection or extend it?
completeScroll() Will move page view to the top or bottom of the document. void
completeScroll( in boolean forward ); Parameters forward Forward or backward if PR_FALSE. getCaretEnabled() Gets the current state of the caret, as set by setCaretEnabled(). boolean getCaretEnabled(); Parameters None. Return value If aOutEnabled==null, returns NS_ERROR_INVALID_ARG else NS_OK. getDisplaySele...
XPCOM Interface Reference by grouping
nitions. Security This section contains APIs for secure channel communications System This section contains Application level interfaces including calls to external support elements (such as device calls). This is the root element and may contain some functions defined in other groups. User This section contains elements specific to a given user's data storage. ...
... This section contains APIs for secure channel communications System This section contains Application level interfaces including calls to external support elements (such as device calls). This is the root element and may contain some functions defined in other groups. User This section contains elements specific to a given user's data storage. ...
...r secure channel communications System This section contains Application level interfaces including calls to external support elements (such as device calls). This is the root element and may contain some functions defined in other groups. User This section contains elements specific to a given user's data storage. ...
...ations System This section contains Application level interfaces including calls to external support elements (such as device calls). This is the root element and may contain some functions defined in other groups. User This section contains elements specific to a given user's data storage. ...
Creating a gloda message query
//developer.mozilla.org/docs/Mozilla/Thunderbird/Thunderbird_extensions/Demo_Addon, Demo3, it seems that the attributeName given in these files is the constraintname to be used (e.g. query.subjectMatches(searchString) for message subject (compare fundattr.js line 145 ). Create a collection from the query Your listener is notified as messages are added to the collection as the database query
completes. You may also see new messages show up if new messages are indexed that meet the constraints. let myListener = { /* called when new items are returned by the database query or freshly indexed */ onItemsAdded: function myListener_onItemsAdded(aItems, aCollection) { }, /* called when items that are already in our collection get re-indexed */ onItemsModified: function myListener_onItemsM...
... The max number of messages which are returned is governed by a preference: "mailnews.database.global.search.msg.limit" Although you can deal with the messages as they show up via the listener, the list of message...
... The max number of messages which are returned is governed by a preference: "mailnews.database.global.search.msg.limit" Although you can deal with the messages as they show up via the listener, the list of messages in the collection is...
...Each m...
Gloda examples
ction _onItemsAdded(aItems, aCollection) { }, /* called when items that are already in our collection get re-indexed */ onItemsModified: function _onItemsModified(aItems, aCollection) { }, /* called when items that are in our collection are purged from the system */ onItemsRemoved: function _onItemsRemoved(aItems, aCollection) { }, /* called when our database query
completes */ onQuery
Completed: function _onQuery
Completed(conversation_coll) { try { for (var conv in conversation_coll) { //do something with the Conversation here alert(conv.subject); } } catch (e) {} } } glodaMessage.conversation.getMessagesCollection(aListener) Alternatively if you need to get a conversation based on the...
...ction _onItemsAdded(aItems, aCollection) { }, /* called when items that are already in our collection get re-indexed */ onItemsModified: function _onItemsModified(aItems, aCollection) { }, /* called when items that are in our collection are purged from the system */ onItemsRemoved: function _onItemsRemoved(aItems, aCollection) { }, /* called when our database query
completes */ onQuery
Completed: function _onQuery
Completed(aCollection) { var items = aCollection.items; for (msg of items) { alert(msg.subject); }; } }; collection = id_q.getCollection(myListener); Show all messages where the from, to and CC values include a specified email address At present there doesn't appear to be any way of going directly from an ema...
...d_q.kind("email"); id_q.value("test@example.com"); id_coll = id_q.getCollection({ onItemsAdded: function _onItemsAdded(aItems, aCollection) { }, onItemsModified: function _onItemsModified(aItems, aCollection) { }, onItemsRemoved: function _onItemsRemoved(aItems, aCollection) { }, onQuery
Completed: function _onQuery
Completed(id_coll) { //woops no identity if (id_coll.items.length <= 0) return; id = id_coll.items[0]; //now we use the identity to find all messages that person was involved with msg_q=Gloda.newQuery(Gloda.NOUN_MESSAGE) msg_q.involves(id) ...
... onItemsModified: function _onItemsModified(aItems, aCollection) { }, /* called when items that are in our collection are purged from the system */ onItemsRemoved: function _onItemsRemoved(aItems, aCollection) { }, /* called when our database query
completes */ onQuery
Completed: function _onQuery
Completed(msg_coll) { try { while(msg = msg_coll.items.pop()) { //do something with the messages here alert(msg.subject); } ...
WebIDL bindings
t32_t); }; [Deprecated="tag"] When deprecating an interface or method, the [Deprecated] annotation causes the WebIDL compiler to insert code that generates deprecation warnings. This annotation can be added to interface methods or interfaces. Adding this to an interface causes a warning to be issued the first time the object is constructed, or any static method on the object is invoked. The
complete list of valid deprecation tags is maintained in nsDeprecatedOperationList.h. Each new tag requires that a localized string be defined, containing the deprecation message to display. [CrossOriginReadable] Used to flag an attribute that, when read, will not have the same-origin constraint tested: it can be read from a context with a different origin. [CrossOriginWrite] Used to flag an attribut...
...rors and corresponding messages is in dom/bindings/Errors.msg. ThrowJSException: allows throwing a preexisting JS exception value. However, the MightThrowJSException() method must be called before any such exceptions are thrown (even if no exception is thrown). Failed: checks whether an exception has been thrown on this ErrorResult. ErrorCode: returns a failure nsresult representing (perhaps in
completely) the state of this ErrorResult. operator=: takes an nsresult and acts like Throw if the result is an error code, and like a no-op otherwise (unless an exception has already been thrown, in which case it asserts). This should only be used for legacy code that has nsresult everywhere; we would like to get rid of this operator at some point. Events Simple Event interfaces can be automatically ...
...ng-to-long-js-maplike;1", Constructor()] interface StringToLongMaplike { readonly maplike<DOMString, long>; }; Has these JS functions available to it: // Sets a certain key with a certain value. Exception thrown on wrong types. this.__DOM_IMPL__.__set(aKey, aValue); // Deletes a key. Returns a boolean, true if key exists and was deleted, false otherwise. this.__DOM_IMPL__.__delete(aKey); //
Completely clear all values from maplike storage this.__DOM_IMPL__.__clear(); Setlike The following interface: [JSImplementation="@mozilla.org/dom/string-js-setlike;1", Constructor()] interface StringSetlike { readonly setlike<DOMString>; }; Has these JS functions available to it: // Adds a key to a set. Exception thrown on wrong types. this.__DOM_IMPL__.__add(aKey); // Deletes a key. Returns a ...
...erface: [JSImplementation="@mozilla.org/dom/string-js-setlike;1", Constructor()] interface StringSetlike { readonly setlike<DOMString>; }; Has these JS functions available to it: // Adds a key to a set. Exception thrown on wrong types. this.__DOM_IMPL__.__add(aKey); // Deletes a key. Returns a boolean, true if key exists and was deleted, false otherwise. this.__DOM_IMPL__.__delete(aKey) //
Completely clear all values from maplike storage this.__DOM_IMPL__.__clear(); Determining the principal of the caller that invoked the WebIDL API This can be done by calling Component.utils.getWebIDLCallerPrincipal(). Throwing exceptions from JS-implemented APIs There are two reasons a JS implemented API might throw. The first reason is that some unforeseen condition occurred and the second is that a...
Mozilla
get a stacktrace (call stack) for a crash or hang but Breakpad fails because it's a special crasher or a hang. This article describes how to get a stacktrace in those cases with WinDbg on Windows. ...
...l crasher or a hang. This article describes how to get a stacktrace in those cases with WinDbg on Windows. (To get a stacktrace for Thunderbird or some other product, substitute the product name where ever you see Firefox in this instructions.) How to implement a custom auto
complete search component The XUL textbox element supports an auto
complete mechanism that is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. There are actually two auto
complete mechanisms: How to investigate Disconnect failures This article will guide you on how to investigate disconnect failures. An example of such a failure ...
... This page lists the various development tools that we operate and/or maintain here at mozilla.org. Naturally, source code for all of these tools is also available. The tools needed to build Mozilla are described on the build page for your platform. Mozilla DOM Hacking Guide Mozilla gives you the opportunity not only to use very powerful and
complete DOM support, but also to work on a world-class implementation of one of the greatest Internet technologies ever created. Mozilla external string guide The Mozilla codebase used to have a notion of "external" strings, which were the string classes visible to code outside of the Mozilla codebase (Extensions, XULRunner applications, and embedders). These cl...
...em The Style System is the module of Mozilla's code responsible for the loading and parsing of CSS style sheets, and the computation of computed values for all CSS properties. The handling of those computed values is the responsibility of other parts of the code. Mozilla Style System Documentation See also the style techtalk for more
complete although less detailed documentation. Mozilla SVG Project Since you have come this far, you probably already know that SVG stands for Scalable Vector Graphics, and that it is an XML language for sophisticated 2-dimensional graphics. SVG is to graphics what XHTML is to text, MathML is to mathematical equations and CML is to the description of chemical mol...
Examine and edit CSS - Firefox Developer Tools
p support in the Style Editor documentation. Overridden declarations If a CSS declaration is overridden by some other CSS rule with a greater weight, then the declaration is shown with a line through it. Overridden declarations have a funnel next to them. Click the funnel to filter the rule view to show only the rules applying to the current node that try to set the same property: that is, the
complete cascade for the given property. This makes it easy to see which rule is overriding the declaration: View @media rules for Print You can toggle the display into a mode that emulates @media rules for print. When on, any rules defined for printing the page will be displayed similar to the "Print Preview" mode that many word processing applications provide. View @media rules for color-scheme...
... Icon Value Description null The prefers-color-scheme media feature is not defined. light The user prefers a light interface. dark The user prefers a dark interface. Note that the first three states of the button may be difficult to distinguish visually. They typically produce a similar effect. Examine computed CSS To see the
complete computed CSS for the selected element, select the Computed panel in the righthand pane. This panel shows the calculated value that each CSS property has for the selected element. (This calculated value is exactly the same as what getComputedStyle would return.) You can Tab through the styles to select them, and you can find more information about each property -- pressing F1 on a selected prop...
...ick on a declaration or a selector in the Rules view you can edit it and see the results immediately. You can also Tab through the different existing properties and values, and start editing them by pressing Enter or Space. To add a new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace). As you start typing a property name, you'll see a list of auto
complete suggestions. Press Tab to accept the current suggestion or Up and Down to move through the list. The default choice is the most common property that starts with the letters you've typed. For example, here the user has typed "c" and the default choice is "color": If you enter an invalid value for a property when editing it, or an unknown property name, a yellow alert icon appears besides the de...
... a yellow alert icon appears besides the declaration. Edits that you make in the Rules view are reflected in the Style Editor, and vice versa. Any changes you make are temporary: reloading the page will restore the original styling. While you're editing CSS, the context menu you'll see is the normal one for working with editable text: CSS variable autocompletion CSS variable names will auto-
complete depending on the variables defined in the CSS. If you enter var( into a property value and then type a dash (-), any variables you have declared in your CSS will then appear in an auto
complete list, which shows a color swatch so you can see exactly what color each variable choice is storing (bug 1451211). In addition, hovering over a CSS variable name brings up a tooltip showing what color v...
Web Console remoting - Firefox Developer Tools
older. The WebConsoleClient lives in WebConsoleClient.jsm (in toolkit/devtools/webconsole) and it is used by the Web Console when working with the Web Console actor. To see how the debugger is used in the Web Console code, look in browser/devtools/webconsole/webconsole.js, and search for WebConsoleConnectionProxy. The new Web Console actors are: The WebConsoleActor allows JS evaluation, auto
complete, 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 argume...
...onMessage 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. ...
...on.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. ...
...elperResult 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. Auto
complete and more The auto
complete request packet: { "to": "conn0.console9", "type": "auto
complete", "text": "d", "cursor": 1 } The response packet: { "from": "conn0.console9", "matches": [ "decodeURI", "decodeURIComponent", "defaultStatus", "devicePixelRatio", "disableExternalCapture", "dispatchEvent", "doMyXHR", "document", "dump" ], "matchProp": "d" } There's also the clearMessagesCache request packet that has no response. This clears the...
CanvasRenderingContext2D.filter - Web APIs
e 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 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 particu...
...he shadow. <offset-y>: See <length> for possible units. Specifies the vertical distance of the shadow. <blur-radius>: The larger this value, the bigger the blur, so the shadow becomes bigger and lighter. Negative values are not allowed. <color>: See <color> values for possible keywords and notations. grayscale() A CSS <percentage>. Converts the drawing to grayscale. A value of 100% is
completely grayscale. A value of 0% leaves the drawing unchanged. hue-rotate() A CSS <angle>. Applies a hue rotation on the drawing. A value of 0deg leaves the input unchanged. invert() A CSS <percentage>. Inverts the drawing. A value of 100% means
complete inversion. A value of 0% leaves the drawing unchanged. opacity() A CSS <percentage>. Applies transparency to the drawing. A value of 0% means co...
...A value of 0% leaves the drawing unchanged. none No filter is applied. Initial value. ...
...A value of 0% leaves the drawing unchanged. none No filter is applied. Initial value. Examples To view these examples, make sure to use a browser that supports this feature; see the compatibility table below. ...
Basic concepts - Web APIs
el. Everything you do in IndexedDB always happens in the context of a transaction. The IndexedDB API provides lots of objects that represent indexes, tables, cursors, and so on, but each of these is tied to a particular transaction. Thus, you cannot execute commands or open cursors outside of a transaction. Transactions have a well-defined lifetime, so attempting to use a transaction after it has
completed throws exceptions. Also, transactions auto-commit and cannot be committed manually. This transaction model is really useful when you consider what might happen if a user opened two instances of your web app in two different tabs simultaneously. Without transactional operations, the two instances could interfere with each other's modifications. If you are not familiar with transactions in a da...
...in and stays constant throughout its lifetime. The name can be any string value (including an empty string). Current version. When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time. ...
... durable In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction IDBTransaction.on
complete was fired only when all data was guaranteed to have been flushed to disk. As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702), which is the same behaviour as other IndexedDB-supporting browsers. In this case the
complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consu...
...t if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further. Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the
complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config. object store The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Record...
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. ...
...hed, 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.on
complete = 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 track via XHR (AudioContext.d...
...ineAudioContext 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 the source code too.) // define online ...
...e = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; source.connect(offlineCtx.destination); source.start(); //source.loop = true; offlineCtx.startRendering().then(function(renderedBuffer) { console.log('Rendering
completed successfully'); var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var song = audioCtx.createBufferSource(); song.buffer = renderedBuffer; song.connect(audioCtx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('Rendering failed: ' + err); // No...
OfflineAudioContext - Web APIs
v> a:hover text { fill: #0095DD; pointer-events: all;} Constructor OfflineAudioContext.OfflineAudioContext() Creates a new OfflineAudioContext instance. 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.on
complete 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 a...
... 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. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface:
complete Fired when the rendering of an offline audio context is
complete. Also available using the on
complete event handler property. Examples In this simple example, we declare 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 an...
...ineAudioContext 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 the source code too.) // define online ...
...e = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; source.connect(offlineCtx.destination); source.start(); //source.loop = true; offlineCtx.startRendering().then(function(renderedBuffer) { console.log('Rendering
completed successfully'); var song = audioCtx.createBufferSource(); song.buffer = renderedBuffer; song.connect(audioCtx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('Rendering failed: ' + err); // Note: The promise should reject when startRendering is called a second time on an O...
PaymentRequest: merchantvalidation event - Web APIs
event. It uses 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. ...
...chant server should access the validation URL in accordance with the payment method documention. 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...
... 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. ...
...vered 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 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. Rel...
PerformanceTiming - Web APIs
o previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. PerformanceTiming.redirectStart Read only When the first HTTP redirect starts. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. PerformanceTiming.redirectEnd Read only When the last HTTP redirect is
completed, that is when the last byte of the HTTP response has been received. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. PerformanceTiming.fetchStart Read only When the browser is ready to fetch the document using an HTTP request. This moment is before the check to any application cache. PerformanceTiming.domainLookupStart Read only ...
...eTiming.domContentLoadedEventStart Read only Right before the parser sent the DOMContentLoaded event, that is right after all the scripts that need to be executed right after parsing have been executed. PerformanceTiming.domContentLoadedEventEnd Read only Right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. PerformanceTiming.dom
Complete Read only When the parser finished its work on the main document, that is when its Document.readyState changes to '
complete' and the corresponding readystatechange event is thrown. PerformanceTiming.loadEventStart Read only When the load event was sent for the current document. If this event has not yet been sent, it returns 0. PerformanceTiming.loadEventEnd Read only When the load ...
... Methods The PerformanceTiming interface doesn't inherit any methods. PerformanceTiming.toJSON() Returns a JSON object representing this PerformanceTiming object. ...
...omplete' and the corresponding readystatechange event is thrown. PerformanceTiming.loadEventStart Read only When the load event was sent for the current document. If this event has not yet been sent, it returns 0. PerformanceTiming.loadEventEnd Read only When the load event handler terminated, that is when the load event is
completed. If this event has not yet been sent, or is not yet
completed, it returns 0. Methods The PerformanceTiming interface doesn't inherit any methods. PerformanceTiming.toJSON() Returns a JSON object representing this PerformanceTiming object. Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming' in that specification. Recommendation Initial definition. ...
RTCPeerConnection: icecandidate event - Web APIs
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 deliver this to the remote peer just like any standard candidate, as described under Sharing a new candidate above. This ensures that the remote peer is given the end-of-candidates notification as well. As you see in the code in the previous sec...
...ny that might have an empty candidate string. Only candidates for which the event's candidate property is null are not forwarded across the signaling connection. The end-of-candidates indication is described in section 9.3 of the Trickle ICE draft specification (note that the section number is subject to change as the specification goes through repeated drafts). Indicating that ICE gathering is
complete Once all ICE transports have finished gathering candidates and the value of the RTCPeerConnection object's iceGatheringState has made the transition to
complete, an icecandidate event is sent with the value of
complete set to null. This signal exists for backward compatibility purposes and does not need to be delivered onward to the remote peer (which is why the code snippet above checks to see...
... This is a more reliable approach than looking at the individual ICE messages for one indicating that ...
... This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished. ...
Using Service Workers - Web APIs
rker is attempted when service worker-controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker (this can be used to start the process of populating an IndexedDB, and caching site assets). This is really the same kind of procedure as installing a native or Firefox OS app -- making everything available 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 real example -- what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? This is a standard thing to want to do, but it can be a bit of a pain. We can use .onload to only display the image after it's loaded, but what about events that start happening before we start listening to them? We could try to work around this using .
complete, but it's still not foolproof, and what about multiple images? And, ummm, it's still synchronous, so blocks the main thread. Instead, we could build our own promise to handle this kind of case. (See our Promises test example for the source code, or look at it running live.) Note: A real service worker implementation would use caching and onfetch rather than the XMLHttpRequest API. Those featu...
... you can specify a list of max scopes for that worker. In Firefox, Service Worker APIs are hidden and cannot be used when the user is in private browsing mode. Install and activate: populating your cache After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site. The install event is fired when an install is successfully
completed. The install event is generally used to populate your browser's offline caching capabilities with the assets you need to run your app offline. To do this, we use Service Worker's brand new storage API -- cache -- a global object on the service worker that allows us to store assets delivered by responses, and keyed by their requests. This API works in a similar way to the browser's standard cache...
... amount of cache storage that a given service worker can use. The browser does its best to manage disk space, but it may delete the Cache storage for an origin. The browser will generally delete all of the data for an origin or none of the data for an origin. Promises passed into waitUntil() will block other events until completion, so you can rest assured that your clean-up operation will have
completed by the time you get your first fetch event on the new service worker. self.addEventListener('activate', (event) => { var cacheKeeplist = ['v2']; event.waitUntil( caches.keys().then((keyList) => { return Promise.all(keyList.map((key) => { if (cacheKeeplist.indexOf(key) === -1) { return caches.delete(key); } })); }) ); }); Developer tools Chr...
SpeechSynthesisErrorEvent.error - Web APIs
Syntax myError = event.error; Value A DOMString containing an error code. Possible codes are: canceled A SpeechSynthesis.cancel method call caused the SpeechSynthesisUtterance to be removed from the queue before it had begun being spoken. ...
...ing containing an error code. Possible codes are: canceled A SpeechSynthesis.cancel method call caused the SpeechSynthesisUtterance to be removed from the queue before it had begun being spoken. interrupted A SpeechSynthesis.cancel method call caused the SpeechSynthesisUtterance to be interrupted after it had begun being spoken and before it
completed. ...
...d A SpeechSynthesis.cancel method call caused the SpeechSynthesisUtterance to be interrupted after it had begun being spoken and before it
completed. ...
... time because the user-agent couldn't access the audio output device (for example, the user may need to correct this by closing another application.) audio-hardware The operation couldn't be
completed at this time because the user-agent couldn't identify an audio output device (for example, the user may need to connect a speaker or configure system settings.) network The operation couldn't be
completed at this time because some required network communication failed. synthesis-unavailable The operation couldn't be
completed at this time because no synthesis engine was available (For example, the user may need to install or configure a synthesis engine.) synthesis-failed The operation failed because the synthesis engine raised an error. language-unavailable No appropriate voice was availab...
SubtleCrypto.encrypt() - Web APIs
IST SP800-38D. One major difference between this mode 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. function getMessageEncoding() { const messageBox = document.querySelector(".rsa-oaep #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } function encryptMessage(publicKey) { let encoded = getMessageEncoding(); return window.crypto.subtle.encrypt( { name: "RSA-OAEP" }, publicKey, encoded ); } ...
...e = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } function encryptMessage(publicKey) { let encoded = getMessageEncoding(); return window.crypto.subtle.encrypt( { name: "RSA-OAEP" }, publicKey, encoded ); } AES-CTR This code fetches the contents of a text box, encodes it for encryption, and encrypts it using AES in CTR mode. See the
complete code on GitHub. function getMessageEncoding() { const messageBox = document.querySelector(".aes-ctr #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } function encryptMessage(key) { let encoded = getMessageEncoding(); // counter will be needed for decryption counter = window.crypto.getRandomValues(new Uint8Array(16)); return wi...
....buffer, 'AES-CTR' , false, ["encrypt", "decrypt"]); const encrypted_content = await window.crypto.subtle.encrypt( { name: "AES-CTR", counter: iv, length: 128 }, key_encoded, data ); //Uint8Array console.log(encrypted_content); AES-CBC This code fetches the contents of a text box, encodes it for encryption, and encrypts it using AES in CBC mode. See the
complete code on GitHub. function getMessageEncoding() { const messageBox = document.querySelector(".aes-cbc #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } function encryptMessage(key) { let encoded = getMessageEncoding(); // iv will be needed for decryption iv = window.crypto.getRandomValues(new Uint8Array(16)); return window.crypt...
...n encryptMessage(key) { let encoded = getMessageEncoding(); // iv will be needed for decryption iv = window.crypto.getRandomValues(new Uint8Array(16)); return window.crypto.subtle.encrypt( { name: "AES-CBC", iv }, key, encoded ); } AES-GCM This code fetches the contents of a text box, encodes it for encryption, and encrypts it using AES in GCM mode. See the
complete code on GitHub. function getMessageEncoding() { const messageBox = document.querySelector(".aes-gcm #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } function encryptMessage(key) { let encoded = getMessageEncoding(); // iv will be needed for decryption iv = window.crypto.getRandomValues(new Uint8Array(12)); return window.crypt...
SubtleCrypto.exportKey() - Web APIs
g exceptions is encountered: InvalidAccessError Raised when trying to export a non-extractable key. NotSupported Raised when trying to export in an unknown format. TypeError Raised when trying to use an invalid format. Examples Note: You can try the working examples out on GitHub. Raw export This example exports an AES key as an ArrayBuffer containing the bytes for the key. See the
complete code on GitHub. /* Export the given key and write it into the "exported-key" space. */ async function exportCryptoKey(key) { const exported = await window.crypto.subtle.exportKey( "raw", key ); const exportedKeyBuffer = new Uint8Array(exported); const exportKeyOutput = document.querySelector(".exported-key"); exportKeyOutput.textContent = `[${exportedKeyBuffer}]`; } /* Genera...
...w.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, ["encrypt", "decrypt"] ).then((key) => { const exportButton = document.querySelector(".raw"); exportButton.addEventListener("click", () => { exportCryptoKey(key); }); }); PKCS #8 export This example exports an RSA private signing key as a PKCS #8 object. The exported key is then PEM-encoded. See the
complete code on GitHub. /* Convert an ArrayBuffer into a string from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String */ function ab2str(buf) { return String.fromCharCode.apply(null, new Uint8Array(buf)); } /* Export the given key and write it into the "exported-key" space. */ async function exportCryptoKey(key) { const exported = await window.crypto.
...nt: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["sign", "verify"] ).then((keyPair) => { const exportButton = document.querySelector(".pkcs8"); exportButton.addEventListener("click", () => { exportCryptoKey(keyPair.privateKey); }); }); SubjectPublicKeyInfo export This example exports an RSA public encryption key as a PEM-encoded SubjectPublicKeyInfo object. See the
complete code on GitHub. /* Convert an ArrayBuffer into a string from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String */ function ab2str(buf) { return String.fromCharCode.apply(null, new Uint8Array(buf)); } /* Export the given key and write it into the "exported-key" space. */ async function exportCryptoKey(key) { const exported = await window.crypto.
...ength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["encrypt", "decrypt"] ).then((keyPair) => { const exportButton = document.querySelector(".spki"); exportButton.addEventListener("click", () => { exportCryptoKey(keyPair.publicKey); }); }); JSON Web Key import This code exports an ECDSA private signing key as a JSON Web Key object. See the
complete code on GitHub. /* Export the given key and write it into the "exported-key" space. */ async function exportCryptoKey(key) { const exported = await window.crypto.subtle.exportKey( "jwk", key ); const exportKeyOutput = document.querySelector(".exported-key"); exportKeyOutput.textContent = JSON.stringify(exported, null, " "); } /* Generate a sign/verify key pair, then set up an e...
SubtleCrypto.importKey() - Web APIs
8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; Examples Note: You can try the working examples on GitHub. Raw import This example imports an AES key from an ArrayBuffer containing the bytes to use. See the
complete code on GitHub. const rawKey = window.crypto.getRandomValues(new Uint8Array(16)); /* Import an AES secret key from an ArrayBuffer containing the raw bytes. Takes an ArrayBuffer string containing the bytes, and returns a Promise that will resolve to a CryptoKey representing the secret key. */ function importSecretKey(rawKey) { return window.crypto.subtle.importKey( "raw", rawKey, "...
...es an ArrayBuffer string containing the bytes, and returns a Promise that will resolve to a CryptoKey representing the secret key. */ function importSecretKey(rawKey) { return window.crypto.subtle.importKey( "raw", rawKey, "AES-GCM", true, ["encrypt", "decrypt"] ); } PKCS #8 import This example imports an RSA private signing key from a PEM-encoded PKCS #8 object. See the
complete code on GitHub. /* Convert a string into an ArrayBuffer from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String */ function str2ab(str) { const buf = new ArrayBuffer(str.length); const bufView = new Uint8Array(buf); for (let i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } const pemEncodedKe...
... binaryDer, { name: "RSA-PSS", // Consider using a 4096-bit key for systems that require long-term security modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["sign"] ); } SubjectPublicKeyInfo import This example imports an RSA public encryption key from a PEM-encoded SubjectPublicKeyInfo object. See the
complete code on GitHub. // from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String function str2ab(str) { const buf = new ArrayBuffer(str.length); const bufView = new Uint8Array(buf); for (let i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } const pemEncodedKey = `-----BEGIN PUBL...
...vert from a binary string to an ArrayBuffer const binaryDer = str2ab(binaryDerString); return window.crypto.subtle.importKey( "spki", binaryDer, { name: "RSA-OAEP", hash: "SHA-256" }, true, ["encrypt"] ); } JSON Web Key import This code imports an ECDSA private signing key, given a JSON Web Key object that represents it. See the
complete code on GitHub. const jwkEcKey = { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; /* Import a PEM encoded RSA private key, to use for RSA-PSS sign...
SubtleCrypto.sign() - Web APIs
ng to the FIPS 198-1 standard. The digest algorithm to use is specified in the HmacKeyGenParams object that you pass into generateKey(), or the HmacImportParams object that you pass into importKey(). Examples Note: You can try the working examples out on GitHub. RSASSA-PKCS1-v1_5 This code fetches the contents of a text box, encodes it for signing, and signs it with a private key. See the
complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window...
...ent.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.crypto.subtle.sign( "RSASSA-PKCS1-v1_5", privateKey, encoded ); RSA-PSS This code fetches the contents of a text box, encodes it for signing, and signs it with a private key. See the
complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsa-pss #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.cryp...
...rsa-pss #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.crypto.subtle.sign( { name: "RSA-PSS", saltLength: 32, }, privateKey, encoded ); ECDSA This code fetches the contents of a text box, encodes it for signing, and signs it with a private key. See the
complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".ecdsa #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.crypto...
...sa #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.crypto.subtle.sign( { name: "ECDSA", hash: {name: "SHA-384"}, }, privateKey, encoded ); HMAC This code fetches the contents of a text box, encodes it for signing, and signs it with a secret key. See the
complete source code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".hmac #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } let encoded = getMessageEncoding(); let signature = await window.crypto.
SubtleCrypto.verify() - Web APIs
ion key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. Supported algorithms The verify() method supports the same algorithms as the sign() method. Examples Note: You can try the working examples out on GitHub. RSASSA-PKCS1-v1_5 This code uses a public key to verify a signature. See the
complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signa...
....querySelector(".rsassa-pkcs1 .signature-value"); signatureValue.classList.remove("valid", "invalid"); let encoded = getMessageEncoding(); let result = await window.crypto.subtle.verify( "RSASSA-PKCS1-v1_5", publicKey, signature, encoded ); signatureValue.classList.add(result ? "valid" : "invalid"); } RSA-PSS This code uses a public key to verify a signature. See the
complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsa-pss #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature.
...signature-value"); signatureValue.classList.remove("valid", "invalid"); let encoded = getMessageEncoding(); let result = await window.crypto.subtle.verify( { name: "RSA-PSS", saltLength: 32, }, publicKey, signature, encoded ); signatureValue.classList.add(result ? "valid" : "invalid"); } ECDSA This code uses a public key to verify a signature. See the
complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".ecdsa #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature. *...
...ure-value"); signatureValue.classList.remove("valid", "invalid"); let encoded = getMessageEncoding(); let result = await window.crypto.subtle.verify( { name: "ECDSA", hash: {name: "SHA-384"}, }, publicKey, signature, encoded ); signatureValue.classList.add(result ? "valid" : "invalid"); } HMAC This code uses a secret key to verify a signature. See the
complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".hmac #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature...
SubtleCrypto.wrapKey() - Web APIs
ES-KW over another AES mode such as AES-GCM is that AES-KW does not require an initialization vector. To use AES-KW, the input must be a multiple of 64 bits. AES-KW is specified in 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", "...
.../ window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, ["encrypt", "decrypt"] ) .then((secretKey) => { return wrapCryptoKey(secretKey); }) .then((wrappedKey) => { console.log(wrappedKey); }); PKCS #8 wrap This example wraps an RSA private signing key. It uses "pkcs8" as the export format and AES-GCM, with a password-derived key, to encrypt it. See the
complete code on GitHub. let salt; let iv; /* 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, ["derive...
...licExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["sign", "verify"] ) .then((keyPair) => { return wrapCryptoKey(keyPair.privateKey); }) .then((wrappedKey) => { console.log(wrappedKey); }); SubjectPublicKeyInfo wrap This example wraps an RSA public encryption key. It uses "spki" as the export format and AES-CBC, with a password-derived key, to encrypt it. See the
complete code on GitHub. let salt; let iv; /* 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, ["derive...
... publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["encrypt", "decrypt"] ) .then((keyPair) => { return wrapCryptoKey(keyPair.publicKey); }) .then((wrappedKey) => { console.log(wrappedKey); }); JSON Web Key import This code wraps an ECDSA private signing key. It uses "jwk" as the export format and AES-GCM, with a password-derived key, to encrypt it. See the
complete code on GitHub. let salt; let iv; /* 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, ["derive...
TextRange - Web APIs
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. ...
...Range(). 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 object and the left edge that
completely contains the TextRange object. TextRange.boundingTopRead only Returns the distance between the top edge 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...
... Move the caret to the beginning or end of the current range. TextRange.duplicate() Returns a copy of TextRange. TextRange.execCommand() Executes a command on the current document, the current selection, or the given scope. TextRange.expand() Expand the range to include the full range of specified units. For example, expanding a "word" means that the words at both ends of the range will
completely included in the range. xpand to wor may become expand to words, etc. TextRange.findText() Searches the specified text in the original range and adjusts the range to include the first match. TextRange.inRange() 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 t...
... Moves the end of the range by a specified number of units. TextRange.moveStart() Moves the start of the range by a specified number of units. TextRange.moveToElementText() Causes the range to contain the text of the specified element. Can only be used on Element objects. TextRange.parentElement() Returns the parent element of the range, which is the smallest element that contains the range
completely. If the selection contains more than one element, when you modify the contents of the selection, the contents will be placed in the corresponding position of the parent element instead of the child element. TextRange.pasteHTML() Paste the HTML content into the given range and replace any previous text and HTML elements in the range. TextRange.queryCommandEnabled() Returns a Boolean indicati...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
The WebGLRenderingContext.checkFramebufferStatus() method of the WebGL API returns the
completeness status of the WebGLFramebuffer object. Syntax GLenum gl.checkFramebufferStatus(target); Parameters target A GLenum specifying the binding point (target). Possible values: gl.FRAMEBUFFER: Collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. When using a WebGL 2 context, the following values are available additionally: gl.DRAW_FRAMEBUFFER: Equivalent to gl.FRAMEBUFFER. Used as a destination for drawing, rendering, clearing, and writing operations. gl.READ_FRAMEBUFFER: Used as a source for reading operations. Return value A GLenum indicating the
completeness status of the framebuffer or 0 if an error occurs. Possible...
...lues are available additionally: gl.DRAW_FRAMEBUFFER: Equivalent to gl.FRAMEBUFFER. Used as a destination for drawing, rendering, clearing, and writing operations. gl.READ_FRAMEBUFFER: Used as a source for reading operations. Return value A GLenum indicating the
completeness status of the framebuffer or 0 if an error occurs. Possible enum return values: gl.FRAMEBUFFER_
COMPLETE: The framebuffer is ready to display. gl.FRAMEBUFFER_IN
COMPLETE_ATTACHMENT: The attachment types are mismatched or not all framebuffer attachment points are framebuffer attachment
complete. gl.FRAMEBUFFER_IN
COMPLETE_MISSING_ATTACHMENT: There is no attachment. gl.FRAMEBUFFER_IN
COMPLETE_DIMENSIONS: Height and width of the attachment are not the same. gl.FRAMEBUFFER_UNSUPPORTED: The format of th...
...UFFER_IN
COMPLETE_MISSING_ATTACHMENT: There is no attachment. gl.FRAMEBUFFER_IN
COMPLETE_DIMENSIONS: Height and width of the attachment are not the same. gl.FRAMEBUFFER_UNSUPPORTED: The format of the attachment is not supported or if depth and stencil attachments are not the same renderbuffer. When using a WebGL 2 context, the following values can be returned additionally: gl.FRAMEBUFFER_IN
COMPLETE_MULTISAMPLE: The values of gl.RENDERBUFFER_SAMPLES are different among attached renderbuffers, or are non-zero if the attached images are a mix of renderbuffers and textures. ...
...g a WebGL 2 context, the following values can be returned additionally: gl.FRAMEBUFFER_IN
COMPLETE_MULTISAMPLE: The values of gl.RENDERBUFFER_SAMPLES are different among attached renderbuffers, or are non-zero if the attached images are a mix of renderbuffers and textures. When using the OVR_multiview2 extension, the following value can be returned additionally: ext.FRAMEBUFFER_IN
COMPLETE_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 in
complete. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); // ... gl.checkFramebufferStatus(gl.FRAMEBUFFER); Spe...
WebGL constants - Web APIs
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 COLOR_ATTACHMENT0 0x8CE0 DEPTH_ATTACHMENT 0x8D00 STENCIL_ATTACHMENT 0x8D20 DEPTH_STENCIL_ATTACHMENT 0x821A NONE 0 FRAMEBUFFER_
COMPLETE 0x8CD5 FRAMEBUFFER_IN
COMPLETE_ATTACHMENT 0x8CD6 FRAMEBUFFER_IN
COMPLETE_MISSING_ATTACHMENT 0x8CD7 FRAMEBUFFER_IN
COMPLETE_DIMENSIONS 0x8CD9 FRAMEBUFFER_UNSUPPORTED 0x8CDD FRAMEBUFFER_BINDING 0x8CA6 RENDERBUFFER_BINDING 0x8CA7 MAX_RENDERBUFFER_SIZE 0x84E8 INVALID_FR...
...0x821A DEPTH_STENCIL 0x84F9 DEPTH24_STENCIL8 0x88F0 DRAW_FRAMEBUFFER_BINDING 0x8CA6 READ_FRAMEBUFFER 0x8CA8 DRAW_FRAMEBUFFER 0x8CA9 READ_FRAMEBUFFER_BINDING 0x8CAA RENDERBUFFER_SAMPLES 0x8CAB FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 FRAMEBUFFER_IN
COMPLETE_MULTISAMPLE 0x8D56 Uniforms Constant name Value Description UNIFORM_BUFFER 0x8A11 UNIFORM_BUFFER_BINDING 0x8A28 UNIFORM_BUFFER_START 0x8A29 UNIFORM_BUFFER_SIZE 0x8A2A MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D MAX_COMBINED_UNIFO...
...RM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 Sync objects Constant name Value Description OBJECT_TYPE 0x9112 SYNC_CONDITION 0x9113 SYNC_STATUS 0x9114 SYNC_FLAGS 0x9115 SYNC_FENCE 0x9116 SYNC_GPU_COMMANDS_
COMPLETE 0x9117 UNSIGNALED 0x9118 SIGNALED 0x9119 ALREADY_SIGNALED 0x911A TIMEOUT_EXPIRED 0x911B CONDITION_SATISFIED 0x911C WAIT_FAILED 0x911D SYNC_FLUSH_COMMANDS_BIT 0x00000001 Miscellaneous constants Constant name Value Description COLOR 0x...
...D_SRGB8_ETC2 0x9276 Compresses sRBG8 data with no alpha channel. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9277 Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9278 Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it
completely opaque or transparent. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9279 Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it
completely opaque or transparent. WEBGL_compressed_texture_pvrtc Constant name Value Description COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 RGB compression in 4-bit mode. One...
Writing WebSocket servers - Web APIs
ists so that it's obvious to the client whether the server supports WebSockets. This is important because security issues might arise if the server accepts a WebSockets connection but interprets the data as a HTTP request. So if the Key was "dGhlIHNhbXBsZSBub25jZQ==", the Sec-WebSocket-Accept header's value is "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". Once the server sends these headers, the handshake is
complete and you can start swapping data! Note: The server can send other headers like Set-Cookie, or ask for authentication or redirects via other status codes, before sending the reply handshake. Keeping track of clients This doesn't directly relate to the WebSocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with cli...
...pping data! Note: The server can send other headers like Set-Cookie, or ask for authentication or redirects via other status codes, before sending the reply handshake. Keeping track of clients This doesn't directly relate to the WebSocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have already
completed the handshake. The same client IP address can try to connect multiple times. However, the server can deny them if they attempt too many connections in order to save itself from Denial-of-Service attacks. For example, you might keep a table of usernames or ID numbers along with the corresponding WebSocket and other data that you need to associate with that connection. Exchanging data frames Ei...
...s means the server should concatenate the frame's payload to the last frame it received from that client. Here is a rough sketch, in which a server reacts to a client sending text messages. The first message is sent in a single frame, while the second message is sent across three frames. ...
...The second frame sent by the client has a text payload (opcode=0x1), but the entire message has not arrived yet (FIN=0). ...
Starting up and shutting down a WebXR session - Web APIs
controllers, as well as button presses on the controllers. Emulator usage While somewhat awkward compared to using an actual headset, this makes it possible to experiment with and developer WebXR code on a desktop computer, where WebXR isn't normally available. It also lets you perform some basic testing before taking your code to a real device. Be aware, however, that the emulator does not yet
completely emulate all of the WebXR API, so you may run into problems you're not expecting. Again, carefully read the readme file and make sure you're aware of the limitations before you begin. Important: You should always test your code on actual AR and/or VR hardware before releasing or shipping a product! Emulated, simulated, or polyfilled environments are not an adequate substitute for actual testing...
... headset or similar apparatus. This option is not yet widely supported, as the AR specification is in flux. inline An on-screen presentation of the XR imagery within the context of the document window. If the session couldn't be created for some reason--such as feature policy disallowing its use or the user declining to grant permission to use the headset--the promise gets rejected. So a more
complete function that starts up and returns a WebXR session could look like this: async function createImmersiveSession(xr) { try { session = await xr.requestSession("immersive-vr"); return session; } catch(error) { throw error; } } This function returns the new XRSession or throws an exception if an error occurs while creating the session. Customizing the session In addition to th...
...() method to schedule a callback to be executed when it's time to render the next frame of animation for the WebXR session. The returned value is an ID we can use later to cancel the request if need be, so we save that into worldData as well. In the end, the worldData object is returned to the caller to allow the main code to reference the data it needs later. At this point, the setup process is
complete and we've entered the rendering stage of our application. To learn more about rendering, see the article Rendering and the WebXR frame animation callback. On operational details Obviously, this was a just an example. You don't need a worldData object to store everything; you can store the information you need to maintain any way you want to. You may need different information or have different ...
...ituation as appropriate for your application. Here we discuss both how to request a shutdown of the WebXR session and how to detect when the session has ended, whether by your request or otherwise. Shutting down the session To cleanly shut down the WebXR session when you're done with it, you should call the session's end() method. This returns a promise you can use to know when the shutdown is
complete. async function shutdownXR(session) { if (session) { await session.end(); /* At this point, WebXR is fully shut down */ } } When shutdownXR() returns to its caller, the WebXR session is fully and safely shut down. If you have work that must be done when the session ends, such as releasing resources and the like, you should do that work in your end event handler rather than in you...
Synchronous and asynchronous requests - Web APIs
or(xhr.statusText); } } }; xhr.onerror = function (e) { console.error(xhr.statusText); }; xhr.send(null); Line 2 specifies true for its third parameter to indicate that the request should be handled asynchronously. Line 3 creates an event handler function object and assigns it to the request's onload attribute. This handler looks at the request's readyState to see if the transaction is
complete in line 4; if it is, and the HTTP status is 200, the handler dumps the received content. If an error occurred, an error message is displayed. Line 15 actually initiates the request. The callback routine is called whenever the state of the request changes. Example: writing a function to read an external file In some cases, you must read many external files. This is a standard function which use...
...); The signature of the utility function loadFile declares (i) a target URL to read (via an HTTP GET request), (ii) a function to execute on successful completion of the XHR operation, and (iii) an arbitrary list of additional arguments that are passed through the XHR object (via the arguments property) to the success callback function. Line 1 declares a function invoked when the XHR operation
completes successfully. It, in turn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 11). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function. Line 5 declares a function invoked when th...
...rn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 11). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function. Line 5 declares a function invoked when the XHR operation fails to
complete successfully. Line 11 stores the success callback given as the second argument to loadFile in the XHR object's callback property. Line 12 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable xhr, passed to the success callback function xhrSuccess., and ultimatel...
... synchronous request. var request = new XMLHttpRequest(); request.open('GET', '/bar/foo.txt', false); // `false` makes the request synchronous request.send(null); if (request.status === 200) { console.log(request.responseText); } Line 3 sends the request. The null parameter indicates that no body content is needed for the GET request. Line 5 checks the status code after the transaction is
completed. If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console. Example: Synchronous HTTP request from a Worker One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker. example.html (the main page): <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; ch...
XRSession - Web APIs
isted 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 planes (distances defining how close and how far away objects can be and st...
...ate to match the values specified in the specified XRRenderStateInit dictionary. Any properties not included in the given dictionary are left unchanged from their current values. Events The following events are delivered to XRSession objects. Event Description end Sent to the XRSession object after the WebXR session has ended and all hardware-related functions have
completed. The event is represented by an object of type XRSessionEvent. Also available through the onend event handler property. inputsourceschange An event of type XRInputSourcesChangeEvent sent to the XRSession when the list of active XR input sources has changed. Also available through the oninputsourceschange event handler property. select An event of type XRInputSourc...
...he onend event handler property. inputsourceschange An event of type XRInputSourcesChangeEvent sent to the XRSession when the list of active XR input sources has changed. Also available through the oninputsourceschange event handler property. select An event of type XRInputSourceEvent which is sent to the session when one of the session's input sources has successfully
completed a primary action. This generally corresponds to the user pressing a trigger, touchpad, or button, speaks a command, or performs a recognizable gesture. The select event is sent after the selectstart event is sent and immediately before the selectend event is sent. If select is not sent, then the select action was aborted before being
completed. Also available through the onselect event handl...
...ype XRInputSourceEvent which is sent to the session object when one of its input devices is first engaged by the user in such a way as to cause the primary action to begin. This is the first of the session* event to be sent. Also available through the onselectstart event handler property. squeeze An XRInputSourceEvent sent to indicate that a primary squeeze action has successfully
completed. This indicates that the device being squeezed has been released, and may represent dropping a grabbed object, for example. It is sent immediately before the squeezeend event is sent to indicate that the squeeze action is over. Also available through the onsqueeze event handler property. squeezeend An XRInputSourceEvent sent to the XRSession when the primary squeeze action ends, ...
Web applications and ARIA FAQ - Accessibility
getElementById("percent-loaded"); // Set its ARIA roles and states, so that assistive technologies know what kind of widget it is. progressBar.setAttribute("role", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); // Create a function that can be called at any time to update the value of the progress bar. function updateProgress(percent
Complete) { progressBar.setAttribute("aria-valuenow", percent
Complete); } Will adding ARIA change my page styles or behavior? No, ARIA is only made available to assistive technology APIs, and doesn't affect native browser functionality with respect to the DOM or styling. From the browser's point of view, the native HTML defines the semantic meaning and behavior of an element, with ARIA attributes acti...
...to the use of ARIA where necessary. So, using the example of a progress bar, you can degrade gracefully to a role="progressbar" in cases where the <progressbar> tag isn't supported. Here is an example of the markup used for an HTML5 progress bar: <!DOCTYPE html> <html> <head><title>Gracefully degrading progress bar</title></head> <body> <progress id="progress-bar" value="0" max="100">0%
complete</progress> <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 setupPro...
...Element) !== "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(percent
Complete) { if (!supportsHTML5Progress) { // HTML5 <progress> isn't supported by this browser, // so we need to update the aria-valuenow attribute progressBar.setAttribute("aria-valuenow", percent
Complete); } else { // HTML5 <progress> is supported, so update the value attribute instead. progressBar.setAttribute("value", percent
Complete); } progressBar.textContent = percent
Complete + "%
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("updat...
<form> - HTML: Hypertext Markup Language
Safari that controls how textual form elements should be automatically capitalized. autocapitalize attributes on a form elements override it on <form>. Possible values: none: No automatic capitalization. sentences (default): Capitalize the first letter of each sentence. words: Capitalize the first letter of each word. characters: Capitalize all characters -- that is, uppercase. ...
...pitalize attributes on a form elements override it on <form>. Possible values: none: No automatic capitalization. sentences (default): Capitalize the first letter of each sentence. words: Capitalize the first letter of each word. characters: Capitalize all characters -- that is, uppercase. auto
complete Indicates whether input elements can by default have their values automatically
completed by the browser. auto
complete attributes on form elements override it on <form>. Possible values: off: The browser may not automatically
complete entries. (Browsers tend to ignore this for suspected login forms; see The auto
complete attribute and login fields.) on: The browser may automatically
complete entries. name The name of the form. Deprecated as of HTML 4 (use id instead). It ...
...(i.e., the browsing context that is an ancestor of the current one and has no parent). If no parent, behaves the same as _self. This value can be overridden by a formtarget attribute on a <button>, <input type="submit">, or <input type="image"> element. ...
...n>, <input type="submit">, or <input type="image"> element. Examples HTML <!-- Form which will send a GET request to the current URL --> <form> <label>Name: <input name="submitted-name" auto
complete="name"> </label> <button>Save</button> </form> <!-- Form which will send a POST request to the current URL --> <form method="post"> <label>Name: <input name="submitted-name" auto
complete="name"> </label> <button>Save</button> </form> <!-- Form with fieldset, legend, and label --> <form method="post"> <fieldset> <legend>Title</legend> <label><input type="radio" name="radio"> Select me</label> </fieldset> </form> Specifications Specification Status Comment HTML Living StandardThe definition of '<form>' in that specification. Livin...
<input type="search"> - HTML: Hypertext Markup Language
agent. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Value A DOMString representing the value contained in the search field. Events change and input Supported Common Attributes auto
complete, list, maxlength, minlength, pattern, placeholder, required, size. IDL attributes value Methods select(), setRangeText(), setSelectionRange(). Value The value attribute contains a DOMString representing the value contained in the search field. You can retrieve this using the HTMLInputElement.value property in JavaScript. searchTerms = mySearch.value; If no valid...
...put (see Validation for more details), the value can be any text string or an empty string (""). ...
...ype, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored
completely. Tip: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section Specifying a pattern for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information i...
... and text types The main basic differences come in the way browsers handle them. The first thing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired. The following screenshot comes from Chrome: In addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as auto
complete options when subsequent searches are performed in search inputs on that domain. This helps users who tend to do searches on the same or similar search queries over time. This screenshot is from Firefox: At this point, let's look at some useful techniques you can apply to your search forms. Setting placeholders You can provide a useful placeholder inside your search input that could give a hint...
<input type="tel"> - HTML: Hypertext Markup Language
r entering phone numbers. Using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient. Note: Browsers that don't support type 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 auto
complete, 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 ...
...e contains a DOMString that either represents a telephone number or is an empty string (""). ...
...ype, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored
completely. Tip: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See Pattern validation below for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expect...
...put id="telNo" name="telNo" type="tel" value="333-4444-4444"> Offering suggested values Taking it a step farther, you can provide a list of default phone number values from which the user can select. To do this, use the list attribute. This doesn't limit the user to those options, but does allow them to select commonly-used telephone numbers more quickly. This also offers hints to auto
complete. The list attribute specifies the ID of a <datalist> element, which in turn contains one <option> element per suggested value; each option's value is the corresponding suggested value for the telephone number entry box. <label for="telNo">Phone number: </label> <input id="telNo" name="telNo" type="tel" list="defaultTels"> <datalist id="defaultTels"> <option value="111-1111-1111"> <option va...
<input type="time"> - HTML: Hypertext Markup Language
rol's value. 12-hour 24-hour Edge The Edge time control is somewhat more elaborate, opening up an hour and minute picker with sliding 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 auto
complete, 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">Ch...
...ry 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). ...
...lways about the same number of characters long. You'll have to resort to CSS for sizing needs. Using the step attribute You can use the step attribute to vary the amount of time jumped whenever the time is incremented or decremented (for example, so the time moves by 10 minutes at a time when clicking the little arrow widgets). This property has some strange effects across browsers, so is not
completely reliable. It takes an integer value that equates to the number of seconds you want to increment by; the default value is 60 seconds, or one minute. If you specify a value of less than 60 seconds (1 minute), the time input will show a seconds input area alongside the hours and minutes: <form> <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" nam...
...Try playing with the example now: Here's a screenshot for those of you who aren't using a browser that supports time inputs: Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that ...
<input type="url"> - HTML: Hypertext Markup Language
nd :invalid CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid URL or not. On browsers that don't support inputs of type url, a url input falls back to being a standard text input. Value A DOMString representing a URL, or empty Events change and input Supported Common Attributes auto
complete, list, maxlength, minlength, pattern, placeholder, readonly, required and size IDL attributes list, value, selectionEnd, selectionDirection Methods select(), setRangeText() and setSelectionRange(). Value The <input> element's value attribute contains a DOMString which is automatically validated as conforming to URL syntax. More specifically, there are two possible ...
...tofurl. See Validation for details on how URLs are validated to ensure that they're formatted properly. ...
...ype, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored
completely. Tip: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section Pattern validation for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is ...
...ue attribute: <input id="myURL" name="myURL" type="url" value="http://www.example.com"> Offering suggested values Taking it a step farther, you can provide a list of default options from which the user can select by specifying the list attribute. This doesn't limit the user to those options, but does allow them to select commonly-used URLs more quickly. This also offers hints to auto
complete. The list attribute specifies the ID of a <datalist>, which in turn contains one <option> element per suggested value; each option's value is the corresponding suggested value for the URL entry box. <input id="myURL" name="myURL" type="url" list="defaultURLs"> <datalist id="defaultURLs"> <option value="https://developer.mozilla.org/"> <option value="http://www.google.com/"> <option...
HTML documentation index - HTML: Hypertext Markup Language
content can be dropped on an element, using the HTML Drag and Drop API. It can have the following values: 17 hidden Global attributes, HTML, Reference The hidden global attribute is a Boolean attribute indicating that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been
completed. 18 id Global attributes, HTML, Reference, Web, id The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). 19 inputmode Attribute, Editing, Forms, Global attributes, HTML, Input, Reference, Text, Web, conte...
...operties impacting the width, CSS takes precedence. 50 HTML attribute: step Attribute, Attributes, constrain validation, step Valid for the numeric input types, including the date, month, week, time, datetime-local, number and range types, the step attribute is a number that specifies the granularity that the value must adhere to or the keyword any. ...
...tep Valid for the numeric input types, including the date, month, week, time, datetime-local, number and range types, the step attribute is a number that specifies the granularity that the value must adhere to or the keyword any. 51 The HTML auto
complete attribute Addresses, Attribute, Email addresses, Forms, HTML, Input, Phone Numbers, Reference, Select, Text, Usernames, auto
complete, form, passwords, textarea auto
complete lets web developers specify what if any permission the user agent has to provide automated assistance in filling out form field values, as well as guidance to the browser as to the type of information expected in the field. 52 disabled Attribute, Attributes, Constraint validation, Forms, required The Boolean disabled attribute, wh...
...pt code and the File API. 127 <input type="hidden"> Element, Forms, HTML, HTML forms, Input, Input Types, Reference, hidden <input> elements of type hidden let web developers include data that cannot be seen or modified by users when a form is submitted. For example, the ID of the content that is currently being ordered or edited, or a unique security token. Hidden inputs are
completely invisible in the rendered page, and there is no way to make it visible in the page's content. 128 <input type="image"> Element, Form Image, Form Image Button, Forms, HTML, HTML Image Button, HTML forms, Image Button, Input, Input Type, Number, Reference <input> elements of type image are used to create graphical submit buttons, i.e. submit buttons that take the form of an i...
Control flow and error handling - JavaScript
tements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements. The JavaScript reference contains exhaustive details about the statements in this chapter. The semicolon (;) character is used to separate statements in JavaScript code. Any JavaScript expression is also a statement. See Expressions and operators for
complete information about expressions. Block statement The most basic statement is a block statement, which is used to group statements. The block is delimited by a pair of curly brackets: { statement_1; statement_2; ? statement_n; } Example Block statements are commonly used with control flow statements (if, for, while). while (x < 10) { x++; } Here, { x++; } is the block statement. ...
...ere, { x++; } is the block statement. Important: JavaScript before ECMAScript2015 (6th edition) does not have block scope! In older JavaScript, variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not define a scope. "Standalone" blocks in JavaScript can produce
completely different results from what they would produce in C or Java. For example: var x = 1; { var x = 2; } console.log(x); // outputs 2 This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. (In C or Java, the equivalent code would have outputted 1.) Since ECMAScript2015, the let and const variable declarations are block-scoped. ...
...ource } If the finally block returns a value, this value becomes the return value of the entire try...catch...finally production, regardless of any return statements in the try and catch blocks: function f() { try { console.log(0); throw 'bogus'; } catch(e) { console.log(1); return true; // this return statement is suspended // until finally block has
completed console.log(2); // not reachable } finally { console.log(3); return false; // overwrites the previous "return" console.log(4); // not reachable } // "return false" is executed now console.log(5); // not reachable } console.log(f()); // 0, 1, 3, false Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch ...
... // while f() executes, the `finally` block returns false, // which overwrites the `throw` inside the above `catch` console.log('caught outer "bogus"'); } // OUTPUT // caught inner "bogus" // false Nesting try...ca...
JavaScript
ered trademarks of Oracle in the U.S. and other countries. However, the two programming languages have a very different syntax, semantic, and use. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Tutorials Learn how to program in JavaScript with guides and tutorials. ...
... a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Tutorials Learn how to program in JavaScript with guides and tutorials. For
complete beginners Head over to our Learning Area JavaScript topic if you want to learn JavaScript but have no previous experience of JavaScript or programming. The
complete modules available there are as follows: JavaScript first steps Answers some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", along with discussing key JavaScript features such as variables, strings, numbers, and arrays. JavaScript building blocks Continues our coverage of JavaScript's key fundamental features, turning our attention to co...
...alizing it. It is a restricted variant of ECMAScript 5, for faster performance and easier debugging. JavaScript typed arrays JavaScript typed arrays provide a mechanism for accessing raw binary data. Memory Management Memory life cycle and garbage collection in JavaScript. Concurrency model and Event Loop JavaScript has a concurrency model based on an "event loop". Reference Browse the
complete JavaScript reference documentation. Standard objects Get to know standard built-in objects Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String, Map, Set, WeakMap, WeakSet, and others. Expressions and operators Learn more about the behavior of JavaScript's operators instanceof, typeof, new, this, the operator precedence, and more. Statements and declarations L...
... Developer Tools Web Console, JavaScript Profiler, Debugger, and more. JavaScript Shells A JavaScript shell allows you to quickly test snippets of JavaScript code. Learn JavaScript An excellent resource for aspiring web developers -- Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the
complete course is available for a small one-time payment. TogetherJS Collaboration made easy. By adding TogetherJS to your site, your users can help each other out on a website in real-time! Stack Overflow Stack Overflow questions tagged with "JavaScript". JavaScript versions and release notes Browse JavaScript's feature history and implementation status. JSFiddle Edit JavaScript, CSS, HTML and g...
Content Scripts - Archive of obsolete content
le the add-on's main code to load content scripts into web pages content scripts can be loaded in as strings, but are more often stored as separate files under the add-on's "data" directory. jpm doesn't make a "data" directory by default, so you must add it and put your content scripts in there. a message-passing API allows the main code and content scripts to communicate with each other This
complete add-on illustrates all of these principles. Its "main.js" attaches a content script to the current tab using the tabs module. In this case the content script is passed in as a string. The content script simply replaces the content of the page: // main.js var tabs = require("sdk/tabs"); var contentScriptString = 'document.body.innerHTML = "<h1>this page has been eaten</h1>";' tabs.activeTab.atta...
...ar, frame - are specified using HTML, and use separate scripts to interact with this content. In many ways these are like content scripts, but they're not the focus of this article. To learn about how to interact with the content for a given user interface module, please see the module-specific documentation: panel, sidebar, frame. Almost all the examples presented in this guide are available as
complete, but minimal, add-ons in the addon-sdk-content-scripts repository on GitHub. Loading content scripts You can load a single script by assigning a string to either the contentScript or the contentScriptFile option. The contentScript option treats the string itself as a script: // main.js var pageMod = require("sdk/page-mod"); var contentScriptValue = 'document.body.innerHTML = ' + ...
...ntent script In the content script the port object is available as a property of the global self object. So to emit a message from a content script: self.port.emit("myContentScriptMessage", myContentScriptMessagePayload); To receive a message from the add-on code: self.port.on("myAddonMessage", function(myAddonMessagePayload) { // Handle the message }); 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. Accessing port in the add-on script In the add-on code, the channel of communication between the add-on and a particular content script context is encapsulated by the worker object. So the port object for communicating with a content script is a property of the corresponding worker object. H...
dev/panel - Archive of obsolete content
onReady Function An event handler that will be called when the document in the panel becomes interactive. It's equivalent to document.readyState === "interactive". At this point you can send the panel document messages. Optional onLoad Function An event handler that will be called after the document in the panel is fully loaded. ...
...at will be called after the document in the panel is fully loaded. It's equivalent to document.readyState === "
complete". Optional Once you've defined the panel's constructor you have to export it so it can be called by the framework. Creating a Tool Next, you need to create a new Tool using the dev/toolbox module, initializing it with the newly defined constructor. ...
...t forget to call start() on the port before passing it over to the panel document. Volcan.js: a JavaScript API for the debugging protocol Communicating with the debugger server by exchanging JSON messages can be cumbersome. So we've also provided a library called volcan.js which gives you a JavaScript API to the remote debugging protocol. Note that at the moment volcan.js does not support the
complete remote debugging protocol. We're still working on documenting exactly which messages are supported by volcan.js. To use volcan.js, you can just include it from your panel's HTML like this: <html> <head> <meta charset="utf-8"> <link href="./my-panel.css"rel="stylesheet"></link> <script src="resource://sdk/dev/volcan.js"></script> </head> <body> <div id = "content"></div>...
Chrome Authority - Archive of obsolete content
t 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. Likewise, it will prevent modules from getting chrome authority unless the manifest indicates that they have asked for it. This will ensure that reviewers see the same authority restrictions that are enforced upon the running code, increasing the effectiveness of the time spent reviewin...
...prevent modules from require()ing modules that are not listed in the manifest. Likewise, it will prevent modules from getting chrome authority unless the manifest indicates that they have asked for it. This will ensure that reviewers see the same authority restrictions that are enforced upon the running code, increasing the effectiveness of the time spent reviewing the add-on. ...
...(until this work is
complete, modules may be able to sneak around these restrictions). The manifest is built with a simple regexp-based scanner, not a full Javascript parser. Developers should stick to simple require statements, with a single static string, one per line of code. If the scanner fails to see a require entry, the manifest will not include that entry, and (once the implementation is
complete) the runtime code will get an exception. For example, none of the following code will be matched by the manifest scanner, leading to exceptions at runtime, when the require() call is prohibited from importing the named modules: // all of these will fail! var xhr = require("x"+"hr"); var modname = "xpcom"; var xpcom = require(modname); var one = require("one"); var two = require("two"); The in...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
<< PreviousNext >> FIXME: We should include a link to the MDC list of snippets FIXME: We need to add a part about 'why and how to create your own component' C++/JS This document was authored by Hiroshi Shimoda of Clear Code Inc. and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Mr. Shimoda is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008). This chapter explains how to use XPCOM to implement advanced processes using only JavaScript. Introduction JavaScript lacks functions for opening files and character-code conversion, among other things. A different mechanism is needed to perform these functions. ...
...utStream); binaryStream.setInputStream(fileStream); var array = binaryStream.readByteArray(fileStream.available()); binaryStream.close(); fileStream.close(); alert(array.map( function(aItem) {return aItem.toString(16); } ).join(' ').toUpperCase( )); When we initialized nsIFileInputStream, we set the second and third parameters to initialize it in read-only mode. ...
... is
complete, you should close all streams. Outputting binary files Listing 14 shows the opposite operation, taking a string of bytes and outputting them as a binary file. Here, we're outputting a text file consisting of the ASCII characters "XUL." When we initialized nsIFileInputStream, we set the second and third parameters to initialize it in write-only mode. Here again, once the process is
complete, you should close all streams. Listing 14: Writing a binary file var array = [88, 85, 76]; file.initWithPath('C:\\temp\\temp.txt'); if (file.exists()) file.remove(true); file.create(file.NORMAL_FILE_TYPE, 0666); var fileStream = Components.classes['@mozilla.org/network/file-output-stream;1'] .createInstance(Components.interfaces.nsIFileOutputStream); fileStream.init(file, 2, ...
Getting Started with Firefox Extensions - Archive of obsolete content
They allow the application to be customized to fit the personal needs of each user if they need additional features, while keeping the applications small to download. Taken from the Extensions page. As described in the quoted text, an extension is a small application that adds something new to one or more Mozilla applications. ...
...torial is about extension development, but themes and language packs are developed in a very similar way. Plugins are entirely different, and they will not be covered here. You can read more about plugins and their development in the Plugins page. Firefox provides a very rich and flexible architecture that allows extension developers to add advanced features, customize the user's experience, and
completely replace and remove parts of the browser. The Mozilla Add-ons repository (AMO) holds an extensive number of extensions with a wide variety of functions: content filtering (AdBlock Plus, NoScript), web application interaction (Delicious Bookmarks, eBay Companion) and web development (DOM Inspector, Firebug). These are very advanced and complex extensions, and you'll learn most of what it takes to...
... xpinstall.signatures.required preference in about:config. Install Hello World Click the above link and then click "allow" in the pop-up bubble. You should see another pop-up telling you that you are installing an unverified add-on. Click "install". After the extension is installed, you'll be asked to restart Firefox. Installing, uninstalling, enabling and disabling add-ons require a restart to
complete, with the exception of NPAPI plugins, Add-ons SDK extensions and bootstrapped extensions. This is an important point to keep in mind if you're building an extension that manipulates other extensions or themes. After installing, look at the main Firefox window and see if you notice anything different. Did you see it? There's a new menu on the main menu, labeled "Hello World!". If you open the...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
ly lives, especially in the realms of business, culture, and politics. Why not attempt to use technology standards for the Web to live out that story? The visual design of Wired News and the Vignette templates were all sorely stale, and we had no significant effort invested into either for more than two years. I think that fact played a critical role in our team's willingness to try out something
completely new. Our engineering team actually needed the least convincing to convert over to a standards-based design, because they could also immediately envision the benefits to their workload and maintenance of the site. How is the site styled now that you've ripped out all the HTML-based presentation? Technically, there are 13 total stylesheets used at any one time. The breakdown: 1 master screen...
...ethods that worked for the Wired News design. By eliminating tables that were strictly used for layout, we significantly cut back on the amount of markup and useless tags in our html, and gained a structure that is much easier to maintain. Now that the content is not locked into a specific table structure, we have much more flexibility in how we present that content. A few changes to the CSS can
completely alter the presentation of thousands of pages. As a very welcome side benefit, we also believe the accessibility of Wired News will dramatically improve without the clutter of nested layout tables. Are you setting up your columns with floats or positioning? In trying to eliminate that last table I was using to set the column structure of our pages, I took a close look at both floated divs and ...
...y that surprises our developers in how easy it is to make a change. Wired News is also dramatically more accessible, without much concentrated effort at making it so. Sure, we now pay more attention to our image alt attributes, and try to use heading tags appropriately. But a huge decrease in the amount [sic] of presentation markup tags also plays a big role too. Since all of our content is also
completely accessible sans style sheets, I think we get the best of both worlds: a well-designed, highly stylized, true-to-our-brand website which adapts in different browsing environments. What would you say to a site developer considering a similar conversion to standards-based layout, either with simple tables or no tables at all? I think the conversion is a matter of taking into account several cons...
Creating an Installer - Archive of obsolete content
presented in a list. The user may choose to continue or cancel. If the user chooses to continue, the installer XPI file is downloaded. A progress bar is displayed to the user during this process. The file install.js is extracted from the install archive and executed. This script will call install functions which will indicate which files from the archive should be installed. Once the script is
complete, the new package has been installed. If multiple packages are being installed, their scripts will run in sequence. Install Triggers As indicated above, the install 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 cont...
...t 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(). This function takes two arguments, the first is a list of packages to install, and the second is a callback function which will be called when the installation is
complete. Here is an example: function doneFn ( name , result ){ alert("The package " + name + " was installed with a result of " + result); } var xpi = new Object(); xpi["Calendar"] = "calendar.xpi"; InstallTrigger.install(xpi,doneFn); First, we define a callback function doneFn() which will be called when the install is
complete. You can name the function whatever you like of course. This function...
...If the result is non-zero, an error occured and the value is an error code. The function doneFn() here just displays an alert box to the user. Next, we create an array xpi which will hold the name (Calendar) and URL (calendar.xpi) of the installer. ...
Progress Meters - Archive of obsolete content
You typically see it when downloading files or when performing a lengthy operation. XUL has a progressmeter element which can be used to create these. There are two types of progress meters: determinate and indeterminate. Determinate progress meters are used when you know the length of time that an operation will take. The progress meter will fill up and, once full, the operation should be finished. ...
... Indeterminate progress meter: The progress meter has the following syntax: <html:progress id="identifier" mode="determined" value="50" max="100"/> The attributes are as follows: id The unique identifer of the progress meter mode The type of the progress meter. If this is set to determined, the progress meter is a determinate progress meter where it fills up as the task
completes. If this is set to undetermined, the progress meter is indeterminate where you do not know the length of time. The value determined is the default if you do not specify this attribute. value The current value of the progress meter. You should only use this for a progress meter that is determinate. The value should be set to an integer percentage from 0 to 100. The value would be changed by a s...
...to undetermined, the progress meter is indeterminate where you do not know the length of time. The value determined is the default if you do not specify this attribute. value The current value of the progress meter. You should only use this for a progress meter that is determinate. The value should be set to an integer percentage from 0 to 100. The value would be changed by a script as the task
completes. max The maximum value of the progress meter. Should be used only with determinate. The find files example Let's add a progress meter to our find file dialog. We would normally put an indeterminate progress meter as we don't know how many files we'll be searching or how long the search will take. However, we'll add a normal one for now as an animating one can be distracting during developm...
Skinning XUL Files by Hand - Archive of obsolete content
What Is a Skin? The skin of a XUL file is its look or overall style. In XUL, skins are created with Cascading Style Sheets and images. To skin a XUL file means to change the overall look of that file by changing its style information. In the very near future, it will be possible to skin XUL files dynamically and
completely -- by pressing a button, selecting a skin from a menu, or by accepting a skin from over the web. When this day comes, skins defined in a global skin file will be applied to a whole application -- like the Mozilla browser -- so that all the various windows and parts will look consistent. In the meantime, however, skinning a file requires some manual interaction. This article can help you get started understanding skins and creating skins for XUL. It presumes you have at least b...
... Unlike a XUL file, a CSS file does not need any particular structure or preamble information at the top. CSS can define styles for elements in a hierarchy, but it is not itself hierarchical, as you saw in the global skin. Instead, a CSS file is usually simply a list of style definitions that are applied to their respective elements and classes by the rendering engine. Here is a very short (but
complete!) cascading stylesheet that might be referenced and used by a XUL file: toolbar.nav-bar { background-image: url("chrome://navigator/skin/navbar-bg.gif"); padding: 0px; padding-bottom: 2px; } box#navbar { background-color: lightblue; } A:link { color: #FA8072; } This stylesheet exhibits three of the different types of style definitions described above. Each type uses a different gro...
...e technologies are. The combination of XUL and CSS provides so much flexibility that it can seem daunting. The purpose of this split between XUL and its skins -- and between the global skin and whatever custom styles you might create -- is to enable the dynamic skinning of applications such as the Mozilla browser. What you have done manually in this article will be done dynamically and much more
completely by a mechanism called thechrome registry. this needs rewording: , which, like the Windows registry, is a database in which information about a user's software and environment can be recorded and accessed as necessary. Software components and users will be able to update the chrome registry and change the global skin. And with the advent of new CSS2 conventions like positioning, the changes you ...
XUL accessibility guidelines - Archive of obsolete content
eckbox or a radio button). However, in all other cases using <label control="[id]"> is enough. Testing assistive information Testing with a screen reader is in many ways the best test, because both the keyboard navigation and underlying semantics/structure of the UI can be tested at the same time. It is an excellent indicator regarding the accessibility of a user interface, but is by no means a
complete test. Ultimately, for applications that must be
completely accessible, it is best to have the application tested by a variety of end users with different software and assistive technology configurations. If you don't have access to screen reader software (and don't know anyone who does), your best option is to throughly check the source code to make sure that all of the above guidelines have bee...
...ack, and allow users to correct errors. Some users with disabilities have difficulties with quick responses. Allow users adequate time to perform tasks. Instruction Provide users with help documentation. Even simple applications should include a help document or manual for user reference. Describe keyboard shortcuts and any other accessibility considerations. Users should be able to reference a
complete description of all major functionality of an application. Also provide details on how to use long or complex help documentation. Alerts Provide accessible alerts for presenting important information to the user. Use scripting or the notificationbox element to flag alerts. Avoid using audio or visual alerts alone to signal urgent events. Users who have audio turned down or off and users who are...
... background color do not provide sufficient contrast. Flex Visual elements and containers resize gracefully. Visual elements and containers do not resize gracefully. Human computer interaction Checkpoint Pass Fail Instruction Help documentation is provided including a description of keyboard shortcuts. Help documentation is not provided or is in
complete. Alerts Alerts are displayed using the alert scripting function or the notificationbox element. Alerts are conveyed visually or audibly, or use a method other than the alert scripting function or the notificationbox element. Interactive elements Interactive elements are sufficiently large and visible. Interactive elements are too small or not sufficiently contrasted ...
NPP_NewStream - Archive of obsolete content
private data associated with the stream in stream->pdata. The MIME type of the stream is provided by the type parameter. The data in the stream can be the file specified in the SRC attribute of the EMBED tag, for an embedded instance, or the file itself, for a full-page instance. A plug-in can also request a stream with the function NPN_GetURL. The browser calls NPP_DestroyStream when the stream
completes (either successfully or abnormally). The plug-in can terminate the stream itself by calling NPN_DestroyStream. The parameter stype defines the mode of the stream. Values: NP_NORMAL (Default): Delivers stream data to the instance in a series of calls to NPP_WriteReady and NPP_Write. The plug-in can process the data progressively as it arrives from the network or file system. NP_ASFILEONLY: T...
...self by calling NPN_DestroyStream. The parameter stype defines the mode of the stream. Values: NP_NORMAL (Default): Delivers stream data to the instance in a series of calls to NPP_WriteReady and NPP_Write. The plug-in can process the data progressively as it arrives from the network or file system. NP_ASFILEONLY: The browser saves stream data to a file in the local cache. When the stream is
complete, the browser calls NPP_StreamAsFile to deliver the path of the file to the plug-in. If the stream comes from a local file, the NPP_Write and NPP_WriteReady functions are not called. NPP_StreamAsFile is simply called immediately. This mode allows the plug-in full random access to the data using platform-specific file operations. NP_ASFILE: File download. Differs from NP_ASFILEONLY in that data is...
... functions are not called. NPP_StreamAsFile is simply called immediately. This mode allows the plug-in full random access to the data using platform-specific file operations. NP_ASFILE: File download. Differs from NP_ASFILEONLY in that data is delivered to the plug-in, through a series of calls to NPP_WriteReady and NPP_Write, as it is saved to the file (as in mode NP_NORMAL). When the stream is
complete, the browser calls NPP_StreamAsFile to deliver the path of the file to the plug-in. If the data in the stream comes from a file that is already local, the data is read, sent to the plug-in through NPP_Write, and written to a file in the local cache. NOTE: Most plug-ins that need the stream saved to a file should use the more efficient mode NP_ASFILEONLY (above); this mode is preserved for comp...
NPP_URLNotify - Archive of obsolete content
on 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 with network, disk I/O, lack of memory, or other p...
...e 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. ...
...revious 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 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_P...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
ug.msTraceAsyncCallbackStarting function associates the callback stack with a previously specified asynchronous operation. Syntax Debug.msTraceAsyncCallbackStarting(asyncOperationId) Parameters asyncOperationId The ID associated with the asynchronous operation. Remarks Call this function in the callback function for the asynchronous operation after the call to Debug.msTraceAsyncOperation
Completed. 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(...
...onId 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. ...
...e app. function asyncWrapperFunction() { var opID = Debug.msTraceAsyncOperationStarting('async trace'); doSomethingAsync().then(function (result) { Debug.msTraceAsyncOperation
Completed(opID, Debug.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperation
Completed(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallback
Completed(); } 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...
LiveConnect Overview - Archive of obsolete content
JavaObject A wrapped Java object, accessed from within JavaScript code. JavaPackage A JavaScript reference to a Java package. Note: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See Data Type Conversion for
complete information. In some ways, the existence of the LiveConnect objects is transparent, because you interact with Java in a fairly intuitive way. For example, you can create a Java String object and assign it to the JavaScript variable myString by using the new operator with the Java constructor, as follows: var myString = new java.lang.String("Hello world"); In the previous example, the variable my...
...with a value similar to the following: C:\Program Files\Java\jre1.4.1\lib\plugin.jar See the Sun JDK documentation for more information about CLASSPATH. Note: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See Data Type Conversions for
complete information. Using the LiveConnect Classes All JavaScript objects appear within Java code as instances of netscape.javascript.JSObject. When you call a method in your Java code, you can pass it a JavaScript object as one of its argument. To do so, you must define the corresponding formal parameter of the method to be of type JSObject. Also, any time you use JavaScript objects in your Java code, y...
...eIt(); } else { throw e; } } } If theCondition is false, the function throws an exception. The exception is caught in the JavaScript code, and if canHandle is true, JavaScript handles it. If canHandle is false, the exception is rethrown, the Java handler catches it, and the doit method returns a Java string: JavaScript error occurred See Exception Handling Statements for
complete information about JavaScript exceptions. Backward Compatibility In JavaScript 1.3 and earlier versions, the JSException class 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. Use a try...catch statement such as the following to handle LiveConnect exceptions...
Archive of obsolete content
feature or API, and how it worked. There are many reasons older documentation can be useful. So, we've established this area into which we can archive older documentation. Material in this Archived content zone should not be used for building new Web sites or apps for modern browsers. It's here for historical reference only. See the
complete index of archived content Note to writers: We need to try to keep the subpages here organized instead of all dumped into one large folder. Try to create subtrees for categories of material. Also, only move pages here that are extremely obsolete. If anyone might realistically need the information in a living product, it may not be appropriate to move it ...
...y in class and id Names Creating a dynamic status bar extension Concepts covered in the previous sample won't be reiterated here; instead, refer to the downloadable sample code or to the previous sample for further details. Creating a status bar extension Many of the concepts introduced here apply to any XUL-based application; however, to keep from getting
completely overwhelmed, we're going to focus specifically on Firefox. CSS3 CSS3 is the latest evolution of the Cascading Style Sheets language and aims at extending CSS2.1. It brings a lot of long-awaited novelties, like rounded corners, shadows, gradients, transitions or animations, as well as new layouts like multi-columns, flexible box or grid layouts. ...
...rmer Mozilla-Based Applications The following is a list of all known applications that at one point used Mozilla technologies or that are no longer being actively maintained. List of Mozilla-Based Applications The following is a list of all known active applications that are built using Mozilla technologies. This list is likely to be in
complete since we think there are many dark matter projects that we don't know about. If you have information about a new project or extra information about an existing project, please feel free to update this page. Localizing an extension This article expands upon the previous samples on extension writing by adding localization support to our stock watcher exte...
HTML: A good basis for accessibility - Learn web development
We've already talked about the importance of proper semantics, and why we should use the right HTML element for the job. This cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly. Out there on the web, the truth is that people do some very strange things with HTML markup. Some abuses of HTML are due to legacy practices that have not been
completely forgotten, and some are just plain ignorance. Whatever the case, you should replace such bad code. Sometimes you are not in the position to get rid of lousy markup -- your pages might be generated by some kind of server-side framework over which you don't have full control, or you might have third party content on your page (such as ad banners) over which you have no control. The goal isn't "...
... are heading up rows, columns, etc. This can only be done visually for the above table (see bad-table.html and try the example out yourself). Now have a look at our punk bands table example -- you can see a few accessibility aids at work here: Table headers are defined using <th> elements -- you can also specify if they are headers for rows or columns using the scope attribute. This gives you
complete groups of data that can be consumed by screen readers as single units. The <caption> element and <table> summary attribute both do similar jobs -- they act as alt text for a table, giving a screen reader user a useful quick summary of the table's contents. The <caption> element is generally preferred as it makes it's content accessible to sighted users too, who might also find it useful. You don...
...ng an extended description of the image, for example: <img src="dinosaur.png" longdesc="dino-info.html"> This sounds like a good idea, especially for infographics like big charts with lots of information on them that could perhaps be represented as an accessible data table instead (see Accessible data tables). However, longdesc is not supported consistently by screen readers, and the content is
completely inaccessible to non-screen reader users. It is arguably much better to include the long description on the same page as the image, or link to it with a regular link. HTML5 includes two new elements -- <figure> and <figcaption> -- which are supposed to associate a figure of some kind (it could be anything, not necessarily an image) with a figure caption: <figure> <img src="dinosaur.png" alt=...
HTML: A good basis for accessibility - Learn web development
We've already talked about the importance of proper semantics, and why we should use the right HTML element for the job. This cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly. Out there on the web, the truth is that people do some very strange things with HTML markup. Some abuses of HTML are due to legacy practices that have not been
completely forgotten, and some are just plain ignorance. Whatever the case, you should replace such bad code. Sometimes you are not in the position to get rid of lousy markup -- your pages might be generated by some kind of server-side framework over which you don't have full control, or you might have third party content on your page (such as ad banners) over which you have no control. The goal isn't "...
... are heading up rows, columns, etc. This can only be done visually for the above table (see bad-table.html and try the example out yourself). Now have a look at our punk bands table example -- you can see a few accessibility aids at work here: Table headers are defined using <th> elements -- you can also specify if they are headers for rows or columns using the scope attribute. This gives you
complete groups of data that can be consumed by screen readers as single units. The <caption> element and <table> summary attribute both do similar jobs -- they act as alt text for a table, giving a screen reader user a useful quick summary of the table's contents. The <caption> element is generally preferred as it makes it's content accessible to sighted users too, who might also find it useful. You don...
...ng an extended description of the image, for example: <img src="dinosaur.png" longdesc="dino-info.html"> This sounds like a good idea, especially for infographics like big charts with lots of information on them that could perhaps be represented as an accessible data table instead (see Accessible data tables). However, longdesc is not supported consistently by screen readers, and the content is
completely inaccessible to non-screen reader users. It is arguably much better to include the long description on the same page as the image, or link to it with a regular link. HTML5 includes two new elements -- <figure> and <figcaption> -- which are supposed to associate a figure of some kind (it could be anything, not necessarily an image) with a figure caption: <figure> <img src="dinosaur.png" alt=...
Introduction to CSS layout - Learn web development
ic positioning is the default that every element gets -- it just means "put the element into its normal position in the document layout flow -- nothing special to see here". Relative positioning allows you to modify an element's position on the page, moving it relative to its position in normal flow -- including making it overlap other elements on the page. Absolute positioning moves an element
completely out of the page's normal layout flow, like it is sitting on its own separate layer. From there, you can fix it in a position relative to the edges of the page's <html> element (or its nearest positioned ancestor element). This is useful for creating complex layout effects such as tabbed boxes where different content panels sit on top of one another and are shown and hidden as desired, or inform...
... Going back to our original non-positioned example, we could add the following CSS rule to implement absolute positioning: .positioned { position: absolute; top: 30px; left: 30px; } Here we give our middle paragraph a position value of absolute, and the same top and left properties as be...
...The other two paragraphs now sit together as if their positioned sibling doesn't exist. The top and left properties have a different effect on absolutely positioned elements than they do on relatively positioned elements. In this case the offsets have been calculated from the top and left of the page. It is possible to chan...
Client-side form validation - Learn web development
ll encounter on the web: Built-in form validation uses HTML5 form validation features, which we've discussed in many places throughout this module. This validation generally doesn't require much JavaScript. Built-in form validation has better performance than JavaScript, but it is not as customizable as JavaScript validation. JavaScript validation is coded using JavaScript. This validation is
completely customizable, but you need to create it all (or use a library). Using built-in form validation One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap: required: Specifies whether a form fiel...
...lowed by c. ab?c--Matches a, optionally followed by a single b, followed by c. ( ac or abc) ab*c--Matches a, optionally followed by any number of bs, followed by c. ( ac , abc, abbbbbc, and so on). a|b -- Matches one character that is a or b. abc|xyz -- Matches exactly abc or exactly xyz (but not abcxyz or a or y, and so on). There are many more possibilities that we don't cover here. For a
complete list and many examples, consult our Regular expressions documentation. Let's implement an example. Update your HTML to add a pattern attribute like this: <form> <label for="choose">Would you prefer a banana or a cherry?</label> <input id="choose" name="i_like" required pattern="[Bb]anana|[Cc]herry"> <button>Submit</button> </form> input:invalid { border: 2px dashed red; } input:vali...
... Note: You can find this example live on GitHub as full-example.html (see also the source code.) Validating forms using JavaScript You must use JavaScript if you want to take control over the look and feel of native error messages or to deal with legacy browsers that do not support HTML's buil...
How to build custom form controls - Learn web development
is very easy to overlook this behavior. This is especially true in a team environment when the people who design the control's behavior are different from the ones who implement it. Another fun example: what will happen if the user hits the up or down arrow keys while the control is in the open state? This one is a little bit trickier. If you consider that the active state and the open state are
completely different, the answer is again "nothing will happen" because we did not define any keyboard interactions for the opened state. On the other hand, if you consider that the active state and the open state overlap a bit, the value may change but the option will definitely not be highlighted accordingly, once again because we did not define any keyboard interactions over options when the control is...
...xpected behaviors and interactions are. At least select has been done before, so we know how it should behave! Designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard. For example, Apple introduced the scroll wheel with the iPod in 2001. They had the market share to successfully introduce a
completely new way of interacting with a device, something most device companies can't do. It is best not to invent new user interactions. For any interaction you do add, it is vital to spend time in the design stage; if you define a behavior poorly, or forget to define one, it will be very hard to redefine it once the users have gotten used to it. If you have doubts, ask for the opinions of others, and...
...n alternative approach: Using radio buttons In the above example, we reinvented a <select> element using non-semantic HTML, CSS, and JavaScript. This select was selecting one option from a limited number of options, which is the same functionality of a same-named group of radio buttons. We could therefore reinvent this using radio buttons instead; let's look at this option. We can start with a
completely semantic, accessible, unordered list of radio buttons with an associated <label>, labeling the entire group with a semantically appropriate <fieldset> and <legend> pair. <fieldset> <legend>Pick a fruit</legend> <ul class="styledSelect"> <li><input type="radio" name="fruit" value="Cherry" id="fruitCherry" checked><label for="fruitCherry">Cherry</label></li> <li><input type="r...
Other form controls - Learn web development
g different text directions if you want to find out more.) Play with the interactive example at the top of the resize reference page for a demonstration of how these work. Drop-down controls Drop-down controls are a simple way to let users select from many different options without taking up much space in the user interface. HTML has two forms of drop down content: the select box, and the auto
complete box. In both cases the interaction is the same -- once the control is activated, the browser displays a list of values the user can select between. Note: You can find examples of all the drop-down box types on GitHub at drop-down-content.html (see it live also). Select box A simple select box is created with a <select> element with one or more <option> elements as its children, each of which...
...o</option> </optgroup> </select> Note: In the case of multiple choice select boxes, you'll notice that the select box no longer displays the values as drop-down content -- instead, all values are displayed at once in a list, with the optional size attribute determining the height of the widget. Note: All browsers that support the <select> element also support the multiple attribute. Auto
complete box You can provide suggested, automatically-
completed values for form widgets using the <datalist> element with child <option> elements to specify the values to display. The <datalist> needs to be given an id. The data list is then bound to an <input> element (e.g. a text or email input type) using the list attribute, the value of which is the id of the data list to bind. Once a data list is...
...es for form widgets using the <datalist> element with child <option> elements to specify the values to display. The <datalist> needs to be given an id. The data list is then bound to an <input> element (e.g. a text or email input type) using the list attribute, the value of which is the id of the data list to bind. Once a data list is affiliated with a form widget, its options are used to auto-
complete text entered by the user; typically, this is presented to the user as a drop-down box listing possible matches for what they've typed into the input. Let's look at an example. <label for="myFruit">What's your favorite fruit?</label> <input type="text" name="myFruit" id="myFruit" list="mySuggestion"> <datalist id="mySuggestion"> <option>Apple</option> <option>Banana</option> <option>Blackb...
Making decisions in your code — conditionals - Learn web development
let shoppingDone = false; if (shoppingDone === true) { let childsAllowance = 10; } else { let childsAllowance = 5; } This code as shown always results in the shoppingDone variable returning false, meaning disappointment for our poor child. It'd be up to us to provide a mechanism for the parent to set the shoppingDone variable 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 exampl...
...textContent = 'It is ' + temperature + ' degrees outside -- nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.'; } else if (temperature >= 86) { para.textContent = 'It is ' + temperature + ' degrees outside -- REALLY HOT! If you want to go outside, make sure to put some sunscreen on.'; } } Even though the code all works together, each if...else statement works
completely independently of the other one. Logical operators: AND, OR and NOT If you want to test multiple conditions without writing nested if...else statements, logical operators can help you. When used in conditions, the first two do the following: && -- AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to true for the whole expression to r...
... separated by || (OR) operators. For example: if (x === 5 || 7 || 10 || 20) { // run my code } In this case the condition inside if(...) will always evaluate to true since 7 (or any other non-zero value) always evaluates to true. This condition is actually saying "if x equals 5, or 7 is true -- which it always is". This is logically not what we want! To make this work you've got to specify a
complete test either side of each OR operator: if (x === 5 || x === 7 || x === 10 ||x === 20) { // run my code } switch statements if...else statements do the job of enabling conditional code well, but they are not without their downsides. They are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex...
Drawing graphics - Learn web development
the circle would be drawn. Before calling fill(), we draw a line to the center of the circle. This means that we get the rather nice Pac-Man-style cutout rendered. If you removed this line (try it!) then re-ran the code, you'd get just an edge of the circle chopped off between the start and end point of the arc. This illustrates another important point of the canvas -- if you try to fill an in
complete path (i.e. one that is not closed), the browser fills in a straight line between the start and end point and then fills it in. That's it for now; your final example should look like this: Note: The finished code is available on GitHub as 3_canvas_paths.html. Note: To find out more about advanced path drawing features such as Bezier curves, check out our Drawing shapes with canvas tu...
... balls[i].draw(); balls[i].update(); balls[i].collisionDetect(); } requestAnimationFrame(loop); } loop(); We run the loop() function once at the bottom of the code to start the cycle, drawing the first animation frame; the loop() function then takes charge of calling requestAnimationFrame(loop) to run the next frame of the animation, again and again. Note that on each frame we are
completely clearing the canvas and redrawing everything. For every ball present we draw it, update its position, and check to see if it is colliding with any other balls. Once you've drawn a graphic to a canvas, there's no way to manipulate that graphic individually like you can with DOM elements. You can't move each ball around on the canvas, because once it's drawn, it's part of the canvas, and is not a...
..., with the exception of Internet Explorer versions less than 10; also Safari doesn't yet support color. If your browser doesn't support these inputs, they will fall back to simple text fields and you'll just have to enter valid color/number values yourself. WebGL It's now time to leave 2D behind, and take a quick look at 3D canvas. 3D canvas content is specified using the WebGL API, which is a
completely separate API from the 2D canvas API, even though they both render onto <canvas> elements. WebGL is based on OpenGL (Open Graphics Library), and allows you to communicate directly with the computer's GPU. As such, writing raw WebGL is closer to low level languages such as C++ than regular JavaScript; it is quite complex but incredibly powerful. Using a library Because of its complexity, most ...
Aprender y obtener ayuda - Learn web development
ollowing have different scopes, but are all realistic and achievable: I want to become a professional web developer in two years' time. I want to learn enough to build a website for my local amateur tennis club. I want to learn HTML and CSS so I can expand my job role to take over updating the content on our company website. The following are not quite as reasonable: I want to go from a
complete beginner to becoming a senior web developer in three months. I want to start my own company and build a social network that will out-perform Facebook, in two years. What do you need to get there? Once you've worked out your goal, it is a good idea to research what you'll need to achieve the goal. For example: Materials I need: A computer Internet access Pens and paper Knowledge I need...
..., but it is easy to forget when you get really into coding. Factor these essential ingredients into your schedule, and make sure you are not doing your learning time instead of these things. Give yourself rewards. It's true that all work and no play makes Jack a dull boy. You should try to schedule fun things to do after each learning session, which you'll only have when the learning is over and
complete. If you are really into gaming, for example, there is something quite motivating about saying "no gaming tonight unless I get through my 5 hours of learning". Now all you need is willpower. Good luck! Co-learning and demoing. This won't be an option for everyone, but if at all possible try to learn alongside others. Again, this is easier if you are doing a college course on web development, but ...
...ed from a list of links, something like: <ul> <li>First menu item</li> <li>Second menu item</li> <li>Third menu item</li> <li>etc.</li> </ul> To make all the items sit horizontally on a line, the easiest modern way is to use flexbox: ul { display: flex; } To remove unneeded spacing and bullet points, we can do this: ul { list-style-type: none; padding: 0; } etc. If you are a
complete beginner to web development, you'll have to do some study and web searches and lookup solutions to such problems. If you are a professional web developer you'll probably remember the last time you solved a similar problem, and only have to look up a few bits of the syntax that you forgot since then. When you find solutions to such problems, it is worth writing down notes on what you did, and kee...
Website security - Learn web development
t that is passed to an underlying SQL statement can change the meaning of the statement. For example, the following code is intended to list all users with a particular name (userName) that has been supplied from an HTML form: statement = "SELECT * FROM users WHERE name = '" + userName + "';" If the user specifies a real name, the statement will work as intended. However, a malicious user could
completely change the behavior of this SQL statement to the new statement in the following example, by simply specifying the text in bold for the userName. SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't'; The modified statement creates a valid SQL statement that deletes the users table and selects all data from the userinfo table (which reveals the informat...
...g example, by simply specifying the text in bold for the userName. SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't'; The modified statement creates a valid SQL statement that deletes the users table and selects all data from the userinfo table (which reveals the information of every user). This works because the first part of the injected text (a';)
completes the original statement. To avoid this sort of attack, you must ensure that any user data that is passed to an SQL query cannot change the nature of the query. One way to do this is to escape all the characters in the user input that have a special meaning in SQL. Note: The SQL statement treats the ' character as the beginning and end of a string literal. By putting a backslash in front of thi...
...icious user hijacks clicks meant for a visible top-level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials into an invisible <iframe> controlled by the attacker. Clickjacking could also be used to get the user to click a button on a visible site, but in doing so actually unwittingly click a
completely different button. As a defense, your site can prevent itself from being embedded in an iframe in another site by setting the appropriate HTTP headers. Denial of Service (DoS). DoS is usually achieved by flooding a target site with fake requests so that access to a site is disrupted for legitimate users. The requests may simply be numerous, or they may individually consume large amounts of reso...
Ember interactivity: Events, classes and state - Learn web development
t.js This creates a todo-data.js file inside the todomvc/app/services directory to contain our service, which initially contains an import statement and an empty class: import Service from '@ember/service'; export default class TodoDataService extends Service { } First of all, we want to define what a todo is. We know that we want to track both the text of a todo, and whether or not it is is
completed. Add the following import statement below the existing one: import { tracked } from '@glimmer/tracking'; Now add the following class below the previous line you added: class Todo { @tracked text = ''; @tracked is
Completed = false; constructor(text) { this.text = text; } } This class represents a todo -- it contains a @tracked text property containing the text of the todo, and a...
...following import statement below the existing one: import { tracked } from '@glimmer/tracking'; Now add the following class below the previous line you added: class Todo { @tracked text = ''; @tracked is
Completed = false; constructor(text) { this.text = text; } } This class represents a todo -- it contains a @tracked text property containing the text of the todo, and a @tracked is
Completed property that specifies whether the todo has been
completed or not. When instantiated, a Todo object will have an initial text value equal to the text given to it when created (see below), and an is
Completed value of false. The only Ember-specific part of this class is the @tracked decorator -- this hooks in to the reactivity system and allows Ember to update what you're seeing in your app autom...
...put> is properly reflected in the UI: Summary OK, so that's great progress for now. We can now add todo items to our app, and the state of the data is tracked using our service. Next we'll move on to getting our footer functionality working, including the todo counter, and look at conditional rendering, including correctly styling todos when they've been checked. We'll also wire up our "Clear
completed" button. Previous Overview: Client-side JavaScript frameworks Next In this module Introduction to client-side frameworks Framework main features React Getting started with React Beginning our React todo list Componentizing our React app React interactivity: Events and state React interactivity: Editing, filtering, conditional rendering Accessibility in React ...
Accessibility in React - Learn web development
aScript languages, knowledge of the terminal/command line. Objective: To learn about implementing keyboard accessibility in React. Including keyboard users At this point, we've accomplished all of the features we set out to implement. A user can add a new task, check and uncheck tasks, delete tasks, or edit task names. And they can filter their task list by all, active, or
completed tasks. Or, at least: they can do all of these things with a mouse. Unfortunately, these features are not very accessible to keyboard-only users. Let's explore this now. Exploring the keyboard usability problem Start by clicking on the input at the top of our app, as if you're going to add a new task. You'll see a thick, dashed outline around that input. This outline is your visual indicator t...
... and you will see this dashed focus indicator move between each of the filter buttons. Keep going until the focus indicator is around the first "Edit" button. Press Enter. The <Todo /> component will switch templates, as we designed, and you'll see a form that lets us edit the name of the task. But where did our focus indicator go? When we switch between templates in our <Todo /> component, we
completely remove the elements that were there before to replace them with something else. That means the element that we were focused on vanishes, and nothing is in focus at all. This could confuse a wide variety of users -- particularly users who rely on the keyboard, or users who use a screen reader. To improve the experience for keyboard and screen-reader users, we should manage the browser's focus o...
...llow a pattern similar to our previous changes: we'll make a new ref, and utilize our usePrevious() hook, so that we can focus on the list heading whenever a user deletes a task. Why the list heading? Sometimes, the place we want to send our focus to is obvious: when we toggled our <Todo /> templates, we had an origin point to "go back" to -- the "Edit" button. In this case however, since we're
completely removing elements from the DOM, we have no place to go back to. The next best thing is an intuitive location somewhere nearby. The list heading is our best choice because it's close to the list item the user will delete, and focusing on it will tell the user how many tasks are left. Creating our ref Import the useRef() and useEffect() hooks into App.js -- you'll need them both below: import ...
Adding a new todo form: Vue events, methods, and models - Learn web development
rt default {}; </script> Let's add in an HTML form that lets you enter a new todo item and submit it into the app. We need a <form> with a <label>, an <input>, and a <button>. Update your template as follows: <template> <form> <label for="new-todo-input"> What needs to be done? </label> <input type="text" id="new-todo-input" name="new-todo" auto
complete="off" /> <button type="submit"> Add </button> </form> </template> So we now have a form component into which we can enter the title of a new todo item (which will become a label for the corresponding ToDoItem when it is eventually rendered). Let's load this component into our app. Go back to App.vue and add the following import statement just below the previous one, i...
...et on it and keeps it in sync with the <input>. v-model works across all the various input types, including check boxes, radios, and select inputs. To use v-model, you add an attribute with the structure v-model="variable" to the <input>. So in our case, we would add it to our new-todo-input field as seen below. Do this now: <input type="text" id="new-todo-input" name="new-todo" auto
complete="off" v-model="label" /> Note: You can also sync data with <input> values through a combination of events and v-bind attributes. In fact, this is what v-model does behind the scenes. However, the exact event and attribute combination varies depending on input types and will take more code than just using the v-model shortcut. Let's test out our use of v-model by logging the valu...
...e as well. Update your ToDoForm component's onSubmit() method to this: onSubmit() { if(this.label === "") { return; } this.$emit('todo-added', this.label); this.label = ""; } Now when you click the "Add" button, the "new-todo-input" will clear itself. Summary Excellent. We can now add todo items to our form! Our app is now starting to feel interactive, but one issue is that we've
completely ignored its look and feel up to now. In the next article, we'll concentrate on fixing this, looking at the different ways Vue provides to style components. Previous Overview: Client-side JavaScript frameworks Next In this module Introduction to client-side frameworks Framework main features React Getting started with React Beginning our React todo list Componentizing ...
Handling common HTML and CSS problems - Learn web development
ms, It is probably better to rely on simple form elements, or selectively use advanced form elements only in supporting browsers, or using a library that provides decent cross browser form widgets, such as jQuery UI or Bootstrap datepicker. CSS fallback behaviour CSS is arguably better at fallbacks than HTML. If a browser encounters a declaration or rule it doesn't understand, it just skips it
completely without applying it or throwing an error. This might be frustrating for you and your users if such a mistake slips through to production code, but at least it means the whole site doesn't come crashing down because of one error, and if used cleverly you can use it to your advantage. Let's look at an example -- a simple box styled with CSS, which has some styling provided by various CSS3 featur...
...This is useful for finding out what versions of the property are implemented in that browser. At the time of writing, both Firefox and Chrome implemented -webkit- prefixed and non-prefixed versions of transform! Once you've found out which prefixes you need to support, you should write them all out in yo...
...l, searching for Autoprefixer, then hitting install. You can set a browser query by pressing the Autoprefixer Settings button and entering the query in the text field in the Settings section on the page. In your code, you can select sections of CSS you want to add prefixes to, open the command pallette (Cmd/Ctrl + Shift + P), then type in Autoprefixer and select the Autoprefixer result that auto
completes. As an example, we entered the following code: body { display: flex; } We highlighted it and ran the Autoprefixer command, and it replaced it with this: body { display: -webkit-box; display: -ms-flexbox; display: flex; } Layout issues Another problem that might come up is differences in layouts between browsers. Historically this used to be much more of a problem, but recently, wi...
Command line crash course - Learn web development
, you type cd into your terminal, followed by the directory you want to move to. Assuming the directory is inside your home directory, you can use cd Desktop (see the screenshots below). Try typing this into your system's terminal: cd Desktop If you want to move back up to the previous directory, you can use two dots: cd .. Note: A very useful terminal shortcut is using the tab key to auto
complete names that you know are present, rather than having to type out the whole thing. For example, after typing the above two commands, try typing cd D and pressing tab -- it should auto
complete the directory name Desktop for you, provided it is present in the current directory. Bear this in mind as you move forward. If the directory you want to go to is nested deep, you need to know the path to get...
...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/Gl...
...ling using npm, like we did with Prettier. ...
Deploying our app - Learn web development
article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. We push the code to GitHub, deploy it using Netlify, and even show you how to add a simple test into the process. Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages. Objective: To finish working through our
complete toolchain case study, focusing on deploying the app. Post development There's potentially a large range of problems to be solved in this section of the project's lifecycle. As such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible. Here's just a few things to consider for this particular project: Generati...
...lly pick up the changes, run the build tasks, and finally release a new update. We're going to add the build command to our package.json file as an npm script, so that the command npm run build will trigger the build process. This step isn't necessary, but it is a good best practice to get into the habit of setting up -- across all our projects, we can then rely on npm run build to always do the
complete build step, without needing to remember the specific build command arguments for each project. Open the package.json file in your project's root directory, and find the scripts property. We'll add a build command that we can run to build our code. Add the following line to your project now: "scripts": { ... "build": "parcel build src/index.html" } Note: If the scripts pro...
...eact be swapped out for something smaller? ...
Learn web development
Welcome to the MDN learning area. This set of articles aims to provide
complete beginners to web development with all that they need to start coding websites. The aim of this area of MDN is not to take you from "beginner" to "expert" but to take you from "beginner" to "comfortable." From there, you should be able to start making your way, learning from the rest of MDN, and other intermediate to advanced resources that assume a lot of previous knowledge. If you are a
complete beginner, web development can be challenging -- we will hold your hand and provide enough detail for you to feel comfortable and learn the topics properly. You should feel at home whether you are a student learning web development (on your own or as part of a class), a teacher looking for class materials, a hobbyist, or som...
...g area release notes to show what has changed -- keep checking back frequently! If you have questions regarding topics you'd like to see covered or feel are missing, drop us a message on our Discourse forum. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Where to start
Complete beginner: If you are a
complete beginner to web development, we'd recommend that you start by working through our Getting started with the web module, which provides a practical introduction to web development. Beyond the basics: If you have a bit of knowledge already, the next step is to learn HTML and CSS in detail: start with our Introduction to HTML module and move on to our CSS first steps ...
...cs refers to the meaning of a piece of code -- for example "what effect does running that line of JavaScript have?", or "what purpose or role does that HTML element have" (rather than "what does it look like?".) Topics covered The following is a list of all the topics we cover in the MDN learning area. Getting started with the web Provides a practical introduction to web development for
complete beginners. HTML -- Structuring the web HTML is the language that we use to structure the different parts of our content and define what their meaning or purpose is. This topic teaches HTML in detail. CSS -- Styling the web CSS is the language that we can use to style and layout our web content, as well as adding behavior like animation. This topic provides comprehensive coverage of CSS. Java...
Gecko info for Windows accessibility vendors
not obvious where the ROLE_SYSTEM_ROW should exist in the tree when the HTML rowspan attribute is used to combine to cells in different rows. There are currently two techniques for parsing tables: 1) use accLocation() to get the coordinates for each cell and feed that into an algorithm that builds up your own table data structure, or 2) use ISimpleDOMNode and parse the table See below for the
complete list of roles and notes about what we support Intentional Differences with Internet Explorer For the most part, where we support an MSAA feature, we have tried to duplicate Internet Explorer's use of it. Please let us know if you find any differences not listed here: Accessible Relations are Supported The accNavigate() method can be used with new constants defined for Gecko. The r...
...text uses no tag or element, uses STATE_READONLY For editable text, that state is cleared. XUL: <textbox> HTML: <input type="text"> or <textarea> DHTML: role="wairole:textfield" or role="wairole:textarea" Sets STATE_LINKED if within link. Sets STATE_TRAVERSED if within visited link. ...
...ou may have heard of some content types beyond HTML, and want to know if Gecko based products will support them: DHTML and AJAX: Gecko and other browsers have long supported dynamic content, where the page appearance changes because of JavaScript. This can be used to create the appearance of desktop-style widgets like menus, spreadsheets and tree views which HTML lacks. Or, it can be used to
completely change content on the fly, without loading a new page. Previously it was not posible to make this accessible, but Firefox 1.5 supports Accessible DHTML, which allows authors to make advanced widgets and web applications accessible. MathML: an XML dialect used to display full math notation on web pages. We do not currently have plans to support MSAA for MathML - we will likely suggest use of t...
Software accessibility: Where are we today?
A major limitation - the lack of context The solutions developed by these accessibility vendors have greatly increased the employment and personal fulfillment opportunities of hundreds of thousands of persons with disabilities, and the importance of their work cannot be diminished. However, all these solutions fell short of providing people with disabilities with a working environment which was
completely accessible and usable by them. This is due to a simple problem of context - the idea that a user's interaction with a computer is governed by the situation in which this interaction takes place. When the user types something on the keyboard, or when an application displays text or images on the screen, the exact meaning of these actions is determined by the context in which they take place. For...
... this interaction takes place. When the user types something on the keyboard, or when an application displays text or images on the screen, the exact meaning of these actions is determined by the context in which they take place. For example, one application might display the image of a light bulb to indicate that it is processing a task, while another might display it as an indicator that it has
completed processing a task. Without the application somehow notifying a blind person about the meaning of the light bulb image, the blind person is unable to understand what the application is attempting to convey. Similarly, voice recognition software often needs information about the context of a user's interaction, in order to make sense of what the user is speaking. This context problem still plagues...
...vey. Similarly, voice recognition software often needs information about the context of a user's interaction, in order to make sense of what the user is speaking. This context problem still plagues modern accessibility aids and solutions. The most recent noteable attempt at solving this problem was put forth by Microsoft in 1997, and is called Microsoft Active Accessibility (MSAA). Realizing that
complete accessibility was not possible without cooperation between applications and accessibility aids such as screen reading software or voice recognition software, Microsoft Active Accessibility defines a Windows-based standard by which applications can communicate context and other pertanent information to accessibility aids. This solution has seen only partial success, largely due to the fact that it...
Mozilla’s UAAG evaluation report
PG and GIF. This evaluation does not cover Mailnews or Composer. There may be accessibility and customizability features not listed here. A very good resource is The Customizing Document. When filing Mozilla bugs based on UAAG requirements, please use bug 24413 as the UAAG meta bug. Checkpoint Information (Same scaled used on W3C's UAAG implementation reports pages) Rating Scale C:
Complete Implementation VG: Very Good Implementation, almost all requirements satisfied G: Good Implementation, most important requirements satisfied P: Poor Implementation, some requirements satisfied and/or difficult for user to access feature NI: Not Implemented NR: Not Rated NA: Not Applicable Document under construction Guideline 1. Support input and output...
... 6.7 API character encodings. (P1) ? We use 16 bit strings, not sure about UTF-16 6.8 DOM CSS access. (P2) G The DOM is available in-process, but not via an out-of-process (COM) interface. Out-of-process access is needed for it to be truly useful for assistive technology 6.9 Timely access. (P2) NR Too vague to measure. Rating Scale C:
Complete Implementation VG: Very Good Implementation, almost all requirements satisfied G: Good Implementation, most important requirements satisfied P: Poor Implementation, some requirements satisfied and/or difficult for user to access feature NI: Not Implemented NR: Not Rated NA: Not Applicable Guideline 7. Observe operating environment conventions. C...
...atures. (P1) NI No end user accessibility documentation yet 12.3 Document default bindings. (P1) NI No end user accessibility documentation yet 12.4 Document changes. (P2) NI No end user accessibility documentation yet 12.5 Dedicated section on accessibility. ...
Accessible Toolkit Checklist
always are. For example, lists of checkboxes are implemented in Windows with images of checked and unchecked checkboxes. Owner drawn toolkits , like XUL and Flash's Flex UI framework use few or no native widgets. These toolkits need to have accessibility implemented from the ground up, and get nothing for free in terms of keyboard, API or OS-theme support. In this case, adding a
complete or even a partial accessibility solution is major work, and will require more than one full time person as well as cooperation from Windows assistive technology vendors when parts of your MSAA solution isn't working. Often these kinds of toolkits don't use a separate window for each control; in that case remember to generate a unique 32 bit child ID for each control so that the MSAA event system ...
...andle standard editing keys, such as arrow keys, home, end, pageup, pagedown, ctrl+left/right, shifted keys for selection, delete, ctrl+delete, backspace, ctrl+backspace, ctrl+a, ctrl+b, ctrl+c, ctrl+i, ctrl+u, ctrl+x, ctrl+v, ctrl+[shift]+z In multiline text field, Enter key inserts new line (thus default button no longer shows dark border when multiline text field is focused) In auto
complete text fields, make sure the auto
complete popup doesn't receive actual or MSAA focus unless an up/down arrow is pressed, and don't use the default system highlight color in the list itself unless it really has focus In auto
complete text fields, make sure that the delete or backspace key removes all auto
completed selected text. In auto
complete text fields, make sure that the left or rig...
...ce is used to bring up the context menu. Space bar toggles checkboxes For listboxes, use owner drawn list items to show a different highlight color when the list is not focused. If you don't the list focus will not be apparent, and screen readers may read the selected list item when they shouldn't. For unfocused lists, use a lighter color highlight to show a non-focused state. For auto
complete lists, use the system color offset by 1, so that it looks active but the list items don't get echoed while they user's trying to simply type and edit. MSAA support, including accessible selection, selectable, multiselectable and extselectable states, and statechange events for checkbox children Trees When a tree view is tabbed to, select the first item if nothing else i...
Browser chrome tests
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. ...
...s 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 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 ...
...write the test to make is shorter, split it into smaller tests, or find why it's taking so long, you should really do that instead! function test() { // requestLongerTimeout accepts an integer factor, that is a multiplier for the the default 30 seconds timeout. // So a factor of 2 means: "Wait for at last 60s (2*30s)". requestLongerTimeout(2); waitForExplicitFinish(); setTimeout(
completeTest, 40000); } function
completeTest() { ok(true, "Timeout did not run"); finish(); } Exceptions in tests Any exceptions thrown under test() will be caught and reported in the test output as a failure. Exceptions thrown outside of test() (e.g. in a timeout, event handler, etc) will not be caught, but will result in a timed out test if they prevent finish() from being called. Cleanin...
Chrome registration
With Gecko 1.9.2 and older, Mozilla reads chrome/*.manifest files from applications. Starting with Gecko 2.0, the root chrome.manifest is the only manifest used; you can add manifest commands to that file to load secondary manifests. Chrome providers A supplier of chrome for a given window type (e.g., for the browser window) is called a chrome provider. The providers work together to supply a
complete set of chrome for a particular window, from the images on the toolbar buttons to the files that describe the text, content, and appearance of the window itself. There are three basic types of chrome providers: Content The main source file for a window description comes from the content provider, and it can be any file type viewable from within Mozilla. It will typically be a XUL file, since ...
...ell as most XBL binding files. Locale Localizable applications keep all their localized information in locale providers. This allows translators to plug in a different chrome package to translate an application without altering the rest of the source code. The two main types of localizable files are DTD files and Java-style properties files. Skin A skin provider is responsible for providing a
complete set of files that describe the visual appearance of the chrome. Typically a skin provider will provide CSS files and images. Note: Scripts (including those found in XBL) loaded from skin packages will not execute. The chrome registry The Gecko runtime maintains a service known as the chrome registry that provides mappings from chrome package names to the physical location of chrome packages...
...and older versions of Firefox will need to provide a fallback. For example: content packagename chrome/path/ content packagename chrome/path/ contentaccessible=yes os Extensions (or themes) may offer different features depending on the operating system on which Firefox is running. The value is compared to the value of OS_TARGET for the platform. os=WINNT os=Darwin See OS_TARGET for a more
complete list of os names. The os name is case insensitive. osversion An extension or theme may need to operate differently depending on which version of an operating system is running. For example, a theme may wish to adopt a different look on Mac OS X 10.5 than 10.4: osversion>=10.5 abi If a component is only compatible with a particular ABI, it can specify which ABI/OS by using this directive. ...
Capturing a minidump
This page describes how to capture these minidumps on Windows, to permit better debugging. ...
... state of a program as it's running, or as it was at the moment of a crash. Small minidumps are created by the Breakpad crash reporting tool, but sometimes that's not sufficient to diagnose a problem. For example, if the application is hanging (not responding to input, but hasn't crashed) then Breakpad is not triggered, and it can be difficult to determine where the problem lies. Sometimes a more
complete form of minidump is needed to see additional details about a crash, in which case manual capture of a minidump is desired. This page describes how to capture these minidumps on Windows, to permit better debugging. Privacy and minidumps Warning! Unlike the minidumps submitted by Breakpad, these minidumps contain the
complete contents of program memory. They are therefore much more likely to con...
...the debugger spits out some text right away and Firefox doesn't come up, select Debug -> Go again. When the program is about to crash, WinDbg will spit out more data, and the prompt at the bottom will change from saying "*BUSY*" to having a number in it. At this point, you should type ".dump /ma c:\temp\firefoxcrash.dmp" -- without the quotes, but don't forget the dot at the beginning. Once it
completes, which can take a fair while, you will have a very large file at c:\temp\firefoxcrash.dmp that can be used to help debug your problem. File size will depend on this size of Firefox running in your enviroment, which could several GB. Ask in the relevant bug or thread how best to share this very large file! Capturing a minidump: application hang On Windows Vista and Windows 7, you can follow ...
Debugging on Mac OS X
nction # that we know will both run early (which we want when we start first start the # app) and run frequently (which we want so that it will trigger ASAP if we # attach to an already running app). The breakpoint runs some commands to # figure out the object directory path from the attached target and then # sources the .lldbinit from there. # # NOTE: This scripts actions take a few seconds to
complete, so the custom # formatters, commands etc. that are added may not be immediately available. # breakpoint set --name nsThread::ProcessNextEvent --thread-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,...
...t the script runs (for # example, `lldb.target.executable.fullpath` is empty). Therefore we must # get the following objects from the 'frame' object. target = frame.GetThread().GetProcess().GetTarget() debugger = target.GetDebugger() # Delete our breakpoint (not actually necessary with `--one-shot true`): target.BreakpointDelete(bp_loc.GetBreakpoint().GetID()) # For
completeness, find and delete the dummy breakpoint (the breakpoint # lldb creates when it can't initially find the method to set the # breakpoint on): # BUG WORKAROUND! GetID() on the *dummy* breakpoint appears to be returning # the breakpoint index instead of its ID. We have to add 1 to correct for # that! :-( dummy_bp_list = lldb.SBBreakpointList(target) debugger.GetDummyTar...
...ands in the console, located in the Debug area of XCode. For example, type js to see the JavaScript stack. For more information, see Debugging Mozilla with lldb. Debugging e10s child processes Using XCode to debug child processes created by an e10s-enabled browser is a little trickier than debugging a single-process browser, but it can be done. These directions were written using XCode 6.3.1
Complete all the steps above under "Creating the Project" From the "Product" menu, ensure the scheme you created is selected under "Scheme", then choose "Scheme > Edit Scheme" In the resulting popup, click "Duplicate Scheme" Give the resulting scheme a more descriptive name than "Copy of Scheme" Select "Run" on the left-hand side of the settings window, then select the "Info" tab. Set the Executable b...
Simple Instantbird build
rements: While you can build Instantbird on older hardware it can take quite a bit of time to compile on slower machines, and having 8GB of RAM is recommended (though you can probably still get away with 4Gb). Good internet connection for the initial source download. Setup: Depending on your Operating System you will need to carry out a different process to prepare your machine. So firstly
complete the instructions for your OS and then continue following these build instructions. Windows Build Prerequisites GNU/Linux Build Prerequisites Mac OS X Build Prerequisites TIP: After completing Setup for your OS, and before you Get the source, you can opt to add the progressExtension to your mercurial.ini (for Windows) or .hgrc (for *Nix / Mac) file. This will provide status feedback during ...
... that. This may take a while, it's a lot of code! First, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout Note: Unless you have a very good network connection, "hg clone" might fail because it gets interrupted. It is faster and more efficient to use Mercurial bundles instead the first time you fetch the
complete repo. In this case, you need a bundle for comm-central, and a bundle for mozilla-central. Unbundle mozilla-central into a "mozilla" subdirectory of your comm-central repo after unbundling comm-central. Then run python client.py checkout to ensure you are up-to-date. The source code requires 1.5GB of free space or more. Build configuration By default, the build system creates a release build of...
...ticular folder. So, for Instantbird, you would run mach build im which has been configured to automatically rebuild /chat as well. Upstream changes To fetch the latest upstream changes, in your comm-central directory, run the same command as before: python client.py checkout Problems Building? Have you: Tried a clobber? This means deleting the object directory so that your next build is
completely fresh. To do this you can use mach clobber Checked the Instantbird buildbot for known failures at the time you pulled the code? If the trunk is broken, you may wish to consider building one of the branches (to pull the source code from a branch, just replace the url to the repository in the hg clone instruction). Checked to make sure that the path in which you placed the sour...
Error codes returned by Mozilla APIs
t was made to call QueryInterface to retrieve an interface which an object does not support. NS_ERROR_NULL_POINTER (0x80004003) An error occurred because a value was set to null when this was not expected. NS_ERROR_ABORT (0x80004004) This error indicates that an operation failed and the caller should abort whatever action is being performed. This typically will occur if an operation could not
complete properly. NS_ERROR_FAILURE (0x80004005) This is the most general of all the errors and occurs for all errors for which a more specific error code does not apply. NS_ERROR_UNEXPECTED (0x8000FFFF) An operation did not
complete due to a condition which was not expected. This error occurred rather than continuing. NS_ERROR_OUT_OF_MEMORY (0x8007000E) This error occurs when there is not enough me...
...memory available to carry out an operation, or an error occurred trying to allocate memory. NS_ERROR_ILLEGAL_VALUE (0x80070057) An argument supplied to a method was not valid, for instance a null value was supplied as an argument which does not allow null values, or a value was out of range. NS_ERROR_NO_AGGREGATION (0x80040110) NS_ERROR_NOT_AVAILABLE (0x80040111) An operation could not be
completed because some other necessary component or resource was not available. NS_ERROR_FACTORY_NOT_REGISTERED (0x80040154) Returned when a service could not be found. NS_ERROR_FACTORY_REGISTER_AGAIN (0x80040155) This error is returned when registering a component and the registration should try registering again later. NS_ERROR_FACTORY_NOT_LOADED (0x800401f8) NS_ERROR_FACTORY_EXISTS (0xC1F30100...
...s malformed. NS_ERROR_ALREADY_CONNECTED (0x804B000B) The connection is already established. XXX currently unused - consider removing. NS_ERROR_NOT_CONNECTED (0x804B000C) The connection does not exist. XXX currently unused - consider removing. NS_ERROR_CONNECTION_REFUSED (0x804B000D) NS_ERROR_NET_TIMEOUT (0x804B000E) NS_ERROR_IN_PROGRESS (0x804B000F) The requested action could not be
completed while the object is busy. Implementations of nsIChannel.asyncOpen() will commonly return this error if the channel has already been opened (and has not yet been closed). NS_ERROR_OFFLINE (0x804B0010) NS_ERROR_NO_CONTENT (0x804B0011) Returned from nsIChannel.asyncOpen() to indicate that OnDataAvailable will not be called because there is no content available. This is used by helper app styl...
mozbrowseractivitydone
. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. ...
... details The details property returns an anonymous JavaScript object with the following properties: success A Boolean that indicates whether the activity has
completed successfully (true) or not (false). ...
... object with the following properties: success A Boolean that indicates whether the activity has
completed successfully (true) or not (false). ...
HTTP Cache
This document describes the New HTTP cache version 2. The code resides in /network/cache2. API Here is a detailed description of the HTTP cache v2 API, examples included. This document only contains what cannot be found or may not be clear directly from the IDL files comments. The cache API is
completely thread-safe and non-blocking. There is no IPC support. It's only accessible on the default chrome process. When there is no profile the new HTTP cache works, but everything is stored only in memory not obeying any particular limits. It is strongly encoraged to NOT USE the OLD cache API any more - nsICacheService et al. It will soon be
completely obsoleted and removed (bug 913828). nsICacheStorageService The HTTP cache entry-point. Accessible as a service only,...
... C++ consumers: functions at LoadContextInfo.h exported header JS consumers: resource://gre/modules/LoadContextInfo.jsm module methods Two storage objects created with the same set of nsILoadContextInfo arguments are identical, containing the same cache entries. Two storage objects created with in any way different nsILoadContextInfo arguments are strictly and
completely distinct and cache entries in them do not overlap even when having the same URIs. nsICacheStorage //github.com/RealityRipple/UXP/blob/master/netwerk/cache2/nsICacheStorage.idl Obtained from call to one of the *Storage methods on nsICacheStorageService. Represents a distinct storage area (or scope) to put and get cache entries mapped by URLs into and from it. Similari...
...e rest of the data - and becomes that way a new writer. The rest of the readers are still concurrently reading the content since output stream for the cache entry is again open and kept by the current writer. Lifetime of an existing entry with only a partial content Such a cache entry is first examined in the nsICacheEntryOpenCallback.onCacheEntryCheck callback, where it has to be checked for
completeness. In this case, the Content-Length (or different indicator) header doesn't equal to the data size reported by the cache entry. The consumer then indicates the cache entry needs to be revalidated by returning ENTRY_NEEDS_REVALIDATION from onCacheEntryCheck. This consumer, from the point of view the cache, takes a role of the writer. Other parallel consumers, if any, are blocked until the wr...
AsyncShutdown.jsm
pically, each shutdown phase removes some capabilities from the application. For instance, at the end of phase profileBeforeChange, no service is permitted to write to the profile directory (with the exception of Telemetry). Consequently, if any service has requested I/O to the profile directory before or during phase profileBeforeChange, the system must be informed that these requests need to be
completed before the end of phase profileBeforeChange. Failing to inform the system of this requirement can (and has been known to) cause data loss. Example At some point during shutdown, the Add-On Manager needs to ensure that all add-ons have safely written their data to disk, before writing its own data. Since the data is saved to the profile, this must be
completed during phase profileBeforeChange. ...
...s a noop. boolean removeBlocker( in function|promise|* condition ) Arguments condition A condition blocking the completion of the phase. This must be the same condition as was passed to addBlocker prior. Return Value Returns true if a blocker has been removed, or false otherwise. Note that a result of false may mean either that the blocker has never been installed or that the phase has
completed and the blocker has already been resolved. Examples AsyncShutdown.profileBeforeChange.addBlocker("Module: just a promise", promise); // profileBeforeChange will not
complete until // promise is resolved or rejected AsyncShutdown.profileBeforeChange.addBlocker("Module: a callback", function condition() { // ... // Execute this code during profileBeforeChang...
...Shutdown.profileBeforeChange.addBlocker("Module: just a promise", promise); // profileBeforeChange will not
complete until // promise is resolved or rejected AsyncShutdown.profileBeforeChange.addBlocker("Module: a callback", function condition() { // ... // Execute this code during profileBeforeChange return promise; // profileBeforeChange will not
complete until promise // is resolved or rejected }); AsyncShutdown.profileBeforeChange.addBlocker("Module: trivial callback", function condition() { // ... // Execute this code during profileBeforeChange // No specific guarantee about completion of profileBeforeChange }); If the promise returned by condition is not resolved/rejected within one minute, the process will cras...
WebRequest.jsm
, though: see Chrome incompatibilities for the details. Usage To import WebRequest, use code like: let {WebRequest} = Cu.import("resource://gre/modules/WebRequest.jsm", {}); The WebRequest object has the following properties, each of which corresponds to a specific stage in executing a web request: onBeforeRequest onBeforeSendHeaders onSendHeaders onHeadersReceived onResponseStarted on
Completed Each of these objects defines two functions: addListener(callback, filter, opt_extraInfoSpec) removeListener(callback) Adding listeners Use addListener to add a listener to a particular event. It takes one mandatory argument and two optional arguments, as detailed below. Name Type Description callback Function The callback argument is a function t...
...ome examples of using filter. Modifying & canceling requests You can use the WebRequest API to modify and cancel network requests. What exactly you're able to do to a network 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. T...
...oaded, or null if the resource will not be loaded into a XUL browser. method String The HTTP method used (GET, POST, etc). responseHeaders Array of HTTP headers. The HTTP response headers that were received. This is only included if you set "responseHeaders" in the opt_extraInfoSpec argument. statusCode Number HTTP response code. on
Completed Triggered when the response has been received. Note that you can't pass "blocking" for this event, so you can't modify or cancel the request from this event: it's informational only. opt_extraInfoSpec values Name Description "responseHeaders" Include response headers in the argument passed to the listener. Listener argument Name Type Descript...
NSPR Error Handling
ress. PR_UNKNOWN_ERROR Some unknown error has occurred. PR_PENDING_INTERRUPT_ERROR The operation terminated because another thread has interrupted it with PR_Interrupt. PR_NOT_IMPLEMENTED_ERROR The preceding function has not been implemented. PR_IO_ERROR The preceding I/O function encountered some sort of an error, perhaps an invalid device. PR_IO_TIMEOUT_ERROR The I/O operation has not
completed in the time specified for the preceding function. PR_IO_PENDING_ERROR An I/O operation has been attempted on a file descriptor that is currently busy with another operation. PR_DIRECTORY_OPEN_ERROR The directory could not be opened. PR_INVALID_ARGUMENT_ERROR One or more of the arguments to the function is invalid. PR_ADDRESS_NOT_AVAILABLE_ERROR The network address (PRNetAddr) is not avai...
...network address specified is invalid (as reported by the network). PR_ADDRESS_IN_USE_ERROR Network address specified (PRNetAddr) is in use. PR_CONNECT_REFUSED_ERROR The peer has refused to allow the connection to be established. PR_NETWORK_UNREACHABLE_ERROR The network address specifies a host that is unreachable (perhaps temporary). PR_CONNECT_TIMEOUT_ERROR The connection attempt did not
complete in a reasonable period of time. PR_NOT_CONNECTED_ERROR The preceding function attempted to use connected semantics on a network file descriptor that was not connected. PR_LOAD_LIBRARY_ERROR Failure to load a dynamic library. PR_UNLOAD_LIBRARY_ERROR Failure to unload a dynamic library. PR_FIND_SYMBOL_ERROR Symbol could not be found in the specified library. PR_INSUFFICIENT_RESOURCES_ERROR...
...ile to a file system on another device. PR_DIRECTORY_CORRUPTED_ERROR The directory object in the file system is corrupted. PR_FILE_EXISTS_ERROR Attempt to create or rename a file when the new name is already being used. PR_MAX_DIRECTORY_ENTRIES_ERROR Attempt to add new filename to directory would exceed the limit allowed. PR_INVALID_DEVICE_STATE_ERROR The device was in an invalid state to
complete the desired operation. PR_DEVICE_IS_LOCKED_ERROR The device needed to perform the desired request is locked. PR_NO_MORE_FILES_ERROR There are no more entries in the directory. PR_END_OF_FILE_ERROR Unexpectedly encountered end of file (Mac OS only). PR_FILE_SEEK_ERROR An unexpected seek error (Mac OS only). PR_FILE_IS_BUSY_ERROR The file is busy and the operation cannot be performed. PR...
NSS sources building testing
test development snapshot of NSS using mercurial/hg (a distributed source control management tool). In order to get started, anonymous read-only access is sufficient. Create a new directory on your computer that you will use as your local work area, and run the following commands. hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss After the above commands
complete, you should have two local directories, named nspr and nss, next to each other. (Historical information: NSPR and NSS source code have recently been re-organized into a new directory structure. In past versions, all files were located in a directory hierarchy that started with the "mozilla" prefix. The NSPR base library was located in directory mozilla/nsprpub. The subdirectories dbm, security/d...
...ory hierarchy. Any C function that isn't contained in .def files is strictly for private use within NSS, and applications and test tools are not allowed to call them. For any functions that are listed in the .def files, NSS promises that the binary function interface (ABI) will remain stable. Building NSS NSS is built using gyp and ninja, or with make on systems that don't have those tools. The
complete build instructions include more information. Once the build is done, you can find the build output below directory dist/?, where ? will be a name dynamically derived from your system's architecture. Exported header files for NSS applications can be found in directory "include", library files in directory "lib", and the tools in directory "bin". In order to run the tools, you should set your syst...
...n many computers the variables HOST=localhost DOMSUF=localdomain works. In case you built NSS in 64 bits, you need to set the USE_64 environment variable to 1 to run the tests. If you get name resolution errors, try to disable IPv6 on the loopback device. After you have set the required environment variables, use "cd nss/tests" and start the tests using "./all.sh". The tests will take a while to
complete; on a slow computer it could take a couple of hours. Once the test suite has
completed, a summary will be printed that shows the number of failures. You can find the test suite results in directory nss/../tests_results (i.e. the results directory ends up next to the nss directory, not within it). Each test suite execution will create a new subdirectory; you should clean them up from time to time...
sslerr.html
ithm." An SSL client has requested an SSL cipher suite that uses a Key Exchange Algorithm for which the local server has no appropriate public key. This indicates a configuration error on the local server. SSL_ERROR_TOKEN_INSERTION_REMOVAL -12205 "PKCS #11 token was inserted or removed while operation was in progress." A cryptographic operation required to
complete the handshake failed because the token that was performing it was removed while the handshake was underway. Another token may also have been inserted into the same slot. SSL_ERROR_TOKEN_SLOT_NOT_FOUND -12204 "No PKCS#11 token could be found to do a required operation." A cryptographic operation required a PKCS#11 token with specific abilities, and no token could be f...
...nd in any slot, including the "soft token" in the internal virtual slot, that could do the job. May indicate a server configuration error, such as having a certificate that is inappropriate for the Key Exchange Algorithm selected. ...
...e job. May indicate a server configuration error, such as having a certificate that is inappropriate for the Key Exchange Algorithm selected. ...
Statistics API
efox (e10s) it is necessary to set security.sandbox.content.level = 0, otherwise the content process will crash. The browser preference javascript.options.mem.log controls dumping of human-readable GC stats messages to the developer console. The browser preference javascript.options.mem.notify controls emission of JSON encoded GC stats to an observer interface. JSON API Addons can obtain the
complete data in JSON format via an observer. The following adds an observer using the JetPack framework. var prefs = require("api-utils/preferences-service"); Components.utils.import('resource://gre/modules/Services.jsm'); function observer(subject, topic, json) { var data = JSON.parse(json); // process the data } prefs.set("javascript.options.mem.notify", true); Services.obs.addObserver(obser...
...umber of compartments that were collected by the GC. compartment_count: integer - The number of compartments that were present in the system at the end of the GC. max_pause: number (milliseconds) - Longest duration pause during the GC. nonincremental_reason: string - A string representing the reason that an incremental GC was aborted or forced to finish in a single slice. If the incremental GC
completed normally, this will be "none". allocated: integer (MB) - Size of the JavaScript heap in MiB at the start of the GC. slices: array of Objects - A list of objects describing each slice in detail. times: Object - A map from phase names to the total time taken by each phase: the sum of each field of the map from the slices. The last two fields require a bit of elaboration. GC work can be divide...
...or sweeping. The division into phases is hierarchical, so a phase can be split into subphases. For example, the sweep phase includes the time for the sweep_atoms, sweep_tables, sweep_compartments phases and so on. The times object gives how much time was spent in each phase of the GC, in milliseconds. Additionally, an incremental GC is divided into a series of slices (the division into slices is
completely separate from the division into phases; neither one is a refinment of the other). A little bit of GC work is done in each slice. In between slices, other browser code is allowed to run. The slices array describes how long each slice took and what work was done during the slice. Each element of the slices array is an object with these fields: slice: integer - The slice index, starting at 0. ...
An Overview of XPCOM
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 that defines the DoSomethingUseful method. In this way, construction 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 ...
... shown below: The nsISupports Interface class Sample: public nsISupports { private: nsrefcnt mRefCnt; public: Sample(); virtual ~Sample(); NS_IMETHOD QueryInterface(const nsIID &aIID, void **aResult); NS_IMETHOD_(nsrefcnt) AddRef(void); NS_IMETHOD_(nsrefcnt) Release(void); }; The various types used in the interface are described in the XPCOM Types section below. A
complete (if spare) implementation of the nsISupports interface is shown below. See A Reference Implementation of QueryInterface for detailed information. Implementation of nsISupports Interface // initialize the reference count to 0 Sample::Sample() : mRefCnt(0) { } Sample::~Sample() { } // typical, generic implementation of QI NS_IMETHODIMP Sample::QueryInterface(const nsIID &aIID, ...
...traction which provides uniform and powerful access to files, directory services which maintain the location of application- and system-specific locations, memory management to ensure everyone uses the same memory allocator, and an event notification system that allows passing of simple messages. The tutorial will show each of these component and services in use, and the XPCOM API Reference has a
complete interface listing of these areas. XPCOM Types There are many XPCOM declared types and simple macros that we will use in the following samples. Most of these types are simple mappings. The most common types are described in the following sections. Method Types The following are a set of types for ensuring correct calling convention and return type of XPCOM methods. NS_IMETHOD Meth...
Monitoring HTTP activity
This is done using the nsIHttpActivityDistributor.addObserver() method in nsIHttpActivityDistributor: var activityDistributor = Components.classes["@mozilla.org/network/http-activity-distributor;1"] .getService(Componen...
...This is done using the nsIHttpActivityDistributor.addObserver() method in nsIHttpActivityDistributor: var activityDistributor = Components.classes["@mozilla.org/network/http-activity-distributor;1"] .getService(Components.interfaces.nsIHttpActivityDistr...
...ANSPORT, 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 well as incoming HTTP headers and
complete HTTP transactions. ...
imgIContainer
h, [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! Obsolete since Gecko 2.0 gfxImageSurface copyFrame(in PRUint32 aWhichFrame, in PRUint32 aFlags); Native code only! void decoding
Complete(); 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 ...
...number, in PRInt32 aTimeout); Obsolete since Gecko 2.0 void startAnimation(); Obsolete since Gecko 2.0 void stopAnimation(); Obsolete since Gecko 2.0 void unlockImage(); Attributes Attribute Type Description animated boolean Whether this image is animated. You can only be guaranteed that querying this will not throw if STATUS_DECODE_
COMPLETE is set on the imgIRequest. Read only. Exceptions thrown NS_ERROR_NOT_AVAILABLE If the animated state cannot be determined. animationMode unsigned short currentFrame gfxASurface Get a surface for the current frame. This may be a platform-native, optimized frame, so you cannot inspect its pixel data. Read only. Native code on...
... new copy of the given frame that you can write to and otherwise inspect the pixels of. gfxImageSurface copyFrame( in PRUint32 aWhichFrame, in PRUint32 aFlags ); Parameters aWhichFrame Frame specifier of the FRAME_* variety. aFlags Flags of the FLAG_* variety. Return value Missing Description Exceptions thrown Missing Exception Missing Description decoding
Complete() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) void decoding
Complete(); Parameters None. Exceptions thrown Missing Exception Missing Description Native code only!draw Draw the current frame on to the context specified. void draw( in gfxContext aContext, in gfxGraphicsFilter aFilter, [const] in gfxMatrix aUserSpaceToImageSpace, [const]...
nsIBrowserHistory
ed as explicitly followed by the user. markPageAsTyped() 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.markPageAsTyped() instead. This method designates the URL as having been explicitly typed in by the user, so it can be used as an auto
complete 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 auto
complete. This will cause the transition type of the next visit of the URL to be marked as "typed." void markPageAsTyped( in nsIURI aURI ); Parameters aU...
... the transition type of the next visit of the URL to be marked as "typed." void markPageAsTyped( in nsIURI aURI ); Parameters aURI The page that is to be marked as typed by the user. registerOpenPage() Obsolete since Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Mark a page as being currently open. Note: This method was an alias for mozIPlacesAuto
Complete.registerOpenPage(), which still exists and can be used instead. void registerOpenPage( in nsIURI aURI ); Parameters aURI The page that is to be marked as currently open. removeAllPages() This method removes all the pages from the global history. void removeAllPages(); Parameters None. Remarks Visits are removed synchronously, but pages are expired asynchronously, off the main th...
...o remove, in microseconds from epoch. aEndTime The time of the last page to remove, in microseconds from epoch. unregisterOpenPage() Obsolete since Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Mark a page as no longer being open (either by closing the window or tab, or by navigating away from that page). Note: This method was an alias for mozIPlacesAuto
Complete.unregisterOpenPage(), which still exists and can be used instead. void unregisterOpenPage( in nsIURI aURI ); Parameters aURI The page to unregister as an open page. See also Places Using the Places history service nsIGlobalHistory2 ...
nsIBrowserSearchService
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 that this code ...
... in the engine description file. confirm A boolean value indicating whether the user should be asked for confirmation before this engine is added to the list. If this value is false, the engine will be added to the list upon successful load, but it will not be selected as the current engine. callback A nsISearchInstallCallback that will be notified when the addition is
complete, or if the addition fails. It will not be called if addEngine throws an exception. Exceptions thrown NS_ERROR_FAILURE If the type is invalid, or if the description file cannot be successfully loaded. addEngineWithDetails() Adds a new search engine, without asking the user for confirmation and without starting to use it right away. void addEngineWithDetails( in AString name, i...
...eCount)] out nsISearchEngine engines ); Parameters engineCount The number of hidden installed search engines. engines An array of the hidden installed nsISearchEngines. init() Initialize the service, or if the service is already initialized, do nothing. This method was introduced in Firefox 16. Attempting to call any method of this interface before init() has
completed will force the service to fall back to a slower, synchronous, initialization. If your code requires nsIBrowserSearchService and is executed during startup, you should make sure that this code is executed from the callback to init(). void init( [optional] in nsIBrowserSearchInitObserver observer ); Parameters observer If specified, a callback called once initialization is com...
nsIContentViewer
ose(in nsISHEntry historyEntry); void destroy(); [noscript,notxpcom,nostdcall] nsIViewPtr findContainerView(); void getBounds(in nsIntRectRef aBounds); Native code only! [noscript,notxpcom] nsIDocumentPtr getDocument(); void hide(); void init(in nsIWidgetPtr aParentWidget, [const] in nsIntRectRef aBounds); Native code only! ...
...ument without addrefing. [noscript,notxpcom] nsIDocumentPtr getDocument(); Parameters None. Return value The DOM document object. hide() void hide(); Parameters None. Native code only!init Initializes the content viewer. ...
...ing. [noscript,notxpcom] nsIDocumentPtr getDocument(); Parameters None. Return value The DOM document object. hide() void hide(); Parameters None. Native code only!init Initializes the content viewer. ...
nsIDNSService
<< 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. aFlags A bitwise OR of the Resolve flag constants. aListener The listener to be notified when the result is available. aListenerTarget Option...
...arget aListenerTarget ); Parameters aHostName The host name or IP-address-literal to resolve. aFlags A bitwise OR of the Resolve flag constants. aListener The listener to be notified when the result is available. aListenerTarget Optional parameter (may be null). If not null, this parameter specifies the nsIEventTarget of the thread on which the listener's onLookup
Complete should be called. If this parameter is null, then onLookup
Complete will be called on an unspecified thread (possibly recursively). Return value An object that can be used to cancel the host lookup. init() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Called to initialize the DNS service. void init(); Parameters None. resolve() Called to synch...
...ethod. void shutdown(); Parameters None. ...
nsIDOMSimpleGestureEvent
r trackpad gesture event. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIDOMMouseEvent Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) The nsIDOMSimpleGestureEvent interface is the datatype for all Mozilla-specific simple gesture events in the Document Object Model. The following events are generated: MozSwipeGesture - Generated when the user
completes a swipe across across the input device. MozMagnifyGestureStart - Generated when the user begins the magnify ("pinch") gesture. The "delta" value represents the initial movement. MozMagnifyGestureUpdate - Generated periodically while the user is continuing the magnify ("pinch") gesture. The "delta" value represents the movement since the last MozMagnifyGestureStart or MozMagnifyGestureUpdate ev...
...estureStart - Generated when the user begins the magnify ("pinch") gesture. The "delta" value represents the initial movement. MozMagnifyGestureUpdate - Generated periodically while the user is continuing the magnify ("pinch") gesture. The "delta" value represents the movement since the last MozMagnifyGestureStart or MozMagnifyGestureUpdate event. MozMagnifyGesture - Generated when the user has
completed the magnify ("pinch") gesture. If you only want to receive a single event when the magnify gesture is
complete, you only need to hook this event and can safely ignore the MozMagnifyGestureStart and the MozMagnifyGestureUpdate events. The "delta" value is the cumulative amount represented by the user's gesture. MozRotateGestureStart - Generated when the user begins the rotation gesture. The "del...
...s gesture. MozRotateGestureStart - Generated when the user begins the rotation gesture. The "delta" value represents the initial rotation. MozRotateGestureUpdate - Generated periodically while the user is continuing the rotation gesture. The "delta" value represents the rotation since the last MozRotateGestureStart or MozRotateGestureUpdate event. MozRotateGesture - Generated when the user has
completed the rotation gesture. If you only want to receive a single event when the rotation gesture is
complete, you only need to hook this event and can safely ignore the MozRotateGestureStart and the MozRotateGestureUpdate events. The "delta" value is the cumulative amount of rotation represented by the user's gesture. MozTapGesture - Generated when the user executes a two finger tap gesture on the in...
nsIJumpListBuilder
None. addListToBuild() Adds a list and if required, a set of items for the list. boolean addListToBuild( in short aCatType, in nsIArray items, Optional in AString catName Optional ); Parameters aCatType The type of list to add. items Optional An array of nsIJumpListItem items to add to the list. catName Optional For custom lists, the title of the list. Return value true if the operation
completed successfully. Exceptions thrown NS_ERROR_UNEXPECTED On internal errors. NS_ERROR_ILLEGAL_VALUE If an item is added that was removed since the last commit. NS_ERROR_INVALID_ARG If incorrect parameters are passed for a particular category or item type. commitListBuild() Commits the current jump list build to the Taskbar. boolean commitListBuild(); Parameters None. Return value true if the opera...
...cessfully. Exceptions thrown NS_ERROR_UNEXPECTED On internal errors. NS_ERROR_ILLEGAL_VALUE If an item is added that was removed since the last commit. NS_ERROR_INVALID_ARG If incorrect parameters are passed for a particular category or item type. commitListBuild() Commits the current jump list build to the Taskbar. boolean commitListBuild(); Parameters None. Return value true if the operation
completed successfully. deleteActiveList() Deletes any currently applied taskbar jump list for this application. Common uses would be the enabling of a privacy mode and uninstallation. boolean deleteActiveList(); Parameters None. Return value true if the operation
completed successfully. Exceptions thrown NS_ERROR_UNEXPECTED On internal errors. initListBuild() Initializes a jump list build and returns ...
... ...
nsIMsgDBView
g 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 onDelete
Completed(in boolean succeeded); nsMsgViewIndex findIndexFromKey(in nsMsgKey aMsgKey, in boolean aExpand); void ExpandAndSelectThreadByIndex(in nsMsgViewIndex aIndex, in boolean aAugment); void addColumnHandler(in AString aColumn, in nsIMsgCustomColumnHandler aHandler); void removeColumnHandler(in AString aColumn); nsIMsgCustomColumnHandler getColumnHandler(in ...
...index of the message to load. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. loadMessageByUrl() Loads a message into the message pane. void loadMessageByUrl(in string aUrl); Parameters aUrl The URL of the message reloadMessage() Reload the currently shown message. void reloadMessage(); reloadMessageWithAllParts() Reload the currently shown message with fetch
CompleteMessage set to true. This forces everything to be re-downloaded. void reloadMessageWithAllParts(); selectMsgByKey() Selects a message based on its key. Used by "go to folder" feature and "remember last selected message" feature. If key is not found, nothing is selected. void selectMsgByKey(in nsMsgKey key); Parameters key The Key of the message to load. nsMsgKey is defined as an unsi...
...erMsgByKey() Selects a message within a folder by its key. This assumes that the key is somewhere in the displayed messages... I think. void selectFolderMsgByKey(in nsIMsgFolder aFolder, in nsMsgKey aKey); Parameters aFolder The nsIMsgFolder to search within. aKey The key of the message. nsMsgKey is defined as an unsigned long in MailNewsTypes2.idl. onDelete
Completed() Called when delete is
completed on a message. Used to notify the tree that rows are going away. void onDelete
Completed(in boolean succeeded); Parameters succeeded true if the delete was successful. findIndexFromKey() Gets the index of a message with a particular key. nsMsgViewIndex findIndexFromKey(in nsMsgKey aMsgKey, in boolean aExpand); Param...
Address Book examples
d view overlay. A photo display handler is a function that behaves as follows: /* * function(aCard, aImg): * The function is responsible for determining how to retrieve * the photo from nsIAbCard aCard, and for displaying it in img * img element aImg. Returns true if successful. If it returns * false, the generic photo display handler will be called. */ How do I set up auto
complete to use the address book? There are 3 address book auto
complete widgets: "mydomain" - use to auto
complete a domain for an email identity, e.g. for a user @bar.com, entering foo would become foo@bar.com "addrbook" - use to auto
complete from a local address book, e.g. a Mork based local store or a OS X address book LDAP - use for searching in LDAP address books. MyDomain and Addrbook Autocom...
...domain" - use to auto
complete a domain for an email identity, e.g. for a user @bar.com, entering foo would become foo@bar.com "addrbook" - use to auto
complete from a local address book, e.g. a Mork based local store or a OS X address book LDAP - use for searching in LDAP address books. MyDomain and Addrbook Auto
complete "mydomain" and "addrbook" both use the toolkit interfaces to provide auto
complete facilities. To use them in code all you need to do is set up your text box as follows: <textbox id="myauto
completetextbox" type="auto
complete" auto
completesearch="mydomain addrbook"/> The attributes of the toolkit auto
complete element can also be used here. The "mydomain" and "addrbook" behaviours can be changed by passing an identity key (see nsIMsgIdentity.key) via an attribute autocomplet...
...o do is set up your text box as follows: <textbox id="myauto
completetextbox" type="auto
complete" auto
completesearch="mydomain addrbook"/> The attributes of the toolkit auto
complete element can also be used here. The "mydomain" and "addrbook" behaviours can be changed by passing an identity key (see nsIMsgIdentity.key) via an attribute auto
completesearchparam on the textbox element. LDAP Auto
complete LDAP auto
complete still uses the XPFE interfaces, it is planned (bug 452232) to move this over to the toolkit interfaces at some stage. The best example of how to use this is via the existing code that can be found here. Click here for a addon demonstrating auto
complete with LDAP and addrbook working with both Thunderbird 2 and Thunderbird 3. ...
Index
the Activity Manager page, and the Activity Manager examples page has code snippets. See nsIActivityManager.idl and nsIActivity.idl files for source documentation. 7 Address Book Interfaces MailNews, Mozilla, SeaMonkey, thunderbird This page contains a list of the interfaces that you'll will most likely hit when writing patches for the Address Book or writing extensions. The
complete list of interfaces for the address book can be found here. Address Book examples show how to perform various tasks and provide code snippets. 8 Address Book examples MailNews, SeaMonkey, thunderbird This article provides examples on accessing and manipulating Thunderbird address books. Address book interfaces provides an overview of the related interfaces. See An overview of ...
...tect When a Folder Opens example. 95 Access Window missing, thunderbird The window object represents the Window of the Thunderbird application as well as the currently opened tabs. You can do many things with the window object, such as accessing the height or width of the window/tab or setting its title, registering timer events and much more. ...
...Enrich MDC by contributing. ...
Demo Addon
...
... }; } // ... ...
... }; } // ... }; let collection = query.getCollect...
URLs - Plugins
ing the plug-in's NPP_URLNotify function and passing it the notifyData value, which may be used to track multiple requests. NPN_GetURLNotify handles the URL request asynchronously. It returns immediately and only later handles the request and calls NPP_URLNotify. Without this notification, the plug-in cannot tell whether a request with a null target failed or a request with a non-null target was
completed. NPError NPN_GetURLNotify(NPP instance, const char* url, const char* target, void* notifyData); The instance, url, and target parameters have the same definitions as those of NPN_GetURL. The notifyData parameter contains private plug-in data that can be used to associate the request with the subsequent NPP_URLNotify call (which returns this value) and/or to pass a poin...
..., const char* target, void* notifyData); The instance, url, and target parameters have the same definitions as those of NPN_GetURL. The notifyData parameter contains private plug-in data that can be used to associate the request with the subsequent NPP_URLNotify call (which returns this value) and/or to pass a pointer to some request-related payload. If a request is not
completed successfully (for example, because the URL is invalid or an HTTP server is down), the browser should call NPP_URLNotify as soon as possible. If a request
completes successfully, and the target is non-null, the browser calls NPP_URLNotify after it has finished loading the URL. If the target is null, it calls NPP_URLNotify after calling NPP_DestroyStream to close the stream. Both the NPN_GetURLNo...
... NPP_URLNotify after it has finished loading the URL. If the target is null, it calls NPP_URLNotify after calling NPP_DestroyStream to close the stream. Both the NPN_GetURLNotify and NPN_PostURLNotify functions call the NPP_URLNotify method to notify the plug-in of the result of a request. Both functions pass the notifyData value to NPP_URLNotify, which tells the plug-in that the URL request was
completed and the reason for completion. void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData); The instance and url parameters have the same definitions as those of NPN_GetURL. The notifyData parameter contains the private plug-in data passed to the corresponding call to NPN_GetURLNotify and NPN_PostURLNotify. Warning: In Gecko 2.0 (Firefox 4 / Thunde...
Debugger.Object - Firefox Developer Tools
ction definition equivalent to the referent function in its effect and result, as a string. Ifpretty is present and true, produce indented code with line breaks. If the referent is not a function that is debuggee code, return undefined. call(this,argument, ...) If the referent is callable, call it with the giventhis value andargument values, and return a completion value describing how the call
completed.This should be a debuggee value, or { asConstructor: true } to invoke the referent as a constructor, in which case SpiderMonkey provides an appropriate this value itself. Eachargument must be a debuggee value. All extant handler methods, breakpoints, and so on remain active during the call. If the referent is not callable, throw a TypeError. This function follows the invocation function conventi...
...ent must be a debuggee value. All extant handler methods, breakpoints, and so on remain active during the call. If the referent is not callable, throw a TypeError. This function follows the invocation function conventions. apply(this,arguments) If the referent is callable, call it with the giventhis value and the argument values inarguments, and return a completion value describing how the call
completed.This should be a debuggee value, or { asConstructor: true } to invokefunction as a constructor, in which case SpiderMonkey provides an appropriate this value itself.Arguments must either be an array (in the debugger) of debuggee values, or null or undefined, which are treated as an empty array. All extant handler methods, breakpoints, and so on remain active during the call. If the referent is n...
...efined, which are treated as an empty array. All extant handler methods, breakpoints, and so on remain active during the call. If the referent is not callable, throw a TypeError. This function follows the invocation function conventions. executeInGlobal(code, [options]) If the referent is a global object, evaluatecode in that global environment, and return a completion value describing how it
completed.Code is a string. All extant handler methods, breakpoints, and so on remain active during the call. This function follows the invocation function conventions. If the referent is not a global object, throw a TypeError exception. Codeis interpreted as strict mode code when it contains a Use Strict Directive. This evaluation is semantically equivalent to executing statements at the global level...
Debugger.Object - Firefox Developer Tools
n definition equivalent to the referent function in its effect and result, as a string. Ifpretty is present and true, produce indented code with line breaks. If the referent is not a function that is debuggee code, return undefined. call(this,argument, ...) If the referent is callable, call it with the giventhis value andargument values, and return a completion value describing how the call
completed.This should be a debuggee value, or { asConstructor: true } to invoke the referent as a constructor, in which case SpiderMonkey provides an appropriate this value itself. Eachargument must be a debuggee value. All extant handler methods, breakpoints, watchpoints, and so on remain active during the call. If the referent is not callable, throw a TypeError. This function follows the invocation func...
...uggee value. All extant handler methods, breakpoints, watchpoints, and so on remain active during the call. If the referent is not callable, throw a TypeError. This function follows the invocation function conventions. apply(this,arguments) If the referent is callable, call it with the giventhis value and the argument values inarguments, and return a completion value describing how the call
completed.This should be a debuggee value, or { asConstructor: true } to invokefunction as a constructor, in which case SpiderMonkey provides an appropriate this value itself.Arguments must either be an array (in the debugger) of debuggee values, or null or undefined, which are treated as an empty array. All extant handler methods, breakpoints, watchpoints, and so on remain active during the call. If the ...
...h are treated as an empty array. All extant handler methods, breakpoints, watchpoints, and so on remain active during the call. If the referent is not callable, throw a TypeError. This function follows the invocation function conventions. evalInGlobal(code, [options]) If the referent is a global object, evaluatecode in that global environment, and return a completion value describing how it
completed.Code is a string. All extant handler methods, breakpoints, watchpoints, and so on remain active during the call. This function follows the invocation function conventions. If the referent is not a global object, throw a TypeError exception. Codeis interpreted as strict mode code when it contains a Use Strict Directive. Ifcode is not strict mode code, then variable declarations incode affect ...
Web console keyboard shortcuts - Firefox Developer Tools
nitiating reverse search) Shift + F9 Ctrl + S Shift + F9 Move to the beginning of the line Home Ctrl + A Ctrl + A Move to the end of the line End Ctrl + E Ctrl + E Execute the current expression Enter Return Enter Add a new line, for entering multiline expressions Shift + Enter Shift + Return Shift + Enter Auto
complete popup These shortcuts apply while the auto
complete popup is open: Command Windows macOS Linux Choose the current auto
complete suggestion Tab Tab Tab Cancel the auto
complete popup Esc Esc Esc Move to the previous auto
complete suggestion Up arrow Up arrow Up arrow Move to the next auto
complete suggestion Down arro...
... Command Wi...
...uto
complete suggestion Tab Tab Tab Cancel the auto
complete popup Esc Esc Esc Move to the previous auto
complete suggestion Up arrow Up arrow Up arrow Move to the next auto
complete suggestion Down arrow Down arrow Down arrow Page up through auto
complete suggestions Page up Page up Page up Page down through auto
complete suggestions Page down Page down Page down Scroll to start of auto
complete suggestions Home Home Home Scroll to end of auto
complete suggestions End End End Global shortcuts These shortcuts work in all tools that are hosted in the toolbox. Command Windows macOS Linux Increase font size Ctrl + + Cmd + + Ctr...
The JavaScript input interpreter - Firefox Developer Tools
cript expressions in the field at the bottom of the console log, at the >> prompt. To enter expressions in single-line mode, type at the prompt and press 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 h...
...d+S on MacOS). A file dialog box opens so you can specify the location to save to. To switch back to single-line mode, click the X icon at the top of the multi-line editing pane, or press Ctrl+B (Windows/Linux) or Cmd+B (MacOS). Accessing variables You can access variables defined in the page, both built-in variables like window and variables added by JavaScript libraries like jQuery: Auto
complete The editor has auto
complete: enter the first few letters and a popup appears with possible completions: Press Enter, Tab, or the right arrow key to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions. Console auto
complete suggestions are case-insensitive. The console suggests completions from the scop...
...ess Enter, Tab, or the right arrow key to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions. Console auto
complete suggestions are case-insensitive. The console suggests completions from the scope of the currently executing stack frame. This means that if you've hit a breakpoint in a function you get auto
complete for objects local to the function. You get auto
complete suggestions for array elements, as well: You can enable or disable autocompletion via the Settings ("gear") menu in the Web Console toolbar. The menuitem Enable Autocompletion has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state. Instant evaluation This f...
Applying styles and colors - Web APIs
t 0.2 which will be used for all shapes from that point on. Every step in the for loop draws a set of circles with an increasing radius. The final result is a radial gradient. By overlaying ever more circles on top of each other, we effectively reduce the transparency of the circles that have already been drawn. By increasing the step count and in effect drawing more circles, the background would
completely disappear from the center of the image. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); // draw background ctx.fillStyle = '#FD0'; ctx.fillRect(0, 0, 75, 75); ctx.fillStyle = '#6C0'; ctx.fillRect(75, 0, 75, 75); ctx.fillStyle = '#09F'; ctx.fillRect(0, 75, 75, 75); ctx.fillStyle = '#F30'; ctx.fillRect(75, 75, 75, 75); ctx.fillStyle = '#FFF';...
...d in with a color only half as dark as the actual stroke color. This is what happens with the 1.0 width line in the previous example code. To fix this, you have to be very precise in your path creation. Knowing that a 1.0 width line will extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,5) results in the situation in the third image--the 1.0 line width ends up
completely and precisely filling a single pixel vertical line. Note: Be aware that in our vertical line example, the Y position still referenced an integer gridline position--if it hadn't, we would see pixels with half coverage at the endpoints (but note also that this behavior depends on the current lineCap style whose default value is butt; you may want to compute consistent strokes with half-pixel co...
...ed off by adding a box with an equal width and half the height of the line's thickness. In this example, we'll draw three lines, each with a different value for the lineCap property. I also added two guides to see the exact differences between the three. Each of these lines starts and ends exactly on these guides. The line on the left uses the default butt option. You'll notice that it's drawn
completely flush with the guides. The second is set to use the round option. This adds a semicircle to the end that has a radius half 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. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); var lineCap = ['butt', 'round', 'square']...
Drawing shapes with canvas - Web APIs
osition. Below this, two lines are drawn which make up two sides of the triangle. ScreenshotLive sample You'll notice the difference between the filled and stroked triangle. This is, as mentioned above, because shapes are automatically closed when a path is filled, but not when they are stroked. If we left out the closePath() for the stroked triangle, only two lines would have been drawn, not a
complete triangle. Arcs To draw arcs or circles, we use the arc() or arcTo() methods. arc(x, y, radius, startAngle, endAngle, anticlockwise) Draws an arc which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction indicated by anticlockwise (defaulting to clockwise). arcTo(x1, y1, x2, y2, radius) Draws an arc with the given control ...
.... For each arc, we start a new path by calling beginPath(). In the code, each of the parameters for the arc is in a variable for clarity, but you wouldn't necessarily do that in real life. The x and y coordinates should be clear enough. radius and startAngle are fixed. The endAngle starts at 180 degrees (half a circle) in the first column and is increased by steps of 90 degrees, culminating in a
complete circle in the last column. The statement for the clockwise parameter results in the first and third row being drawn as clockwise arcs and the second and fourth row as counterclockwise arcs. Finally, the if statement makes the top half stroked arcs and the bottom half filled arcs. Note: This example requires a slightly larger canvas than the others on this page: 150 x 200 pixels. <html> <bo...
... direct visual feedback as to what we're doing. This makes it pretty hard to draw complex shapes. In the following example, we'll be drawing some simple organic shapes, but if you have the time and, most of all, the patience, much more complex shapes can be created. There's nothing very difficult in these examples. In both cases we see a succession of curves being drawn which finally result in a
complete shape. Quadratic Bezier curves This example uses multiple quadratic Bezier curves to render a speech balloon. <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'); // Quadratric curves example ctx...
Document.readyState - Web APIs
the value of this property changes, a readystatechange event fires on the document object. Syntax var string = document.readyState; Values The readyState of a document can be one of following: loading The document is still loading. interactive The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.
complete The document and all sub-resources have finished loading. The state indicates that the load event is about to fire. Examples Different states of readiness switch (document.readyState) { case "loading": // The document is still loading. break; case "interactive": // The document has finished loading. We can now access the DOM elements. // But sub-resources such as images, ...
... { case "loading": // The document is still loading. break; case "interactive": // The document has finished loading. We can now access the DOM elements. // But sub-resources such as images, stylesheets and frames are still loading. var span = document.createElement("span"); span.textContent = "A <span> element."; document.body.appendChild(span); break; case "
complete": // The page is fully loaded. console.log("The first CSS rule is: " + document.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...
...ext); 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 Specification Status Comment ...
Document - Web APIs
come visible or has been hidden. Also available via the onvisibilitychange property. wheel Fired when the user rotates a wheel button on a pointing device (typically a mouse). Also available via the onwheel property. Animation events animationcancel Fired when an animation unexpectedly aborts. Also available via the onanimationcancel property. animationend Fired when an animation has
completed normally. Also available via the onanimationend property. animationiteration Fired when an animation iteration has
completed. Also available via the onanimationiteration property. animationstart Fired when an animation starts. Also available via the onanimationstart property. Clipboard events copy Fired when the user initiates a copy action through the browser's user interface. Als...
...rror property. Keyboard events keydown Fired when a key is pressed. Also available via the onkeydown property. keypress Fired when a key that produces a character value is pressed down. Also available via the onkeypress property. keyup Fired when a key is released. Also available via the onkeyup property. Load & unload events DOMContentLoaded Fired when the document has been
completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. readystatechange Fired when the readyState attribute of a document has changed. Also available via the onreadystatechange property. Pointer events gotpointercapture Fired when when an element captures a pointer using setPointerCapture(). Also available via the ongotpointercapture property. lo...
...h points are moved along the touch surface. Also available via the ontouchmove property touchstart Fired when one or more touch points are placed on the touch surface. Also available via the ontouchstart property Transition events transitioncancel Fired when a CSS transition is canceled. Also available via the ontransitioncancel property. transitionend Fired when a CSS transition has
completed. Also available via the ontransitionend property. transitionrun Fired when a CSS transition is first created. Also available via the ontransitionrun property. transitionstart Fired when a CSS transition has actually started. Also available via the ontransitionstart property. Non-standard extensions Firefox notes Mozilla defines a set of non-standard properties made only for XUL c...
EffectTiming.fill - Web APIs
tion's effects are not visible when its playState is pending with a delay, when its playState is finished, or during its endDelay or delay. In other words, if the animation isn't in its active interval, the affected element is not visible. "forwards" The affected element will continue to be rendered in the state of the final animation framecontinue to be applied to the after the animation has
completed playing, in spite of and during any endDelay or when its playState is finished. "backwards" The animation's effects should be reflected by the element(s) state prior to playing, in spite of and during any delay and pending playState. "both" Combining the effects of both forwards and backwards: The animation's effects should be reflected by the element(s) state prior to playing and retained a...
...and during any endDelay or when its playState is finished. "backwards" The animation's effects should be reflected by the element(s) state prior to playing, in spite of and during any delay and pending playState. "both" Combining the effects of both forwards and backwards: The animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has
completed playing, in spite of and during any endDelay, delay and/or pending or finished playState. "auto" If the animation effect the fill mode is being applied to is a keyframe effect (KeyframeEffect or KeyframeEffectReadOnly), "auto" is equivalent to "none". Otherwise, the result is "both". Examples Here are a few examples. Fill mode: none HTML content The HTML is pretty simple. We have a <div>...
...om its original orientation. var boxRotationTiming = { duration: 2000, iterations: 1, fill: "none" }; The boxRotationTiming object describes how long the animation should take to run, how many times it should run, what state the element should be in before the animation begins and after it ends, and so forth. Here we specify that the animation should take 2000 milliseconds (2 seconds) to
complete, should only run once, and that the fill mode should be "none". As defined above, the "none" fill mode means that the element will be rendered in its natural, unaltered condition anytime the animation isn't actively running. document.getElementById("animateButton").addEventListener("click", event => { document.getElementById("box").animate( boxRotationKeyframes, boxRotationTiming ); ...
FileReader - Web APIs
FileReader.error Read only A DOMException representing the error that occurred while reading the file. FileReader.readyState Read only A number indicating the state of the FileReader. This is one of the following: EMPTY 0 No data has been loaded yet. LOADING 1 Data is currently being loaded. DONE 2 The entire read request has been
completed. FileReader.result Read only The file's contents. This property is only valid after the read operation is
complete, and the format of the data depends on which of the methods was used to initiate the read operation. Event handlers FileReader.onabort A handler for the abort event. This event is triggered each time the reading operation is aborted. FileReader.onerror A handle...
...operation. Event handlers FileReader.onabort A handler for the abort event. This event is triggered each time the reading operation is aborted. FileReader.onerror A handler for the error event. This event is triggered each time the reading operation encounter an error. FileReader.onload A handler for the load event. This event is triggered each time the reading operation is successfully
completed. FileReader.onloadstart A handler for the loadstart event. This event is triggered each time the reading is starting. FileReader.onloadend A handler for 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 Fil...
... Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. abort Fired when a read has been aborted, for example because the program called FileReader.abort(). Also available via the onabort property. error Fired when the read failed due to an error. Also available via the onerror property. load Fired when a read has
completed successfully. Also available via the onload property. loadend Fired when a read has
completed, successfully or not. Also available via the onloadend property. loadstart Fired when a read has started. Also available via the onloadstart property. progress Fired periodically as data is read. Also available via the onprogress property. Specifications Specification Status ...
HTMLFormElement - Web APIs
g reflecting the value of the form's enctype HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms. HTMLFormElement.acceptCharset A DOMString reflecting the value of the form's accept-charset HTML attribute, representing the character encoding that the server accepts. HTMLFormElement.auto
complete A DOMString reflecting the value of the form's auto
complete HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser. HTMLFormElement.noValidate A Boolean reflecting the value of the form's novalidate HTML attribute, indicating whether the form should not be validated. Named inputs are added to their owner form instance as prop...
...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. Deprecated methods HTMLFormElement.requestAuto
complete() Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. The form will receive an event once the user has finished with the interface, the event will either be auto
complete when the fields have been filled or auto
completeerror when there was a problem. Events Listen to these events using addEventListener...
...ml> Submitting forms and uploading files using XMLHttpRequest If you want to know how to serialize and submit a form using the XMLHttpRequest API, please read this paragraph. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement' in that specification. Living Standard The following method has been added: requestAuto
complete(). HTML5The definition of 'HTMLFormElement' in that specification. Recommendation The elements properties returns an HTMLFormControlsCollection instead of a raw HTMLCollection. This is mainly a technical change. The following method has been added: checkValidity(). The following properties have been added: auto
complete, noValidate, and encoding. ...
IDBObjectStore.add() - Web APIs
The add() method of the IDBObjectStore interface 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. 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. For updating ex...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // Make a request to add our newItem object to the object store...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // Make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); objectSt...
IDBRequest - Web APIs
tain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the IDBRequest instance. All asynchronous operations immediately return an IDBRequest instance. ...
...If an error occurs while performing the operation, the exception is made available through the result property and an error event is fired (IDBRequest.onerror). ...
...nd the result is not available, an InvalidStateError exception is thrown. IDBRequest.source Read only The source of the request, such as an IDBIndex or an IDBObjectStore. If no source exists (such as when calling IDBFactory.open), it returns null. IDBRequest.readyState Read only The state of the request. Every request starts in the pending state. The state changes to done when the request
completes successfully or when an error occurs. IDBRequest.transaction Read only The transaction for the request. This property can be null for certain requests, for example those returned from IDBFactory.open unless an upgrade is needed. (You're just connecting to a database, so there is no transaction to return). Methods No methods, but inherits methods from EventTarget. Events Listen to these e...
KeyframeEffect.KeyframeEffect() - Web APIs
The KeyframeEffect() constructor of the Web Animations API returns a new KeyframeEffect object instance, and also allows you to clone an existing keyframe effect object instance. Syntax var keyframes = new KeyframeEffect(element, keyframeSet, keyframeOptions); var keyframes = new KeyframeEffect(sourceKeyFrames); Parameters The first type of constructor (see above) creates a
completely new KeyframeEffect object instance. Its parameters are: element The DOM element to be animated, or null. keyframeSet An keyframe object or null. keyframeOptions Optional Either an integer representing the animation's duration (in milliseconds), or an Object containing one or more of the following: delay Optional The number of milliseconds to delay the start of the animation. Defaults to 0. d...
... 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". duration Optional The number of milliseconds each iteration of the animation takes to
complete. Defaults to 0. Although this is technically optional, keep in mind that your animation will not run if this value is 0. easing Optional The rate of the animation's change over time. Accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The numbe...
....42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The number of milliseconds to delay after the end of an animation. This is primarily of use when sequencing animations based on the end time of another animation. Defaults to 0. fill Optional Dictates whether the animation's effects should be reflected by the element(s) prior to playing ("backwards"), retained after the animation has
completed playing ("forwards"), or both. Defaults to "none". iterationStart Optional Describes at what point in the iteration the animation should start. 0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration. Defaults to 0.0. iterations Optional The number of times the animation s...
Capabilities, constraints, and settings - Web APIs
s 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 requested values had to be adjusted and because platform default values aren't represented. For a
complete representation of the track's current configuration, use getSettings(). In the Media Stream API, both MediaStream and MediaStreamTrack have constrainable properties. Determining if a constraint is supported If you need to know whether or not a given constriant is supported by the user agent, you can find out by calling navigator.mediaDevices.getSupportedConstraints() to get a list of the cons...
...s you experiment with media constraints by editing the source code describing the constraint sets for audio and video tracks. You can then apply those changes and see the result, including both what the stream looks like and what the actual media settings are set to after applying the new constraints. The HTML and CSS for this example are pretty simple, and aren't shown here. You can look at the
complete example by clicking here. HTML content <p>Experiment with media constraints! Edit the constraint sets for the video and audio tracks in the edit boxes on the left, then click the "Apply Constraints" button to try them out. The actual settings the browser selected and is using are shown in the boxes on the right. Below all of that, you'll see the video itself.</p> <p>Click the "Star...
...is called to handle promises which fail, and the log() function appends the error message to a special logging <div> box under the video. function log(msg) { logElement.innerHTML += (msg + "<br>"); } function handleError(reason) { log("Error <code>" + reason.name + "</code> in constraint <code>" + reason.constraint + "</code>: " + reason.message); } Result Here you can see the
complete example in action. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'Constrainable pattern' in that specification. Candidate Recommendation Initial definition. ...
Payment processing concepts - Web APIs
usually 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 valida...
...s 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 validation URL itself. By then delivering this data (or a Promise which resolves to the loaded data) to the payment handler by passing it into
complete(), the payment handler can use the retrieved data and whatever algorithm and other data to support in order to verify that the merchant can use the payment handler. Thus, it's important to note that the user agent never sends a 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 h...
... sends a 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...
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
Example The following example illustrates this property's usage. ...
... Example The following example illustrates this property's usage. ...
... // Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.domInteractive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } ...
RTCPeerConnection: iceconnectionstatechange event - Web APIs
oniceconnectionstatechange One common task performed by the iceconnectionstatechange event listener: to trigger ICE restart when the state changes to failed. See ICE restart in Lifetime of a WebRTC session for further information. Usage notes A successful connection attempt will typically involve the state starting at new, then transitioning through checking, then connected, and finally
completed. However, under certain circumstances, the connected state can be skipped, causing a connection to transition directly from the checking state to
completed. This can happen when only the last checked candidate is successful, and the gathering and end-of-candidates signals both occur before the successful negotiation is
completed. ICE connection state during ICE restarts When an ICE restart is ...
...If ICE restart is initiated while in the transient disconnected state, the state transitions instead to checking, essentially indicating that the negotiation is ignoring the fact that the connection had been temporarily lost. ...
... the negotiation is ignoring the fact that the connection had been temporarily lost. State transitions as negotiation ends When the negotiation process runs out of candidates to check, the ICE connection transitions to one of two states. If no suitable candidates were found, the state transitions to failed. If at least one suitable candidate was successfully identified, the state transitions to
completed. The ICE layer makes this determination upon receiving the end-of-candidates signal, which is provided by caling addIceCandidate() with a candidate whose candidate property is an empty string (""), or by setting the RTCPeerConnection property canTrickleIceCandidates to false. Examples An event handler for this event can be added using the RTCPeerConnection.oniceconnectionstatechange property o...
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. ...
...stination 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. Available options are: preventClose: If this is set to true, the source ReadableStream closing will no longer cause the destination WritableStream to be closed. The method will return a fulfilled promise once this process
completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventAbort: If this is set to true, errors in the source ReadableStream will no longer abort the destination WritableStream. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. preventCancel: If this i...
... will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. signal: If set to an AbortSignal object, ongoing pipe operations can then be aborted via the corresponding AbortController. Return value A Promise that resolves when the piping process has
completed. Exceptions TypeError The writableStream and/or readableStream objects are not a writable stream/readable stream, or one or both of the streams are locked. Examples // Fetch the original image fetch('png-logo.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(body => body.pipeThrough(new PNGTransformStream())) .then(rs => rs.pipeTo(new FinalDestinationStr...
WebRTC connectivity - Web APIs
Lots of info here is good but the organization is a mess since this is sort of a dumping ground right now. Signaling Unfortunately, WebRTC can't create connections without some sort of server in the middle. We call this the signal channel or signaling service. ...
...agent just waits to be told which candidate pair to use. It's important to keep in mind that a single ICE session may result in the controlling agent choosing more than one candidate pair. Each time it does so and shares that information with the controlled agent, the two peers reconfigure their connection to use the new configuration described by the new candidate pair. Once the ICE session is
complete, the configuration that's currently in effect is the final one, unless an ICE reset occurs. At the end of each generation of candidates, an end-of-candidates notification is sent in the form of an RTCIceCandidate whose candidate property is an empty string. This candidate should still be added to the connection using addIceCandidate() method, as usual, in order to deliver that notification to th...
...the remote peer. When there are no more candidates at all to be expected during the current negotiation exchange, an end-of-candidates notification is sent by delivering a RTCIceCandidate whose candidate property is null. This message does not need to be sent to the remote peer. It's a legacy notification of a state which can be detected instead by watching for the iceGatheringState to change to
complete, by watching for the icegatheringstatechange event. When things go wrong During negotiation, there will be times when things just don't work out. For example, when renegotiating a connection--for example, to adapt to changing hardware or network configurations--it's possible that negotiation could reach a dead end, or some form of error might occur that prevents negotiation at all. There may be...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
er of issues with the API and some potential race conditions that needed to be prevented. These issues have since been addressed, letting us simplify our WebRTC negotiation significantly. The perfect negotiation pattern is an example of the ways in which negotiation have improved since the early days of WebRTC. Perfect negotiation concepts Perfect negotiation makes it possible to seamlessly and
completely separate the negotiation process from the rest of your application's logic. Negotiation is an inherently asymmetric operation: one side needs to serve as the "caller" while the other peer is the "callee." The perfect negotiation pattern smooths this difference away by separating that difference out into independent negotiation logic, so that your application doesn't need to care which end of th...
...getting an error and aborting the connection attempt. The old way Consider this onnegotiationneeded event handler: pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(await pc.createOffer()); signaler.send({description: pc.localDescription}); } catch(err) { console.error(err); } }; Because the createOffer() method is asynchronous and takes some time to
complete, there's time in which the remote peer might attempt to send an offer of its own, causing us to leave the stable state and enter the have-remote-offer state, which means we are now waiting for a response to the offer. But once it receives the offer we just sent, so is the remote peer. This leaves both peers in a state in which the connection attempt cannot be
completed. Perfect negotiation with ...
...o know when it needs to throw away a received offer if it's currently waiting for a reply to an offer it's already sent. The code checks to see if the message is an offer, and if so, if the local signaling state isn't stable. If it's not stable, and the local peer is the polite one, we need to trigger rollback so we can replace the outgoing offer with the new incoming one. and these must both be
completed before we can proceed with handling the received offer. Since there isn't a single "roll back and use this offer instead", performing this change on the polite peer requires two steps, executed in the context of Promise.all(), which is used to ensure that both statements execute
completely before continuing to handle the received offer. The first statement triggers rollback and the second sets ...
Window - Web APIs
n resized. Also available via the onresize property. storage Fired when a storage area (localStorage or sessionStorage) has been modified in the context of another document. Also available via the onstorage property. Animation events animationcancel Fired when an animation unexpectedly aborts. Also available via the onanimationcancel property. animationend Fired when an animation has
completed normally. Also available via the onanimationend property. animationiteration Fired when an animation iteration has
completed. Also available via the onanimationiteration property. animationstart Fired when an animation starts. Also available via the onanimationstart property. Clipboard events clipboardchange Fired when the system clipboard content changes. copy Fired when the user...
... Also available using the onpageshow event handler property. popstate Fired when the active history entry changes. Also available using the onpopstate event handler property. Load & unload events beforeunload Fired when the window, the document and its resources are about to be unloaded. Also available via the onbeforeunload property. DOMContentLoaded Fired when the document has been
completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. load Fired when the whole page has loaded, including all dependent resources such as stylesheets images. Also available via the onload property. unload Fired when the document or a child resource is being unloaded. Also available via the onunload property. Manifest events appinstalled Fired ...
... event handler property. unhandledrejection Sent when a JavaScript Promise is rejected but there is no handler in place to catch the rejection. Also available using the onunhandledrejection event handler property. Transition events transitioncancel Fired when a CSS transition is canceled. Also available via the ontransitioncancel property. transitionend Fired when a CSS transition has
completed. Also available via the ontransitionend property. transitionrun Fired when a CSS transition is first created. Also available via the ontransitionrun property. transitionstart Fired when a CSS transition has actually started. Also available via the ontransitionstart property. Interfaces See DOM Reference. ...
ARIA: application role - Accessibility
v element and all of its descendants to be treated like they are part of a desktop application. Description The application role indicates to assistive technologies that this part of the web content contains elements that do not conform to any other known HTML element or WAI-ARIA widget. Any sort of special interpretation of HTML structures and widgets should be suspended, and control should be
completely handed over to the browser and web application to handle mouse, keyboard, or touch interaction. In this mode, the web author is
completely responsible for handling any and all keyboard input, focus management, and other interactions and cannot assume assistive technologies would do any processing on their end. If the web application encompassed by the application role contains parts that shou...
...he name of the application or purpose of the widget that is being exposed. aria-describedby Used to indicate the idref of an element that contains additional instructions for navigating or operating this element. aria-roledescription Used to give the application a more descriptive role text for screen readers to speak. This should be localized. Keyboard interactions Keyboard interaction is
completely under the web author's control and can be anything associated with the particular widget being implemented. In a slides application, for example, a widget could be created that uses the arrow keys to position elements on the slide, and uses audio feedback via an ARIA live region to communicate the position and overlap status with other objects. Focus is being managed via aria-activedescendant. ...
...ss Used to handle keyboard input and control the focus Click, Touch Handle as appropriate for your widget as well Changing attribute values aria-activedescendant is used to manage the focus inside the application container. Set in response to keyboard or other application events that change focus or point of interaction. The application role does not have a related HTML widget and thus is
completely free form. The author of the application must take full responsibility for not letting users get stuck in a focus limbo or trap focus inside something the user cannot exit of. All aspects of interaction, including returning to the regular web content on other parts of the page, must be handled. Use wisely, and cautiously! Examples Some prominent web applications that use the application role...
<color> - CSS: Cascading Style Sheets
color, such as red, blue, black, or lightseagreen. Although the names more or less describes their respective colors, they are essentially artificial, without a strict rationale behind the names used. There are a few caveats to consider when using color keywords: HTML only recognizes the 16 basic color keywords found in CSS1, using a specific algorithm to convert unrecognized values (often to
completely different colors). The other color keywords should only be used in CSS and SVG. Unlike HTML, CSS will
completely ignore unknown keywords. The color keywords all represent plain, solid colors, without transparency. Several keywords are aliases for each other: aqua / cyan fuchsia / magenta darkgray / darkgrey darkslategray / darkslategrey dimgray / dimgrey lightgray / ligh...
... tomato #ff6347 turquoise #40e0d0 violet #ee82ee wheat #f5deb3 whitesmoke #f5f5f5 yellowgreen #9acd32 CSS Color Module Level 4 rebeccapurple #663399 transparent keyword The transparent keyword represents a fully transparent color. This makes the background behind the colored item
completely visible. Technically, transparent is a shortcut for rgba(0,0,0,0). Compatibility note: To prevent unexpected behavior, such as in a <gradient>, the current CSS spec states that transparent should be calculated in the alpha-premultiplied color space. However, be aware that older browsers may treat it as black with an alpha value of 0. Historical note: transparent wasn't a true color in CSS ...
... 4. When written as a unitless <number>, it is interpreted as degrees, as specified in CSS Color Module Level 3. By definition, red=0deg=360deg, with the other colors spread around the circle, so green=120deg, blue=240deg, etc. As an <angle>, it implicitly wraps around such that -120deg=240deg, 480deg=120deg, -1turn=1turn, etc. S (saturation) and L (lightness) are percentages. 100% saturation is
completely saturated, while 0% is
completely unsaturated (gray). 100% lightness is white, 0% lightness is black, and 50% lightness is "normal." A (alpha) can be a <number> between 0 and 1, or a <percentage>, where the number 1 corresponds to 100% (full opacity). Functional notation: hsl[a](H S L[ / A]) CSS Colors Level 4 adds support for space-separated values in the functional notation. System Color...
Adding captions and subtitles to HTML5 video - Developer guides
owser Compatibility Browser support for WebVTT and the <track> element is fairly good, although some browsers differ slightly in their implementation. Internet Explorer Internet Explorer 10+ subtitles are enabled by default, and the default controls contain a button and a menu that offers the same functionality as the menu we just built. The default attribute is also supported. Note: IE will
completely ignore WebVTT files unless you define the MIME type. This can easily be done by adding an .htaccess file to an appropriate directory that contains AddType text/vtt .vtt. Safari Safari 6.1+ has similar support to Internet Explorer 10+, displaying a menu with the different available options, with the addition of an "Auto" option, which allows the browser to choose. Chrome and Opera These bro...
... the browser to choose. Chrome and Opera These browsers have similar implementations again: subtitles are enabled by default and the default control set contains a 'cc' button that turns subtitles on and off. Chrome and Opera ignore the default attribute on the <track> element and will instead try to match the browser's language to the subtitle's language. ...
...layer implements subtitles in both SRT and WebVTT file formats. playr This small plugin implements subtitles, captions, and chapters as well as both WebVTT and SRT file formats. Flowplayer HTML5 player supporting WebVTT. jwplayer This video player is very extensive and does a lot more than simply support video captions. It supports the WebVTT, SRT and DFXP formats. MediaElement.js Another
complete video player that also support video captions, albeit only in SRT format. LeanBack Player Yet another video player that supports WebVTT captions as well as providing other standard player functionality. SublimeVideo This player also supports captions through WebVTT and SRT files. Video.js Supports WebVTT video subtitles. Radiant Media Player Supports multi-languages WebVTT closed captions...
Media events - Developer guides
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. loadedmetadata The media's metadata has finished loading; all attributes now contain as much useful information as they're going to. loadstart Sent when loa...
...tarts, and after seeked, if it was playing before seeking. progress Sent periodically to inform interested parties of progress downloading the media. Information about the current amount of the media that has been downloaded is available in the media element's buffered attribute. ratechange Sent when the playback speed changes. seeked Sent when a seek operation
completes. seeking Sent when a seek operation begins. stalled Sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend Sent when loading of the media is suspended; this may happen either because the download has
completed or because it has been paused for any other reason. timeupdate The time indicated by the ...
...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 initiates a seek operation to the 10-second mark in the media. This causes a seeking event to be sent when the operation begins, then a seeked event to be dispatched when the seek is
completed. In other words, this example seeks t...
Overview of events and handlers - Developer guides
ct which will 'emit' that event. The pattern is implemented by defining a JavaScript function which takes as an argument the data structure which was agreed upon, and registering the function using the name String with the object which will emit the event. The function is said to be a 'listener' or a 'handler' with both names used interchangeably. This pattern can easily be followed using
completely custom code, as explained in the article on custom events. The pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity. Modern web browsers follow the event pattern using a standardized approach. Browsers use as the data structure for the properties of the event, an object derived from the EventPrototype object. Browsers use as...
... orientation, the document object, including the loading, modification, user interaction, and unloading of the page, the objects in the DOM (document object model) tree including user interactions or modifications, the XMLHttpRequest objects used for network requests, and the media objects such as audio and video, when the media stream players change state. although this list is currently in
complete. Some notable events are: Note: This list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. This will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this Stack Overflow question. the global object window emits an event called 'load' when the...
... the mouse button while the mouse pointer is on top of the DOM node in the HTML page. The Event object hierarchy The web browser defines many events of different kinds. Each definition includes, as the data structure passed to the handler function, an object which inherits from the EventPrototype object. A partial diagram of the class hierarchy of event objects is: Note: This diagram is in
complete. The Web API Documentation contains a page defining the Event object which also includes the known DOM event subclasses of the Event object. Documents Three sources on the MDN (Mozilla Developer Network) web site are particularly useful for programmers wanting to work with events: this Event Guide which is part of the Web Developers' Guide, the Event Reference, the Web API documentatio...
<input type="checkbox"> - HTML: Hypertext Markup Language
InputElement's checked IDL attribute is updated.) Note: Unlike other input controls, a checkboxes value is only included in the submitted data if the checkbox is currently checked. If it is, then the value of the checkbox's value attribute is reported as the input's value. Unlike other browsers, Firefox by default persists the dynamic checked state of an <input> across page loads. Use the auto
complete attribute to control this feature. indeterminate If the indeterminate attribute is present on the <input> element defining a checkbox, the checkbox's value is neither true nor false, but is instead indeterminate, meaning that it's state cannot be determined or stated in pure binary terms. This may happen, for instance, if the state of the checkbox depends on multiple other checkboxes, and those...
...ault. This is demonstrated in the section Value above. Using checkbox inputs We already covered the most basic use of checkboxes above. Let's now look at the other common checkbox-related features and techniques you'll need. Handling multiple checkboxes The example we saw above only contained one checkbox; in real-world situations you'll be likely to encounter multiple checkboxes. If they are
completely unrelated, then you can just deal with them all separately, as shown above. However, if they're all related, things are not quite so simple. For example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the Examples section). <fieldset> <legend>Choose your interests</legend> <div> <input type="checkbox" id="codin...
...cks the total number of checked ingredients: If none are checked, the recipe name's checkbox is set to unchecked. If one or two are checked, the recipe name's checkbox is set to indeterminate. If all 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. var overall = document.querySelector('input[id="EnchTbl"]'); var ingredients = document.querySelectorAll('ul input'); overall.addEventListener('click', function(e) { e.preventDefault(); }); for(var i = 0; i < ingredients.length; i++) { ingredients[i].addEventListener('click', updateDisplay); } function updateDisplay() { var checkedCount = 0; for(var i = 0; i < i...
<input type="text"> - HTML: Hypertext Markup Language
xt fields. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Value A DOMString representing the text contained in the text field. Events change and input Supported Common Attributes auto
complete, list, maxlength, minlength, pattern, placeholder, readonly, required and size IDL attributes list, value Methods select(), setRangeText() and setSelectionRange(). Value The value attribute is a DOMString that contains the current value of the text entered into the text field. You can retrieve this using the value property in JavaScript. let theText = myTextInput.
...nts are in place for the input (see Validation for more details), the value may be an empty string (""). ...
...ype, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored
completely. Tip: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See Specifying a pattern for further details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is e...
Global attributes - HTML: Hypertext Markup Language
den>...</foo>, even though <foo> is not a valid HTML element. In addition to the basic HTML global attributes, the following global attributes also exist: xml:lang and xml:base -- these are inherited from the XHTML specifications and deprecated, but kept for compatibility purposes. The multiple aria-* attributes, used for improving accessibility. ...
...ven though <foo> is not a valid HTML element. In addition to the basic HTML global attributes, the following global attributes also exist: xml:lang and xml:base -- these are inherited from the XHTML specifications and deprecated, but kept for compatibility purposes. The multiple aria-* attributes, used for improving accessibility. ...
...be moved to this new location. link, will create a link to the dragged data. exportparts Used to transitively export shadow parts from a nested shadow tree into a containing light tree. hidden A Boolean attribute indicates that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been
completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown. id Defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). inputmode Provides a hint to browsers as to the type of virtual keyboard c...
MIME types (IANA media types) - HTTP
A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) is a standard that indicates the nature and format of a document, file, or assortment of bytes. It is defined and standardized in IETF's RFC 6838. The Internet Assigned Numbers Authority (IANA) is responsible for all official MIME types, and you can find the most up-to-date and
complete list at their Media Types page. Important: Browsers use the MIME type, not the file extension, to determine how to process a URL, so it's important that web servers send the correct MIME type in the response's Content-Type header. If this is not correctly configured, browsers are likely to misinterpret the contents of files and sites will not work correctly, and downloaded files may be mishandled. Structure of a MIME type The s...
...upport. As for MIME types of audio or video files, they typically specify the container format (file type). The optional codecs parameter can be added to the MIME type to further specify which codecs to use and what options were used to encode the media, such as codec profile, level, or other such information. The most commonly used MIME types used for web content are listed below. This isn't a
complete list of all the types that may be available, however. See the media container formats guide for that. MIME type Audio or video type audio/wave audio/wav audio/x-wav audio/x-pn-wav An audio file in the WAVE container format. The PCM audio codec (WAVE codec "1") is often supported, but other codecs have limited support (if any). audio/webm An aud...
...container format. Theora is the usual video codec used within it; Vorbis is the usual audio codec, although Opus is becoming more common. application/ogg An audio or video file using the Ogg container format. Theora is the usual video codec used within it; Vorbis is the usual audio codec. multipart/form-data The multipart/form-data type can be used when sending the values of a
completed HTML Form from browser to server. As a multipart document format, it consists of different parts, delimited by a boundary (a string starting with a double dash --). Each part is its own entity with its own HTTP headers, Content-Disposition, and Content-Type for file uploading fields. Content-Type: multipart/form-data; boundary=aBoundaryString (other headers associated with the multipart docume...
Concurrency model and the event loop - JavaScript
s 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-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime...
...uding the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread. A downside of this model is that if a message takes too long to
complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages. Adding messages In web browsers, messages are added anytime an event occurs and there is an event listener attac...
...e execution depends on the number of waiting tasks in the queue. In the example below, the message ''this is just a message'' will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time). Basically, the setTimeout needs to wait for all the code for queued messages to
complete even though you specified a particular time limit for your setTimeout. (function() { console.log('this is the start'); setTimeout(function cb() { console.log('Callback 1: this is a msg from call back'); }); // has a default time value of 0 console.log('this is just a message'); setTimeout(function cb1() { console.log('Callback 2: this is a msg from call back'); }, 0); ...
Symbol - JavaScript
Every symbol value returned from Symbol() is unique. ...
...al symbol registry. Finding symbol properties on objects The method Object.getOwnPropertySymbols() returns an array of symbols and lets you find symbol properties on a given object. Note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object. Constructor Symbol() Creates a new Symbol object. It is in
complete as a constructor because it does not support the syntax "new Symbol()". Static properties Symbol.asyncIterator A method that returns the default AsyncIterator for an object. Used by for await...of. Symbol.hasInstance A method determining if a constructor object recognizes an object as its instance. Used by instanceof. Symbol.isConcatSpreadable A Boolean value indicating if an object sho...
...merable in for...in iterations. In addition, Object.getOwnPropertyNames() will not return symbol object properties, however, you can use Object.getOwnPropertySymbols() to get these. let obj = {} obj[Symbol('a')] = 'a' obj[Symbol.for('b')] = 'b' obj['c'] = 'c' obj.d = 'd' for (let i in obj) { console.log(i) // logs "c" and "d" } Symbols and JSON.stringify() Symbol-keyed properties will be
completely ignored when using JSON.stringify(): JSON.stringify({[Symbol('foo')]: 'foo'}) // '{}' For more details, see JSON.stringify(). Symbol wrapper objects as property keys When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol: let sym = Symbol('foo') let obj = {[sym]: 1} obj[sym] // 1 obj[Object(sym)] // still 1 Specification...
Critical rendering path - Web Performance
it finds links to external resources, be they stylesheets, scripts, or embedded image references. Some requests are blocking, which means the parsing of the rest of the HTML is halted until the imported asset is handled. The browser continues to parse the HTML making requests and building the DOM, until it gets to the end, at which point it constructs the CSS object model. With the DOM and CSSOM
complete, the browser builds the render tree, computing the styles for all the visible content. After the render tree is
complete, layout occurs, defining the location and size of all the render tree elements. Once
complete, the page is rendered, or 'painted' on the screen. Document Object Model DOM construction is incremental. The HTML response turns into tokens which turns into nodes which turn into t...
...he CSSOM contains all the styles of the page; information on how to style that DOM. CSSOM is similar to the DOM, but different. While the DOM construction is incremental, CSSOM is not. CSS is render blocking: the browser blocks page rendering until it receives and processes all of the CSS. CSS is render blocking because rules can be overwritten, so the content can't be rendered until the CSSOM is
complete. CSS has its own set of rules for identifying valid tokens. Remember the C in CSS stands for 'Cascade'. CSS rules cascade down. As the parser converts tokens to nodes, with descendants of nodes inheriting styles. The incremental processing features don't apply to CSS like they do with HTML, because subsequent rules may override previous ones. The CSS object model gets built as the CSS is parsed,...
...kens. Remember the C in CSS stands for 'Cascade'. CSS rules cascade down. As the parser converts tokens to nodes, with descendants of nodes inheriting styles. The incremental processing features don't apply to CSS like they do with HTML, because subsequent rules may override previous ones. The CSS object model gets built as the CSS is parsed, but can't be used to build the render tree until it is
completely parsed because styles that are going to be overwritten with later parsing should not be rendered to the screen. In terms of selector performance, less specific selectors are faster than more specific ones. For example, .foo {} is faster than .bar .foo {} because when the browser finds .foo, in the second scenario, it has to walk up the DOM to check if .foo has an ancestor .bar. The more specif...
Understanding latency - Web Performance
G 250 Kbps 50 Kbps 300 Good 2G 450 Kbps 150 Kbps 150 Regular 3G 750 Kbps 250 Kbps 100 Good 3G 1.5 Mbps 750 Kbps 40 Regular 4G/LTE 4 Mbps 3 Mbps 20 DSL 2 Mbps 1 Mbps 5 Wi-Fi 30 Mbps 15 Mbps 2 Network Timings Also, on the network tab, you can see how long each request took to
complete. We can look at how long a 267.5Kb SVG image asset took to download. When a request is in a queue, waiting for a network connection it is considered blocked. Blocking happens when there are too many simultaneous connections made to a single server over HTTP. If all connections are in use, the browser can't download more resources until a connection is released, meaning those requests and resou...
...ltaneous connections made to a single server over HTTP. If all connections are in use, the browser can't download more resources until a connection is released, meaning those requests and resources are blocked. DNS resolution is the time it took to do the DNS lookup. The greater the number of hostnames, the more DNS lookups need to be done. Connecting is the time it takes for a TCP handshake to
complete. Like DNS, the greater the number of server connections needed, the more time is spend creating server connections. The TLS handshake is how long it took to set up a secure connection. While a TLS handshake does take longer to connect than an insecure connection, the additional time needed for a secure connection is worth it. Sending is the time taken to send the HTTP request to the server. Wa...
...eeded, the more time is spend creating server connections. The TLS handshake is how long it took to set up a secure connection. While a TLS handshake does take longer to connect than an insecure connection, the additional time needed for a secure connection is worth it. Sending is the time taken to send the HTTP request to the server. Waiting is disk latency, the time it took for the server to
complete its response. Disk latency used to be the main area of performance concern. However server performance has improved as computer memory, or CPU, has improved. Depending on the complexity of what is needed from the server, this can still be an issue. Receiving is the time it takes to download the asset. The receiving time is determined by a combination of the network capacity and the asset file si...
XUL Migration Guide - Archive of obsolete content
y, the main options are: the SDK includes modules that implement some basic user interface components including buttons, dialogs, and context menu items. there is a collection of community-developed modules that includes various user interface components. by using the SDK's low-level APIs you can directly modify the browser chrome. XUL Windows XUL windows are used to define
completely new windows to host user interface elements specific to the add-on. The SDK generally expects you to specify your user interface using HTML, not XUL. However, you can include a chrome.manifest file in your add-on and it will be included in the generated XPI. my-addon/ chrome/ content/ locale/ skin/ chrome.manifest data/ lib/ package.json There are...
... add-on needs correspondingly more rigorous security design and review. Using XPCOM This example uses the action button API, which is only available from Firefox 29 onwards. Finally, if none of the above techniques work for you, you can use the require("chrome") statement to get direct access to the Components object, which you can then use to load and access any XPCOM object. The following
complete add-on uses nsIPromptService to display an alert dialog: var {Cc, Ci} = require("chrome"); var promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"]. getService(Ci.nsIPromptService); require("sdk/ui/button/action").ActionButton({ id: "xpcom-example", label: "Hello from XPCOM", icon: "./icon-16.png", onClick: function() { promptSvc.alert(null, "My Add-on", "Hello...
indexed-db - Archive of obsolete content
ntation here, but refer you to the IndexedDB API documentation for all the details. The database created will be unique and private per add-on, and is not linked to any website database. The module cannot be used to interact with a given website 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/i...
...; 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.on
complete = 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...
panel - Archive of obsolete content
panel content You can't directly access your panel's content from your main add-on code. To access the panel's content, you need to load a script into the panel. In the SDK these scripts are called "content scripts" because they're explicitly used for 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 a panel using the contentScript or contentScriptFile options to the Panel() constructor. You can communicate with the script using either the postMessage() API or (preferably, usually) the port API. For example, here's an ad...
...hough panels can host HTML documents, they are not implemented as browser tabs, so many things that work in normal web pages do not work inside panels: Prior to Firefox 33, you don't get a context menu. From Firefox 33 you can enable a context menu by passing contextMenu: true to the panel's constructor. The HTML <select> element doesn't work. The HTML <datalist> element doesn't give you auto
complete suggestions (bug 918600). You can't embed Flash (bug 952578). You can't provide tooltips using title attributes (bug 918600). Security warning pages (the "This Connection is Untrusted" warning) does not work, so panels which trigger it will be broken (bug 1031554). Mouse button shortcuts, such as using the middle button to open a link in a new page, don't work. Scrolling using keyboard doesn...
places/bookmarks - Archive of obsolete content
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, other add-ons, or the user. Examples Creating a new bookmark let { Bookmark, save } = require("sdk/places/bookmarks"); // Create a new bookmark instance, unsaved let bookmar...
...ents Bookmark|Group|Separator : For the save function, this is the saved, latest snapshot of the bookmark item. For search, this is a snapshot of a bookmark returned from the search query. Bookmark|Group|Separator|object : Only in save data events. The initial instance of the item that was used for the save request. error The error event is emitted whenever a bookmark item's save could not be
completed. Arguments string : A string indicating the error that occurred. Bookmark|Group|Separator|object : Only in save error events. The initial instance of the item that was used for the save request. end The end event is called when all bookmark items and dependencies have been saved, or an aggregate of all items returned from a search query. Arguments array : The array is an ordered list of t...
places/history - Archive of obsolete content
t data, // sorted by visit date, with all entries from more than a week ago // that contain 'ruby', *in addition to* entries from this last week // that contain 'javascript' }); Globals Functions search(queries, options) Queries can be performed on history entries by passing in one or more query options. Each query option can take several properties, which are AND'd together to make one
complete query. For additional queries within the query, passing more query options in will OR the total results. An options object may be specified to determine overall settings, like sorting and how many objects should be returned. Parameters queries : object|array An Object representing a query, or an Array of Objects representing queries. Each query object can take several properties, which are que...
... found, whereas end events are emitted as an aggregate of an entire search, passing in an array of all results into the handler. Events data The data event is emitted for every item returned from a search. Arguments Object : This is an object representing a history entry. Contains url, time, accessCount and title of the entry. error The error event is emitted whenever a search could not be
completed. Arguments string : A string indicating the error that occurred. end The end event is called when all search results have returned. Arguments array : The value passed into the handler is an array of all entries found in the history search. Each entry is an object containing the properties url, time, accessCount and title. ...
ui/frame - Archive of obsolete content
ostMessage("pong", e.origin); } Arguments event : This contains two properties: source, which defines a postMessage() function which you can use to send messages back to this particular frame instance. origin, which you can use as the targetOrigin argument to postMessage() if you want to communicate with this particular frame instance. ...
...defines a postMessage() function which you can use to send messages back to this particular frame instance. origin, which you can use as the targetOrigin argument to postMessage() if you want to communicate with this particular frame instance. load This event is emitted while a frame instance is
completely loaded. It's the equivalent of the point where the frame's document.readyState becomes "
complete": var { Frame } = require("sdk/ui/frame"); var frame = new Frame({ url: "./frame.html" }); frame.on("load", ping); function ping(e) { e.source.postMessage("ping", "*"); } Arguments event : This contains two properties: source, which defines a postMessage() function which you can use to send messages back to this particular frame instance. origin, which you can use as the targetOrigi...
ui/sidebar - Archive of obsolete content
e first message goes from the main add-on code to the sidebar script. Using attach The attach event is triggered whenever the DOM for a new sidebar instance is loaded and its scripts are attached. The sidebar script may not be initialized yet, so you can't reliably send messages to the sidebar script right away: however, you can start listening to messages from the script. ...
...-on: sidebar script got the reply Using ready The ready event is emitted when the DOM for the sidebar's content is ready. It is equivalent to the DOMContentLoaded event. At this point the sidebar script is initialized, so you can send messages to the sidebar script and be confident that they will not be lost. Listen to this event if your add-on initiates the conversation. ...
Displaying annotations - Archive of obsolete content
the matcher searches the DOM for elements that match annotations. If it finds any it binds functions to that element's mouseenter and mouseleave events to send messages to the main module, 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. ...
...a.url('jquery-1.4.2.min.js'), data.url('annotation/annotation.js')], onShow: function() { this.postMessage(this.content); } }); Execute cfx run one last time. Activate the annotator and enter an annotation. You should see a yellow border around the item you annotated: When you move your mouse over the item, the annotation should appear: Obviously this add-on isn't
complete yet. It could do with more beautiful styling, it certainly needs a way to delete annotations, it should deal with OverQuota more reliably, and the matcher could be made to match more reliably. But we hope this gives you an idea of the things that are possible with the modules in the SDK. ...
Creating Reusable Modules - Archive of obsolete content
MD5); // this tells updateFromStream to read the entire file const PR_UINT32_MAX = 0xffffffff; ch.updateFromStream(istream, PR_UINT32_MAX); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string. ...
... 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 with returned nsILocalFile... } return path; } exports.promptForFile = promptForFile; md5.js Next, create another file in "lib", called "md5.js". ...
Downloading Files - Archive of obsolete content
nd only if, the URL is not // related to a window, null should be used instead. ...
...ils.privacyContextFromWindow(aURLSourceWindow); var progressElement = document.getElementById("progress_element"); persist.progressListener = { onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { var percent
Complete = Math.round((aCurTotalProgress / aMaxTotalProgress) * 100); progressElement.textContent = percent
Complete +"%"; }, onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { // do something } } persist.saveURI(obj_URI, null, null, null, "", targetFile, privacy); Downloading files that require credentials Before calling nsIWebBrowserPersist.saveURI(), you need to set the progressListener property of the nsIWebBrowserPersist instance to an object that implements nsIAuthPrompt.
HTML to DOM - Archive of obsolete content
>. The <div> is returned, and it is never actually appended to the current page. The returned <body> object is of type Element Here is a sample that counts the number of paragraphs in a string: var DOMPars = HTMLParser('<p>foo</p><p>bar</p>'); alert(DOMPars.getElementsByTagName('p').length); If HTMLParser() returns the element name html (instead of body), you have all document object with its
complete functions list, therefore you can retrieve info within div tag like this: var DOMPars = HTMLParser("<div id='userInfo'>John was a mediocre programmer, but people liked him <strong>anyway</strong>.</div>"); alert(DOMPars.getElementById('userInfo').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...
...retrieve info within div tag like this: var DOMPars = HTMLParser("<div id='userInfo'>John was a mediocre programmer, but people liked him <strong>anyway</strong>.</div>"); alert(DOMPars.getElementById('userInfo').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. For that matter, we're going to load our HTML document first: var request = XMLHttpRequest(); request.open("GET", "http://example.org/file.html", false); request.send(null); our next step is to create the Document object that will represent the DOM into which we'll insert our newly-retrieve...
Communication between HTML and your extension - Archive of obsolete content
What I wanted to do was have an extension "look" for something on an HTML page and if it found that something perform some operation on the found thing and then update the status bar with the results of the operation. ...
...t is on the page. What I tried My first attempt was trying to create an XBL component. From what I gather, XBL components are more designed for creating custom components and their specific component behavior rather than trying to impose some kind of messaging on existing components. Next I started investigating events, there are only a handful of events and the W3C documentation is pretty
complete. The basic problem with the event model is probably due to what I was trying to do. In my HTML I have an input element in a form. I set the onBlur action to a little javascript function that performed a standard AJAX request to get a result. The onreadystatechange was set to another little javascript function that would update a specific element on the HTML page with the result. The result of th...
Extension Versioning, Update and Compatibility - Archive of obsolete content
E% in your updateInfoURL if you want to have locale information included in the URL -- this allows you to customize the text based on the user's locale. You may also use the other substitution strings supported by updateURL, although those may be less useful. Formatting Prior to Firefox 4 Prior to Firefox 4 you could only use the following tags, any other tags have themselves and their contents
completely stripped: h1, h2 and h3 for general headings p for paragraphs ul and ol for lists. Within lists use the usual li tag for each list item. Within h1, h2, h3, p and li tags you may use: b or strong for bolder text i or em for italicized text Formatting in Firefox 4 and later From Firefox 4 the restrictions are relaxed somewhat. The following tags are interpreted normally: h1, h2 ...
...Firefox 4 and later From Firefox 4 the restrictions are relaxed somewhat. The following tags are interpreted normally: h1, h2 and h3 for general headings p, div, pre and blockquote for block formatting ul, ol, li, dl, dt and dd for lists b, i, em, strong, u, q, sub, sup and code for text formatting br and hr for line breaking The head, style and script tags and any of their contents are
completely stripped. Other tags aren't included in the result but do have their contents displayed, so the following snippet: <span><q>Text</q></span> Would be rendered exactly the same as: <q>Text</q> Sample File <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="en-US" dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> <h2>My Ex...
Install Manifests - Archive of obsolete content
ed, when the extension is selected in the Extensions list, the Options button is enabled and will show this. <em:optionsURL>chrome://myext/content/options.xul</em:optionsURL> Gecko 7 note In Firefox 7 you can also simply include your options XUL as a file named options.xul, in the base directory of the add-on. skinnable A true or false value property that tells the application whether the (
complete) theme can be skinned by lightweight themes/personas: Examples <em:skinnable>true</em:skinnable> strictCompatibility A Boolean value indicating if the add-on should be enabled when the version of the application is greater than its max version. By default, the value of this property is false meaning that the compatibility checking will not be performed against the max version. <em:strictCom...
...vailable. When not included, the add-on manager will still check for updates on AMO, using the ID of the extension. Note: It is strongly recommended that the updateURL be an HTTPS (secure) link. Non-secure update URLs can be hijacked by a malicious update.rdf file, enabling malware to infiltrate the user's computer. Alternatively, you could host your extension on AMO and leave out the updateURL
completely. This provides secure updates automatically. For security reasons, Gecko 1.9 applications require that if you specify an updateURL, it must be an HTTPS URL, or you must include an updateKey. Your server must send this file as text/rdf, text/xml or application/rdf+xml or the update checker may not work. The add-on manager will substitute the following values into this URL in case you wish to...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
<< Previous This document was authored by Taro (btm) Matsuzawa and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Matsuzawa-san is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008.) This chapter discusses tools to assist in developing extensions. Tools for extension developers FIXME: Are we sure we'll talking about Venkman since it's not well maintained FIXME: We maybe should talk about Firebug and Chromebug FIXME: and what about Console 2 and Docked-JS Console? Venkman, the JavaScript debugger Venkman is a full-fledged JavaScript debugger that runs inside Firefox. ...
...wnload gonzui-win32-1.2.2.zip and expand it into a suitable directory. Download the Firefox source code and place it in the same directory as gonzui (simply because it's easier to specify a file that's in the same directory). Open a command prompt and navigate to the directory containing gonzui. The next command will import the source code: gonzui-import.exe mozilla Once the import process is
complete, type the following command to launch the gonzui server: gonzui-server.exe Now you can access gonzui from your web browser by typing the following into your location bar : http://localhost:46984 This lets you browse all packages, click on links to traverse them, and take traversed-link locations as search starting points (Figure A). FIXME: Figure A: gonzui 1 - http://quicknote.mozdev.org ...
Chapter 1: Introduction to Extensions - Archive of obsolete content
<< PreviousNext >> Note: If you want contribute to this document please following guidelines from the Contribute page. This document was authored by Hideyuki Emura and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Emura-san is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008.) Introduction If you're reading this guide, you've probably used Firefox before. Perhaps the first time you looked at Firefox, you may have been surprised to see that it has a much simpler structure than other full-featured browsers, such as Opera or Safari. ...
... Offers detailed tab-related settings. PrefBar Gives access to numerous preferences from the toolbar. NoScript Enables and disables JavaScript execution on a site-by-site basis. Web application integration extensions FIXME: Update this. The use the APIs of certain web applications to provide certain pieces of information. New feature extensions FIXME: Update this. Extensions can add
completely new features to Firefox. This class of extension requires a greater level of knowledge and programming ability. GreaseMonkey UserChrome.js Both of these provide an environment for running user scripts (JavaScript) in Firefox itself, where the scripts can target specific websites. Adblock Plus Blocks the display of unwanted advertisements on web pages. All-in-One Gestures Adds mouse-...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
necessarily true in the future or even now. This article is aimed at presenting alternatives to common eval uses in add-ons and other Javascript 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 eva...
...rBracket = functionBody.indexOf("{") + 1; functionBody = functionBody.substring(0, afterBracket) + "myAddon.onAddTab(aURI);" + functionBody.substring(afterBracket); eval("gBrowser.addTab = " + functionBody); Of course, this not only looks messy, but can be quite error prone. Other extensions might do something similar, trying to hook the same functions, but a little different, ending up with
completely broken code. The code is hard to read and by that hard to maintain and review. (The example is a quite simple one. In real life such code is often far more complex) The code might break in the future, as certain assumptions might not longer be true, for example the function signature may change (aURI from above becomes aURL) or the function is replaced by a short-hand/arrow function: functi...
Handling Preferences - Archive of obsolete content
"homepage", it will filter all the preferences and display only the ones which include the word "homepage" in its name or value. Right-clicking on the list reveals several options that allow you to modify preference values and add new ones. Preferences with non-default values are highlighted in bold. All changes done in about:config are saved to the prefs.js file. The list in about:config is not
complete. Some Firefox preferences have no default value, so they are left out unless you add them manually. An extensive specification of Firefox preferences can be seen in this page. You don't need to know them by heart; if doing task X requires some preference, then it's better to look for an explanation on how to do X rather than diving into the preferences list and see if you can find the preference ...
... at the top of the window will need icons, and just like with toolbar buttons there are subtle differences between operating systems. The prefwindow allows you to use the preferences and preference elements, which facilitate preference handling. The preferences element is just a container, and you should have one per window, or one per prefpane if you have those. The element and its children are
completely invisible, and their purpose is to list the preferences to be used in the window/pane. <preferences> <preference id="xulschoolhello-message-count-pref" name="extensions.xulschoolhello.message.count" type="int" /> <!-- More preference elements. --> </preferences> After you define the preferences you need, you associate them with the form elements in your window or pane using the p...
CSS3 - Archive of obsolete content
is now an independent part of the language and moves towards standardization at its own pace. While some modules are already W3C Recommendations, other still are early Working Drafts. New modules are also added when new needs are identified. Formally, there is no CSS3 standard per se . Each module being standardized independently, the standard CSS consists of CSS2.1 amended and extended by the
completed modules, not necessary all with the same level number. At each point of time, a snapshot of the CSS standard can be defined, listing CSS2.1 and the mature modules. The W3 consortium periodically publishes such snapshots, like in 2007, 2010, 2015, 2017, and 2018. Though today no module with a level greater than 3 is standardized, this will change in the future. Some modules, like Selectors 4 or...
.... The W3 consortium periodically publishes such snapshots, like in 2007, 2010, 2015, 2017, and 2018. Though today no module with a level greater than 3 is standardized, this will change in the future. Some modules, like Selectors 4 or CSS Borders 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 r...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
er module. The Data Loader module is responsible for the requests and retrieves the stock data information from the web. It also sends an event to the Data Binder module. The Data Binder module is responsible for the binding of the data with the HTML interface. In addition to these components, you will also find the piece of code that is responsible for the DHTML ticker. Note that the ticker is a
completely separated component. The Data Binder will put the content in the proper place, so the existing DHTML ticker application is able to handle it. Special Markup to support the model It's important to add special markup that fulfills the requirements of the application. This example uses an IFRAME element as the mechanism to establish the communication with the server side application. So the follow...
...ME, 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 to do this. One is to keep checking the IFRAME until the document has
completed loading. Another approach is to request an HTML page in the IFRAME and inside this page (requested data), set the onload event to callback a function notifying the parent document (originator). This sample is using the second approach. To demonstrate how the callback mechanism is implemented, imagine the following HTML page loaded into the IFRAME as a result of a request (retrieveData method req...
JXON - Archive of obsolete content
ges or settings XML documents, for example). In these cases JXON could represent the most practical way. In this article we will show how to convert a parsed XML document (i.e. an instance of Document) to a JavaScript Object tree (i.e. a tree of nested instances of Object) and viceversa, with some different algorithms. It could be useful to read the XML introduction article first. If you want a
complete bidirectional JXON library (modelled on the JSON global object), skip to the dedicated paragraph (but please read the note about the const statement compatibility). Note: If you are interested to address only some parts of an XML document (and are not starting in JavaScript/JSON for templating purposes), use XPath instead of converting the whole document into JSON. Conversion snippets Now imag...
... though our algorithms work fine with any kind of XML document. Note: Despite the term JXON suggesting "lossless" conversions, these techniques are not actually lossless if one needs to preserve ordering of elements, as is common with many XML dialects (including of course XHTML). The ECMAScript standard (JavaScript) indicates that object iteration order is implementation dependent. Appendix: a
complete, bidirectional, JXON library Now we can create a more
complete, bidirectional, JXON library based on all our algorithms (see: #1, #2, #3, #4, reverse). Its usage is modeled on the JSON native object. Before implementing it in a working environment, please read the note about the const statement compatibility. The following code is also available on GitHub. "use strict"; /*\ |*| |*| JXON frame...
List of Mozilla-Based Applications - Archive of obsolete content
If you have information about a new project or extra information about an existing project, please feel free to update this page. A list of former Mozilla-based applications is also available. ...
... font management tool Firecast digital signage and interactive kiosk tools Also used in Firecast EasyStart Mozilla Firefox web browser Web Browser usage stats from Global Stats FossaMail email client for Windows platform, based on Mozilla Thunderbird Developed by Moonchild Productions, creator of the...
MMgc - Archive of obsolete content
required. DRC() is required for RC objects, since the reference count must be maintained. Write barriers are not needed for C++ objects that exist purely on the stack, and never in the heap. The Flash Player class "NativeInfo" is a good example. Such objects are essentially the same as stack-based local variables. Zeroing RCObjects All RCObjects (including all subclasses) must zero themselves out
completely upon destruction. Asserts enforce this. The reason is that our collector zeroes memory upon free and this was hurting performance. Since MMgc must traverse objects to decrement refcounts properly upon destruction, I just made destructors do zeroing too. This mostly applies to non-pointer fields as DRCWB smart pointers do this for you. Poisoned Memory In DEBUG builds, MMgc writes "poison" into d...
... loop that processes a queue. The way it works is that all GC roots are registered with the GC library and it can mark everything by traversing the roots. At the beginning all the GC roots are pushed onto the work queue. Items on the queue are conservatively marked and unmarked GC pointers discovered while processing each item are pushed on to the queue. When the queue is empty all the marking is
complete. Thus the queue itself is a perfect way to maintain marking state between marking increments. This isn't an accident, the GC system was in part designed this way so that it could be easily incrementalized. The problem then becomes: How to account for the fact that the mutator is changing the state of the heap between marking increments How much time to spend marking in each increment Mark consi...
Protecting Mozilla's registry.dat file - Archive of obsolete content
and Internet Explorer The easyest way to put into place the registry.dat file for a user would theoretically be to put it into the user's profile directory on the server. However, this issue is problematic, because: When the users logs in for the first time, Windows 2000 apparently doesn't load the profile from the server... In other Windows versions, Internet Explorer (which is hard to kick off
completely) likes to install "Personnalized settings" when the user logs in for the first time, and this seems to have the interesting "side-effect" of wiping any non-microsoft subfolders from %USERPROFILE%\Application Data, including Mozilla's . In order to prevent this, it's preferable to have mozilla's registry.dat file copied over from the server using the logon script. Moreover, it's advisable to "pr...
... "side-effect" of wiping any non-microsoft subfolders from %USERPROFILE%\Application Data, including Mozilla's . In order to prevent this, it's preferable to have mozilla's registry.dat file copied over from the server using the logon script. Moreover, it's advisable to "protect" the mozilla registry using attrib +r +s in case the logon script is finished before IE's "Personnalized settings" have
completed their dirty deed... In summary, you can use the following series of commands in your logon script (usually stored in /home/samba/netlogon/STARTUP.BAT on the server): rem ================================================== rem Mozilla rem ================================================== attrib -r -s "%USERPROFILE%\Application Data\Mozilla" >NUL 2>NUL attrib -r -s "%USERPROFILE%\Application Data...
Drag and Drop - Archive of obsolete content
ed. ondragenter Called for an element when the mouse pointer first moves over the element while something is being dragged. This might be used to change the appearance of the element to indicate to the user that the object can be dropped on it. ondragexit Called for an element when the mouse pointer moves out of an element while something is being dragged. The is also called after a drop is
complete so that an element has a chance to remove any highlighting or other indication. ondragdrop This event handler is called for an element when something is dropped on the element. At this point, the user has already released the mouse button. The element can simply ignore the event or can handle it some way, such as pasting the dragged object into itself. ondragend Called when the drag operat...
...agAndDrop.js nsDragAndDrop.js which is contained in the widget-toolkit (or global) package. XPCOM Drag and Drop interfaces Two interfaces are used to support drag and drop. The first is a drag service, nsIDragService and the second is the drag session, nsIDragSession. The nsIDragService is responsible for creating drag sessions when a drag starts, and removing the drag session when the drag is
complete. The function invokeDragSession should be called to start a drag inside an ondraggesture event handler. Once this function is called, a drag has started. The function invokeDragSession takes four parameters, as described below: invokeDragSession(element, transferableArray, region, actions) element A reference to the element that is being dragged. This can be retrieved by getting the propert...
JavaScript Client API - Archive of obsolete content
uid oldId and change it to be associated with the guid newId. getAllIDs() Must return an iterable list containing the GUIDs of every item being stored on the local system. This can be a dictionary-type object where the keys are the GUIDs and the values are whatever; or it can simply be a list of GUIDs. This is the method that the engine will call the first time it syncs, in order to get a
complete inventory of what data there is that will need to be uploaded to the server. Unless the items you're syncing have their own inherent GUIDs already defined, you'll need to invent GUIDs for all your items at this time. When one of these GUIDs is later passed as an argument to createRecord(), you need to return a record based on the matching data. Therefore, it's the responsibility of this method to...
...ined, you'll need to invent GUIDs for all your items at this time. When one of these GUIDs is later passed as an argument to createRecord(), you need to return a record based on the matching data. Therefore, it's the responsibility of this method to define the guid -> item mapping, and to store it for later reference by other methods. wipe() When this method is called, your Store needs to
completely wipe all of its stored data from the local application. That doesn't mean just whatever caches of the data the Store happens to be maintaining; it means the underlying data itself. For instance, BookmarkStore.wipe() deletes all bookmarks from the current Firefox profile. How to do this for your particular data type is up to you to figure out. The next three methods are called by the sync algo...
Creating a Help Content Pack - Archive of obsolete content
t_packs I hesitate to call it "original", tho, because I've basically rewritten the entire thing so that it's easier and faster to use to create Help content. The previous document had a lot of places where ideas were simply introduced without explanation, and I've tried to go through things a bit more slowly with better descriptions. This is still very much a work in progress, tho, and I need to
complete the rest of it soon (where "
complete" means "use what's there that's good, build on the stuff that's not as good, and add other useful information as necessary". This document describes how to integrate HTML help documentation into your application using the Mozilla Help Viewer. Documentation contained in the Help Viewer can be accessed using any XUL application or program that embeds Mozilla. ...
...Search automatically goes through all of the elements in the table of contents, index, and glossary, but you might wish to have Search go through more sources of data. One possible source might be an online, dynamically-generated list of added content stored on your web site. To have the Help Viewer search...
Twitter - Archive of obsolete content
ct corresponding to the parameters of the Twitter method. For instance, some Twitter methods have an id parameter, so you would define an id property and set its value to a user's ID. (You can read about the parameters of the various methods at Twitter's API reference.) There are two special, optional properties: success and error. 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 describin...
...mples 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!" }, username: "basic_auth_username", password: "basic_auth_password", success: function () console.log("Hey!") }); User authentication You can supply a username and password to methods that require authentication using the second, more advanced call style described above. Or you can simply rely on...
Menu - Archive of obsolete content
tpack.notifications.show(menuitem.label) }); Add an item to the hyperlink context menu that tweets the link: jetpack.menu.context.page.on("a").add(function (context) { return { label: "Tweet", command: function () jetpack.lib.twitter.statuses.update({ status: context.node.href }) }; )); Add an item to the page's context menu depending on some complex criteria that can't be
completely expressed via a CSS selector: jetpack.menu.context.page.beforeShow = function (menu, context) { menu.reset(); if (matchesMyCriteria(context)) menu.add("Match!"); }; Add an item to both the hyperlink context menu and the image context menu: jetpack.menu.context.page.on("a, img").set("A Link or Image"); Add an item to the image context menu, but only for images contained in hyperlinks: ...
...atus bar item) and attach menus directly to it. contextMenu becomes the button's context menu. Left-click the button to show popupMenu: var button = $("<div />", document); button.text("Click Me"); var contextMenu = new jetpack.Menu(["Do This", "Do That", "And the Other"]); contextMenu.contextOn(button); var popupMenu = new jetpack.Menu(["Frumpy", "Frimpy", "Frompy"]); popupMenu.popupOn(button);
Complete jetpacks See a
complete, real-word example that you can install in the simple storage documentation. Check also jetpacks tagged with "tutorial" at the Jetpack Gallery. ...
Tamarin build documentation - Archive of obsolete content
le ANDROID_DEVICE in the makefile (near line 65) to point to your sdk/ndk top folder. - Find the two instances of "android-ndk" and make sure they match your ndk's name (they should already). - In a terminal window change to your /openssl folder and run make build_libs to create the necessary 'libcrypto.a' and 'libssl.a' static libraries. ...
... will be compiled. Documentation on how to setup a user repository http://developer.mozilla.org/En/Publishing_Mercurial_Clones. Push any changes that you want to test into this repository. Request a build via the form at http://tamarin-builds.mozilla.org/build_trigger/requestbuild.cfm User Email: Your email address. An email with the build status will be sent to this address when a builder
completes whether it is passes or fails. Mercurial Repository: Give the location of the repository that will be used for the build. NOTE: Only repositories hosted on http://hg.mozilla.org/ are accepted. Revision: Specify the revision number that will be built. Currently this only accepts the change number and not the hash. Branch: Which branch of tamarin the repository is based on, Tamarin-Centra...
Tamarin Build System Documentation - Archive of obsolete content
sections: Sandbox Compile, Sandbox Smoke, Sandbox Test tamarin-central is considered a "sandbox" and will appear under Sandbox phase What are the build phases? Compile, Smoke, Test. When all of the slave machines are free they all start the first build phase simultaneously. If an error or failure occurs on any slave in a phase the build stops. The next phase is started when all slaves have
completed the previous phase successfully. The Compile phase compiles all of the tamarin source code and builds all of the shell executables, any errors will stop the phase and a red box will appear on the slave where the error occurred. The compile phase takes about 20-25 minutes. The Smoke phase runs a set of tests on each platform until 2 minute is exceeded. The set of smoke tests can contain any s...
... 20-25 minutes. The Smoke phase runs a set of tests on each platform until 2 minute is exceeded. The set of smoke tests can contain any shell build and any test suite (including performance). The smoke test list is constantly updated to contain the most recent failures, most frequent failures, and the newest testcases. The idea is to catch test failures in a few minutes rather than running the
complete test run (1h 45m). The smoke test including downloading the shell takes about 3-4 minutes. The Test phase runs all functional testcases including acceptance tests, cmdline tests, and selftests. The acceptance tests are the majority and are run on all shells (release, release-debugger, debug, debug-debugger). The test phase takes approximately 1 hour 45 minutes. The Performance and Deep phases ...
Tamarin Roadmap - Archive of obsolete content
The Tamarin roadmap is intended to provide visibility into planned features and release dates. The roadmap is a living document representing current best thinking and is subject to change. Comments or questions are welcome and encouraged via the tamarin-devel mailing list. ...
...inking and is subject to change. Comments or questions are welcome and encouraged via the tamarin-devel mailing list. TC Jan '09 Feature Links Status Integrate the TT String class Tamarin:String implementation Tamarin:Strings bug 465506
Complete Enhanced C++ profiler Enhance memory profiler to work in Release builds and be more performant In Progress Enable LIR for ARM targets bug 460764
Complete AMD64 NanoJit bug 464476 In Progress Port NanoJit to PowerPC bug 458077
Complete Add mac-x64 and linux-x64 buildbots
Complete fail build on assertion in acceptance tests
Complete Merge tracking bug bug 469836 In Progress TC Feb '09 Spring backlog tbd. ...
URIs and URLs - Archive of obsolete content
The filename consists of filebasename and fileextension. If the spec is completly broken down, it consists of: scheme, username, password, host, port, directory, filebasename, fileextension, param, query and ref. Together these segments form the URL spec with the following syntax: scheme://username:password@host:port/directory/filebasename.fileextension;param?query#ref For performance reasons the
complete spec is stored in escaped form in the nsStandardURL object with pointers (position and length) to each basic segment and for the more global segments like path and prehost for example. Necko provides pre written urlparsers for schemes based on hierachical naming systems. Escaping To be able to parse an URL safely it is sometimes necessary to "escape" certain characters, to hide them from the par...
..."escape" certain characters, to hide them from the parser. An escaped character is encoded as a character triplet, consisting of the percent character "%" followed by the two hexadecimal digits representing the octet code. For example, "%20" is the escaped encoding for the US-ASCII space character. Another quote from RFC 2396: A URI is always in an "escaped" form, since escaping or unescaping a
completed URI might change its semantics. Normally, the only time escape encodings can safely be made is when the URI is being created from its component parts; each component may have its own set of characters that are reserved, so only the mechanism responsible for generating or interpreting that component can determine whether or not escaping a character will change its semantics. Likewise, a URI must ...
Venkman Introduction - Archive of obsolete content
ion modules in Firefox by just clicking a hyperlink. If you don't already have Venkman or would like to upgrade, you can easily get the latest version from Firefox Add-ons. The installation process is two steps. First, from within the browser you want to host the debugger application, visit the Firefox Add-ons page and click on the "install" link for the most recent version. When the download is
complete, restart your browser (some Windows users may also need to restart their computer as well). You can then access the debugger via a new, dynamically created menuitem in the Tools menu of that browser, or else restart the browser with a special debugger option. To see which version of Venkman you have, type /version in the Interactive Session view. For more information about the latest improvement...
...how to use the next command. The input area supports command history and tab-completion for command names. Command history remembers the last 20 commands entered. The up and down arrows can be used to revisit these previous commands. Tab completion allows the user to type the first portion of a command, and press tab twice to see possible completions. If only one command matches, it will be auto-
completed on the first tab. View Customization Venkman offers nearly
complete control over the arrangement and display of views within the application. The debugger is built on top of an application framework that allows you to drag and drop, resize, and toggle all the available views, and even to create new views or modules for the debugger if you choose--though this latter is an advanced topic and a s...
Creating XPI Installer Modules - Archive of obsolete content
urces (i.e. XUL, JavaScript, or CSS files) in the chrome subdirectories and editing them with a text editor has been replaced by something a lot of developers find more confusing and esoteric. This article describes the new packaging scheme of Mozilla and offers a tutorial for creating a new package that can then be redistributed, installed, and made available to users. The XPI Packaging Scheme A
complete description of the new packaging scheme is beyond the scope of this article. The reader is referred to JAR Packaging, which describes the design, goals, and options available for JAR packaging in some depth. What follows is a very brief overview of the design and a description of what Mozilla expects in installable packages. Resources are collected in JAR archives whose contents are specified in ...
...ve and put it in the content/ subdirectory with the other package resources. barley/ content/ barley.gif barley.js barley.xul contents.rdf These four files are all you need in your new package. The next step is to zip up the contents of the working directory. Using a ZIP archiver[zip], create a new archive of the content/ subdirectory and name it barley.jar: Once this step is
complete, the Barley package is in the same state as the JAR packages of the Mozilla UI. comm.jar, en-US.jar, and all of the other archived UI packages have a similar--if slightly more complex--structure and content specification as the barley.jar. Making the Barley Install Script What remains is to package up your JAR file in such a way that it can be installed using Mozilla's XPInstall technology. The X...
panel.type - Archive of obsolete content
arrow Specify this for a panel that provides an arrow pointing at its anchor. drag Specify this for a panel that's being used as a drag image for a drag and drop operation. Otherwise leave this attribute out. ...
... arrow Specify this for a panel that provides an arrow pointing at its anchor. drag Specify this for a panel that's being used as a drag image for a drag and drop operation. Otherwise leave this attribute out. ...
OpenClose - Archive of obsolete content
t. However, there may be situations when you wish to open a menu manually. The menu element has an open property which may be set to true to open the menu, or false to close the menu. A simple example: somemenu.open = true; This single line of code will open a menu referenced by the variable 'somemenu'. Note that the open property applies to the menu or button, not to the menupopup. ...
...olean isContextMenu); The isContextMenu argument indicates that a context menu is being opened, and functions the same as the corresponding argument for the openPopup method. In the following example, the popup is opened at horizontal positon 100 and vertical position 200: popup.openPopupAtScreen(100, 200, false); Note that if the supplied coordinates would cause the popup to be partially or
completely off screen, the popup will be moved such that it is fully visible, and may be resized if necessary. Closing a Popup with the hidePopup method A popup menu is closed by the user pressing the Escape key or by clicking somewhere outside the popup. For closing menupopups that use the menu tag, the button tag and the toolbarbutton tag, see Closing Menus above. To close a popup with a script, use...
Property - Archive of obsolete content
align allNotifications allowEvents alwaysOpenPopup amIndicator appLocale autoCheck autoFill autoFillAfterMatch boxObject browsers builder builderView buttons canAdvance canGoBack canGoForward canRewind checked checkState child children className clickSelectsAll clientHeight clientWidth collapsed color columns command commandManager
completeDefaultIndex container contentDocument contentPrincipal contentTitle contentView contentViewerEdit contentViewerFile contentWindow contextMenu control controller controllers crop current currentIndex currentItem currentNotification currentPage currentPane currentSet currentURI customToolbarCount database datasources date dateLeadingZero dateVal...
...tViewerEdit contentViewerFile contentWindow contextMenu control controller controllers crop current currentIndex currentItem currentNotification currentPage currentPane currentSet currentURI customToolbarCount database datasources date dateLeadingZero dateValue decimalPlaces decimalSymbol defaultButton defaultValue description dir disableAuto
complete disableAuto
Complete disableautoselect disabled disableKeyNavigation dlgType docShell documentCharsetInfo editable editingColumn editingRow editingSession editor editortype emptyText Deprecated since Gecko 2 enableColumnDrag eventNode firstOrdinalColumn firstPermanentChild flex focused focusedItem force
Complete group handleCtrlPageUpDown handleCtr...
Filtering - Archive of obsolete content
er a triple or member is added or removed, the template must be rebuilt by calling the rebuild method. This method will remove all of the existing generated content, delete all of the internal information pertaining to the results, and start again as if the template were just being examined for the first time. The template will be parsed again and the data examined for new results. You can view a
complete example of this in action. A menulist is used to allow one to select either a specific country, or select All to show all of the photos. When a choice is made, the applyFilter function as shown above is called and the template content gets rebuilt with the desired filter applied. In this example, the menulist is hard-coded to contain the items that we know are in the datasource. Next, we'll look ...
...below are copied for each result. The elements above are not. <action> <menupopup> <menuitem uri="?country" label="?countrytitle" value="?country"/> </menupopup> </action> The result will be two generated menuitems, one for each country, inside a menupopup. The value attribute is assigned the ?country variable so that the applyFilter function can use this value easily for filtering. The
complete example shows this working. Note that due to a bug with template generation in menulists when the datasource hasn't loaded yet, you may have to load the example twice to get it work. This issue only affects the menulist element. Several workarounds can be used in this simple example. First, you could move the <menupopup> element outside of the template and put the datasources attribute on it inst...
The Joy of XUL - Archive of obsolete content
an application may specify that an Overlay be included in its definition. But Overlays can also be specified externally, enabling the designer to superimpose them upon an application without changing the original source. In practical terms, this enables developers to maintain one code stream for a given application, then apply custom branding or include special features for customers with a
completely independent code base. This leads to an overall solution that is easier and less costly to maintain in the long run. There is an additional benefit to Overlays for software developers who intend to add features to Mozilla that they wish to keep proprietary. The Netscape Public License (NPL) and Mozilla Public License (MPL) require developers who alter original work (source code files that ...
...his component to the other platforms. Fortunately, an implementation of the libical library was already available for Macintosh so, with the cross platform nature of XPCOM, a Macintosh calendar implementation was working within a few days. However, there was no existing Win32 port available, so developers had to undertake a porting effort to migrate libical to Windows. Within a week this too was
complete and Mozilla had a working calendar for all three primary platforms: Linux, Macintosh, and Windows. XPInstall is easy for developers and for users.The Calendar is not a planned deliverable for the Mozilla 1.0 release, and therefore is not included as a standard component in regular nightly and milestone release builds. Developers who are equipped with the software and knowledge required to compil...
XUL Reference - Archive of obsolete content
query queryset radio radiogroup resizer richlistbox richlistitem row rows rule scale script scrollbar scrollbox scrollcorner separator spacer spinbuttons splitter stack statusbar statusbarpanel stringbundle stringbundleset tab tabbrowser (Firefox-only starting with Firefox 3/Gecko 1.9) tabbox tabpanel tabpanels tabs template textnode textbox textbox (Firefox auto
complete) textbox (Mozilla auto
complete) timepicker titlebar toolbar toolbarbutton toolbargrippy toolbaritem toolbarpalette toolbarseparator toolbarset toolbarspacer toolbarspring toolbox tooltip tree treecell treechildren treecol treecols treeitem treerow treeseparator triple vbox where window wizard wizardpage Categorical list of all XUL elements << XUL Reference << Wind...
...enuseparator menupopup panel tooltip popupset toolbar toolbarbutton toolbargrippy toolbaritem toolbarpalette toolbarseparator toolbarset toolbarspacer toolbarspring toolbox tabbox tabs tab tabpanels tabpanel groupbox caption separator spacer button checkbox colorpicker datepicker menulist progressmeter radio radiogroup scale splitter textbox textbox (Firefox auto
complete) textbox (Mozilla auto
complete) timepicker description label image listbox listitem listcell listcol listcols listhead listheader richlistbox richlistitem tree treecell treechildren treecol treecols treeitem treerow treeseparator box hbox vbox bbox deck stack grid columns column rows row scrollbox action assign binding bindings conditions content member p...
Deploying XULRunner - Archive of obsolete content
ate shortcuts to scripts that launch your application in the unregistered bundled XULRunner. The responsibility still lies with the developer to provide the correct version of XULRunner per platform. In the end, most users are afraid of links that don't have a pretty icon so you may want to have a look at the Branding section of XULRunner tips. Windows On Windows, XULRunner does not yet have a
complete built-in installation solution; app developers should use pre-existing solutions for a native Windows installer. An example of one such solution may be found in the article: Creating a Windows Inno Setup installer for XULRunner applications. The installed files should be arranged in the following directory structure: installdir/ application.ini components/ ... components wh...
... the XULRunner application was not updated to know about the change, so it will report an error: "Unable to load XPCOM." XULRunner was fixed in Gecko 39. See this blog post for additional background about this change. XULRunner 38 and earlier In XULRunner 38 and earlier, XULRunner is provided in a Mac OS X Framework bundle, which is placed in your application bundle's Frameworks directory. The
complete bundle structure is as follows: MyApp.app/ Contents/ Info.plist PkgInfo Frameworks/ XUL.framework/ files copied from /Library/Frameworks/XUL.framework/Versions/1.8/... make sure you copy all symlinks correctly (use rsync -rl /Library/Frameworks/XUL.framework ...). Resources/ application...
Archived Mozilla and build documentation - Archive of obsolete content
lable in most Mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. It reports JavaScript-related errors and warnings, CSS errors and arbitrary messages from chrome code. In Firefox, the Error Console can be opened from the tools menu or by Ctrl-Shift-J. Exception logging in JavaScript Technical review
completed. Existing Content This is a list of existing mozilla.org documentation. It needs to be checked, prioritized, and migrated. Extension Frequently Asked Questions This is quick set of answers to the most common issues with extension development. They are currently written with mostly Firefox in mind, but most if not all should ea...
... browsers in a more useful and usable way. Plugin Architecture This page contains some notes on how plugins work internally in Gecko. It is mainly of interest to Gecko developers. Porting NSPR to Unix Platforms Last modified 16 July 1998 Priority Content Update: I've removed documents from this list that have been migrated into the wiki. The list of
completed documents is available through the DevEdge page. Prism Prism is a simple XULRunner-based browser that hosts web applications without the normal web browser user interface. Prism is based on a concept called Site-Specific Browsers (SSB). An SSB is designed to work exclusively with a single web application. It doesn't have the menus, toolbars and other accoutreme...
Gecko Compatibility Handbook - Archive of obsolete content
or HTML, CSS, and the DOM existed. These earlier, non-standards based browsers differed in several ways from Gecko: These browsers use proprietary (non-standard) HTML, CSS, and JavaScript. Internet Explorer 4 and Netscape Navigator 4 share support for a large part of the HTML 3.2 standard and basic JavaScript. While they support the CSS 1 standard to some degree, the implementations are not
complete and have non-standard features added. Neither Internet Explorer 4 or Netscape Navigator 4 support the W3 DOM. Instead, each browser supports its own proprietary API for manipulating the content, style and position of HTML Elements in a web page. In addition, Internet Explorer 4 and Netscape Navigator 4 use
completely different methods of embedding third-party software into the browser. Gecko ...
...ore of the reasons listed above. This is also the case for older versions of web authoring tools such as Macromedia's Dreamweaver 2 and 3. Newer versions of these APIs and tools do support Gecko however. For example, DYNAPI is now maintained at SourceForge and offers a Gecko-compatible version. Newer versions of web authoring tools support Gecko. Wrong DOCTYPE Problem: An incorrect DOCTYPE can
completely alter a page's presentation. Gecko, Internet Explorer for Mac OS and Internet Explorer 6 all use a technique called DOCTYPE sniffing to determine if a page is to be laid out in a fashion compatible with the older browsers or if it is to be laid out in a fashion compatible with the W3 standards. Using the appropriate DOCTYPE in an HTML document allows a web page author to continue to support ...
Extentsions FAQ - Archive of obsolete content
ion_FAQ and check if there are any errors in JS console. Friday, September 29 - October 6, 2006 (? top) Is there anyway, via plugin or extension, for Firefox to mimic the functionality of IE in this respect? The IETab (Opens IE in a Firefox tab) should be able do this if you set it to always open "file://*" URLs in an IE tab. The appearance with a FireFox tab isn't quite the same as having a
completely separate Explorer window. However, it's functional and does allow for the Explorer to be handling the display of the folder contents, and all of the right-click context menu support is present so it should meet my needs. What is the valid location and things needed to to release a Mozilla extension on Mozallia site? You must remove updateURL from the install.rdf and use a known to AMO min...
.../mozilla1.8/so...ents/nsBrowser... Firefox will clean all those preferences which are still "default", that is not changed by the user or the application/extension. To provide those default preferences to your extension see: http://kb.mozillazine.org/Dev_:_Usin...lt_preferences BTW: Resetting prefences to default will clear them in case no default prefence is (still) available. Those will be
completely removed upon next application launch. Is it possible to create a sidebar on the top of the page? Not unless you make it a separate window. There's a bug in bugzilla about stacking other widgets on top of browser/iframe, which hopefully will be fixed for Gecko 1.9. Could someone write an extension that zaps the Google Analytics cookie, the Urchin cookie, switches Gmail and Google Calender...
2006-10-06 - Archive of obsolete content
To help out with testing meet in IRC chat room #qa. ...
... a few problems found where FF was hanging on shutdown and some weird behaviors in the download manager. Update checker was run; all failures found were expected. Build is Go for launch. Vista Testers - needed to test Firefox and Thunderbird in Vista. Any test case ideas specific to Vista are welcomed. Check posting for details. FireFox 2 RC2 testing - Tim Riley announced the L10n builds were
completed last night. To help out with testing meet in IRC chat room #qa. Test results will be posted here. Discussions None for this week Meetings Community Test Day - on Friday October 6th, 2006 in IRC chat room #testday there will be a test day focusing on Safe Browsing between 7am to 5pm PDT. Bug Day - in IRC chat room #bugday on Oct 3rd. Reminder from Tracy. Check posting for times in your regi...
NPFullPrint - Archive of obsolete content
_NPFullPrint { NPBool pluginPrinted; /* true: print fullscreen */ NPBool printOne; /* true: print one copy */ /* to default printer */ void* platformPrint; /* Platform-specific */ } NPFullPrint; Fields The data structure has the following fields: pluginPrinted Determines whether the plug-in prints in full-page mode. Values: true: Plug-in takes
complete control of the printing process and prints full-page. false: (Default) Plug-in renders its area of the page only (for embedded plug-in). printOne Not currently in use. Should always be false. true: Print single copy of page to the default printer. false: Display print dialogs so user can choose printer, other options. platformPrint Platform-specific printing information. Mac OS: THPrint ...
...c OS: THPrint MS Windows: Printer's device context Description The NPP_Print function passes the plug-in a pointer to an NPPrint object (previously allocated by the browser). The NPFullPrint structure is used when the mode field of NPPrint is set to NP_Full. The pluginPrinted field of this structure determines whether the plug-in prints in full-page mode or not. If you want the plug-in to take
complete control of the printing process, it should print the full page and set the field pluginPrinted to true before returning. If you want an embedded plug-in to simply render its area of the page, set pluginPrinted to false and return immediately; the browser calls NPP_Print again with the NPEmbedPrint substructure of NPPrint. See Also NPP_Print, NPPrint, NPEmbedPrint ...
NPP_DestroyStream - Archive of obsolete content
yed. Syntax #include <npapi.h> NPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason); Parameters The function has the following parameters: instance Pointer to current plug-in instance. stream Pointer to current stream. reason Reason the stream was destroyed. Values: NPRES_DONE (Most common):
Completed normally; all data was sent to the instance. NPRES_USER_BREAK: User canceled stream directly by clicking the Stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. NPRES_NETWORK_ERR: Stream failed due to problems with network, disk I/O, lack of memory, or other problems. Returns If successful, the plug-in should retur...
...: Stream failed due to problems with network, disk I/O, lack of memory, or other problems. Returns If successful, the plug-in should return NPERR_NO_ERROR. If unsuccessful, the plug-in should return an error code. For possible values, see Error Codes. Description The browser calls the NPP_DestroyStream function when a data stream sent to the plug-in is finished, either because it has
completed successfully or terminated abnormally. After this, the browser deletes the NPStream object. You should delete any private data allocated in stream->pdata at this time, and should not make any further references to the stream object. See Also NPP_NewStream, NPStream ...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
XEmbed when the plugin is first initialized. If you've built your plugin so that it will support either Xt or XEmbed you can include a fallback for older style hosting. If you haven't you can return an error and the plugin will be ignored. It's good practice to do this in case people try to install your plugin for older versions of the browser that don't support XEmbed functionality. This is an in
complete example of what a piece of code might look like that tries to check for the proper Mozilla version. This would be included in your NP_Initialize function. NPError NP_Initialize(NPNetscapeFuncs* nsTable, NPPluginFuncs* pluginFuncs) { NPError err = NPERR_NO_ERROR; PRBool supportsXEmbed = PR_FALSE; NPNToolkitType toolkit = 0; [ code that copies all of the function tables and does ] ...
...ugin that would run out of process as well as using other toolkits like Qt to build plugins. Since XEmbed was designed for cross-toolkit and out of process applications, it should work. In fact, version 1.5 of the Java Plugin will probably use XEmbed out of process. The author has no specific knowledge of other instances where people are using this architecture, though. XEmbed Sample Plugin For a
complete working sample of a plugin using in-process XEmbed, see the DiamondX XEmbed Example Plugin. Works only in Firefox 2.0. ...
Introduction to SSL - Archive of obsolete content
with the session key. It then sends a separate (encrypted) message indicating that the client portion of the handshake is finished. The server sends a message to the client informing it that future messages from the server will be encrypted with the session key. It then sends a separate (encrypted) message indicating that the server portion of the handshake is finished. The SSL handshake is now
complete, and the SSL session has begun. The client and the server use the session keys to encrypt and decrypt the data they send to each other and to validate its integrity. Before continuing with the session, Red Hat servers can be configured to check that the client's certificate is present in the user's entry in an LDAP directory. This configuration option provides one way of ensuring that the clien...
...e key used to create the signature and that the data has not been tampered with since it was signed. At this point, however, the binding between the public key and the DN specified in the certificate has not yet been established. The certificate might have been created by someone attempting to impersonate the user. To validate the binding between the public key and the DN, the server must also
complete Step 3 and Step 4. Is today's date within the validity period? The server checks the certificate's validity period. If the current date and time are outside of that range, the authentication process won't go any further. If the current date and time are within the certificate's validity period, the server goes on to Step 3. Is the issuing CA a trusted CA? Each SSL-enabled server maintains a l...
Common Firefox theme issues and solutions - Archive of obsolete content
The purpose of this page is to provide provide theme developers with notes on how to fix common issues. It is a companion document to the AMO editors guide Common Theme Problems, which provides editors with "boilerplate" copy and paste review notes for common theme issues. This document was started on July 27, 2012 so it will take some time to
completely fill in and some issues still need to have solutions written for them. Operating system specific issues Windows 7 Windows 7 Aero missing right-hand title bar buttons When tabs are on top and the menu bar is disabled, Firefox is missing the min/max/restore/close button on the right side of the title bar. Please see the following threads on MozillaZine for solutions to this issue: http://forums.mozillazine.org/viewtopic.php?f=18&t=2131121 ht...
...Using the default theme in the latest Firefox, please try Tools > Web Developer > Inspect to see how this new feature functions and how it should be styled. You'll probably want to copy the files from the folder browser/devtools/ from the default theme into your theme and then modify as necessary to achieve t...
Scratchpad - Archive of obsolete content
persistent, multiline editor, and the Console to interact with the page. Editing The Scratchpad window looks something like this (on macOS the menu bar is at the top of the screen): The File menu offers options to save and load JavaScript code snippets, so you can reuse code later if you like. Code completion Scratchpad integrates the tern code analysis engine, and uses that to provide auto
complete suggestions and popups containing information on the current symbol. To list auto
complete suggestions, press Ctrl + Space. For example, try typing d, then pressing Ctrl + Space. You'll see the auto
complete box, as shown below: The icon next to each suggestion indicates the type, and the currently highlighted suggestion gets a popup with more information. ? and ? cycle through the suggestions an...
... In the Editor Preferences section of the developer tools settings, you can choose to use Vim, Emacs, or Sublime Text key bindings instead...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
</tt>, the file descriptor must be closed before the thread exits. In this memo we explain the problem this guideline is trying to work around and discuss its limitations. NSPR IO on NT The IO model of NSPR 2.0 is synchronous and blocking. A thread calling an IO function is blocked until the IO operation finishes, either due to a successful IO completion or an error. If the IO operation 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 r...
...PT_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 (called the idle threads) monitoring the IO completion port for
completed IO requests. If a
completed IO request appears at the IO completion port, an idle thread fetches it and wakes up the thread that issued the IO request earlier. This is the normal way the thread is awakened. IO Timeout and Interrupt However, NSPR may wake up the thread in two other situations: if the overlapped IO request is not
completed before the specified timeout. (Note that we can't spe...
Old Proxy API - Archive of obsolete content
}, }; proxy = Proxy.create(handler); var c = Object.create(proxy); print(c.foo); // prints: 'true' (from "proxy !== rcvr") and 'bye' (from "c.foo"). // In this example, the get trap rcvr argument is the c object while proxy is its prototype Examples Very simple example A trap is called almost each time something happens to your proxy (that is used like an object). ...
... Examples Very simple example A trap is called almost each time something happens to your proxy (that is used like an object). Here is an example: var in
completeHandler = {get:function(myProxy, name){ alert('Property ' + name + ' accessed.'); return 1; } }; var p = Proxy.create(in
completeHandler); var q = p.blabla; // alerts 'Property blabla accessed' and 1 is assigned to q p.azerty = "Trying to set a property"; // throws an error since neither the set trap or the fundamental trap used in the set trap are implemented No-op forwarding proxy In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it. function han...
Implementation Status - Archive of obsolete content
n be found on the Mozilla XForms Specials page. Specification Chapter Index Here we give an overview of XForms 1.1 specification chapters and the current status of the Mozilla support. The sections are marked with their current status: Supported, partial support, in progress, and not currently supported. We have listed the most relevant bugs here, but check out the Bugzilla XForms buglist for the
complete list. 3. Document Structure Section Title Status Notes Bugs 3.1 Namespaces supported 3.2.1 Common Attributes supported 3.2.2 Linking Attributes supported 3.2.3 Single-Node Binding Attributes supported...
...ed 7.7.7 random() supported 7.7.8 compare() supported 7.8.1 if() supported 7.8.2 property() partial returns basic for conformance-level, should return full. version will return as "1.0" for now, until more 1.1 work is
completed. 334333; 7.8.3 digest() unsupported 7.8.4 hmac() unsupported 7.9.1 local-date() supported 7.9.2 local-dateTime() supported 7.9.3 now() supported 7.9.4 ...
RDF in Mozilla FAQ - Archive of obsolete content
ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource); // Be sure that your web server will deliver this as text/xml (recommended) or text/rdf! remote.Init("http://www.mozilla.org/some-rdf-file.rdf"); // Make it load! Note that this will happen asynchronously. By setting // aBlocking to true, we could force it to be synchronous, but this // is generally a bad idea, because your UI will
completely lock up! 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 t...
...r 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 nsIRDFRemoteDataSource interface, it is possible to immediately query the loaded property to determine if the datasource has loaded or not: // Get the RDF service var RDF = Components .classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); // Get the datasource. var ds = RDF.GetDataSource...
The Business Benefits of Web Standards - Archive of obsolete content
ng behind proprietary markup and technologies, can contribute to a company's business goals. Site Wide Consistent Look and Feel By separating structure (or content) from presentation, web designers have a lot to gain. Specifically, presentation is defined using layout-oriented CSS language. Storing CSS in a separate document (aka style sheet) and applying it to a set of HTML documents permits a
complete change of presentation for all these documents in a snap. Strict HTML (as opposed to the often-used transitional HTML markup), forces the designer not to use presentation tags in the HTML documents, naturally enforcing the separation of content from presentation. By locating all the style and design issues in one document - the style sheet - whole sites can be rethemed in one go. The blogging co...
... designer not to use presentation tags in the HTML documents, naturally enforcing the separation of content from presentation. By locating all the style and design issues in one document - the style sheet - whole sites can be rethemed in one go. The blogging community are particularly dynamic in this respect where on many platforms including WordPress, TextPattern and Habari, the site theme is a
complete and discrete entity in its own right. Improved User Experience: Less Bandwidth and Fast Loads HTML code is often much more compact (therefore easier to read and maintain) when used in conjunction with CSS. According to various reports, case studies, and Andy King, author of Speed Up Your Web Site: Web Site Optimization, CSS has made it possible to transform table-based layouts into CSS-based la...
Efficient animation for web games - Game development
ions are much higher level than JavaScript, and express a very specific intent. Because of this, the browser can make some assumptions that it can't easily make when you're manually tweaking values in JavaScript. To take a concrete example, if you start a CSS transition to move something from off-screen so that it is fully visible on-screen, the browser knows that the related content will end up
completely visible to the user and can then pre-render that content. When you animate position with JavaScript, the browser cannot easily make that same assumption, and so you might end up causing it to draw only the newly-exposed region of content, which may introduce slow-down. There are signals at the beginning and end of animations that allow you to attach JavaScript callbacks and form a rudimentary f...
...tend to prioritise framerate during player movement and combat, but may prioritise image quality or physics detail when compromise to framerate and input response would be less noticeable. Measure performance There are some popular animation-related libraries and UI toolkits with animation functions that still do things like using setTimeout to drive their animations, drive all their animations
completely individually, or other similar things that aren't conducive to maintaining a high frame-rate. One of the goals for the Puzzowl game is for it to be a solid 60fps on reasonable hardware (for the record, it's almost there on Galaxy Nexus-class hardware) while still being playable on low-end devices (such as a Firefox OS Geeksphone Keon). It would have been good to use as much third party software...
Animations and tweens - Game development
moothly animate properties of an object in the gameworld, such as width or opacity. Let's add a tween to our game to make the bricks smoothly disappear when they are hit by the ball. Go to your ballhitBrick() function, find your brick.kill(); line, and replace it with the following: var killTween = game.add.tween(brick.scale); killTween.to({x:0,y:0}, 200, Phaser.Easing.Linear.None); killTween.on
Complete.addOnce(function(){ brick.kill(); }, this); killTween.start(); Let's walk through this so you can see what's happening here: When defining a new tween you have to specify which property will be tweened -- in our case, instead of hiding the bricks instantly when hit by the ball, we will make their width and height scale to zero, so they will nicely disappear. To the end, we use the add.tw...
...k.scale as the argument as this is what we want to tween. The to() method defines the state of the object at the end of the tween. It takes an object containing the chosen parameter's desired ending values (scale takes a scale value, 1 being 100% of size, 0 being 0% of size, etc.), the time of the tween in milliseconds and the type of easing to use for the tween. We will also add the optional on
Complete event handler, which defines a function to be executed when the tween finishes. The last thing do to is to start the tween right away using start(). That's the expanded version of the tween definition, but we can also use the shorthand syntax: game.add.tween(brick.scale).to({x:2,y:2}, 500, Phaser.Easing.Elastic.Out, true, 100); This tween will double the brick's scale in half a second using...
Randomizing gameplay - Game development
This means that every game is quite similar. To fix this and improve playability we should make the rebound angles more random, and in this article we'll look at how. ...
... of the paddle and the place where the ball hits it. Also, the direction (left or right) is determined by that value -- if the ball hits the left side of the paddle it will bounce left, whereas hitting the right side will bounce it to the right. It ended up that way because of a little bit of experimentation with the given values, you can do your own experimentation and see what happens. It's not
completely random of course, but it does make the gameplay a bit more unpredictable and therefore more interesting. 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 works: Summary You've finished all the lessons -- congratulations! By this point you would have learnt the basics of Phaser and the logic behind simple...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
In computing, the word "asynchronous" is used in two major contexts. Networking and communications Asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt. ...
...lications--is a mechanism that requests relatively small amounts of data from the server using HTTP, with the result being returned when available rather than immediately. Software design Asynchronous software design expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to
complete. When the secondary task is
completed, the original task is notified using an agreed-upon mechanism so that it knows the work is done, and that the result, if any, is available. There are a number of programming techniques for implementing asynchronous software. See the article Asynchronous JavaScript for an introduction to them. Learn more Technical reference Fetching data from the ser...
What is accessibility? - Learn web development
nesses, such as depression and schizophrenia. It also includes people with learning disabilities, such as dyslexia and attention deficit hyperactivity disorder. Importantly, though there is a lot of diversity within clinical definitions of cognitive impairments, people with them experience a common set of functional problems. These include difficulty with understanding content, remembering how to
complete tasks, and confusion caused by inconsistent webpage layouts. A good foundation of accessibility for people with cognitive impairments includes: delivering content in more than one way, such as by text-to-speech or by video; easily-understood content, such as text written using plain-language standards; focusing attention on important content; minimizing distractions, such as unnecessary co...
... Notes Designing with cognitive accessibility will lead to good design practices. They will benefit everyone. Many people with cognitive impairments also have physical disabilities. Websites must conform with the W3C's Web Content Accessibility Guidelines, including cognitive accessibility guidelines. The W3C's Cognitive and Lear...
CSS values and units - Learn web development
: Hue: The base shade of the color. This takes a value between 0 and 360, representing the angles round a color wheel. Saturation: How saturated is the color? This takes a value from 0-100%, where 0 is no color (it will appear as a shade of grey), and 100% is full color saturation Lightness: How light or bright is the color? This takes a value from 0-100%, where 0 is no light (it will appear
completely black) and 100% is full light (it will appear
completely white) We can update the RGB example to use HSL colors like this: Just as RGB has RGBA, HSL has an HSLA equivalent, which gives you the same ability to specify the alpha channel. I've demonstrated this below by changing my RGBA example to use HSLA colors. You can use any of these color values in your projects. It is likely that ...
...e when specifying generated content. In this case the value is quoted to demonstrate that it is a string. In the below example we use unquoted color keywords along with a quoted generated content string. Functions The final type of value we will take a look at is the group of values known as functions. In programming, a function is a reusable section of code that can be run multiple times to
complete a repetitive task with minimum effort on the part of both the developer and the computer. Functions are usually associated with languages like JavaScript, Python, or C++, but they do exist in CSS too, as property values. We've already seen functions in action in the Colors section -- rgb(), hsl(), etc. The value used to return an image from a file -- url() -- is also a function. A value that beh...
Legacy layout methods - Learn web development
d. In the <style> element, add the following code, which gives the wrapper container a width of 980 pixels, with padding on the right hand side of 20 pixels. ...
...The rows will remain separated, and not interfere with each other. The gutters between the columns are 20 pixels wide. We create these gutters as a margin on the left side of each column -- including the first column, to balance out the 20 pixels of padding on the right hand side of the container. ...
Responsive design - Learn web development
yout, describing a method of creating a design that could adapt to different screen resolutions. This approach required JavaScript to detect the screen resolution and load the correct CSS. Zoe Mickley Gillenwater was instrumental in her work to describe and formalize the different ways in which flexible sites could be created, attempting to find a happy medium between filling the screen or being
completely fixed in size. Responsive design The term responsive design was coined by Ethan Marcotte in 2010 and described the use of three techniques in combination. The first was the idea of fluid grids, something which was already being explored by Gillenwater, and can be read up on in Marcotte's article, Fluid Grids (published in 2009 on A List Apart). The second technique was the idea of fluid i...
...lems. You can provide multiple sizes along with "hints" (meta data that describes the screen size and resolution the image is best suited for), and the browser will choose the most appropriate image for each device, ensuring that a user will download an image size appropriate for the device they are using. You can also art direct images used at different sizes, thus providing a different crop or
completely different image to different screen sizes. You can find a detailed guide to Responsive Images in the Learn HTML section here on MDN. Responsive typography An element of responsive design not covered in earlier work was the idea of responsive typography. Essentially, this describes changing font sizes within media queries to reflect lesser or greater amounts of screen real estate. In this ex...
CSS FAQ - Learn web development
or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance. Modern browsers have two main rendering modes: Quirks Mode: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. Documents with an in
complete, incorrect, or missing DOCTYPE declaration or a known DOCTYPE declaration in common use before 2001 will be rendered in Quirks Mode. Standards Mode: the browser attempts to follow the W3C standards strictly. New HTML pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern DOCTYPE declaration will be rendered with Standards Mode. Gecko-based brow...
...ise when the standard is extended. The use of such properties on production websites is not recommended -- they have already created a huge web compatibility mess. For example, many developers only using the -webkit- prefixed version of a property when the non-prefixed version is supported across all browsers meant that a feature relying on that property would break in non-webkit-based browsers,
completely needlessly. This problem got so bad that other browsers started to implement -webkit- prefixed aliases to improve web compatibility, as specified in the Compatibility Living Standard. In fact most browsers now do not use CSS prefixes when implementing experimental features, instead implementing those features only on Nightly browser versions or similar. If you need to use prefixes in your wor...
Styling web forms - Learn web development
ph in Chrome. Rather, it uses the font-family: system-ui. This is another reason to use <button> elements over their equivalent input types! There's a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. This decision is yours to make, as the designer of your site, or web application. Box sizing All text fields have
complete support for every property related to the CSS box model, such as width, height, padding, margin, and border. As before, however, browsers rely on the system default styles when displaying these widgets. It's up to you to define how you wish to blend them into your content. If you want to keep the native look and feel of the widgets, you'll face a little difficulty if you want to give them a consi...
... Tweaking the textareas <textarea> elements default to being rendered as an inline-block element. The two important things here are the resize and overflow properties. While our design is a fixed-size design, and we could use the resize property to pre...
JavaScript basics - Learn web development
let myVariable = 3; !(myVariable === 3); "Does-not-equal" gives basically the same result with different syntax. Here we are testing "is myVariable NOT equal to 3". This returns false because myVariable IS equal to 3: let myVariable = 3; myVariable !== 3; There are a lot more operators to explore, but this is enough for now. See Expressions and operators for a
complete list. Note: Mixing data types can lead to some strange results when performing calculations. Be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter '35' + '25' into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than addi...
... setting its onclick handler property equal to an anonymous (i.e. nameless) function, which contains the code we want the click event to run. Note that document.querySelector('html').onclick = function() {}; is equivalent to let myHTML = document.querySelector('html'); myHTML.onclick = function() {}; It's just shorter. Supercharging our example website With this review of JavaScript basics
completed (above), let's add some new features to our example site. Adding an image changer In this section, you will learn how to use JavaScript and DOM API features to alternate the display of one of two images. This change will happen as a user clicks the displayed image. Choose an image you want to feature on your example site. Ideally, the image will be the same size as the image you added previ...
What’s in the head? Metadata in HTML - Learn web development
e page and into a new text file in your code editor, then save it in a sensible place. Press the "Raw" button on the GitHub page, which causes the raw code to appear (possibly in a new browser tab). Next, choose your browser's File > Save Page As... menu and choose a sensible place to save the file. Now open the file in your browser. You should see something like this: It should now be
completely obvious where the <h1> content appears, and where the <title> content appears! You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it. The <title> element contents are also used in other ways. For example, if you try bookmarking the page (Bookmarks > Bookmark This Page or the star ...
... of meta element it is; what type of information it contains. content specifies the actual meta content. Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example: <meta name="author" content="Chris Mills"> <meta name="description" content="The MDN Web Docs Learning Area aims to provide
complete beginners to the Web with all they need to know to get started with developing web sites and applications."> Specifying an author is beneficial in many ways: it is useful to be able to understand who wrote the page, if you have any questions about the content and you would like to contact them. Some content management systems have facilities to automatically extract page author information and m...
General asynchronous programming concepts - Learn web development
d running. Note: OK, in our case, it is ugly and we are faking the blocking effect, but this is a common problem that developers of real apps fight to mitigate all the time. Why is this? The answer is because JavaScript, generally speaking, is single-threaded. At this point, we need to introduce the concept of threads. ...
...fight to mitigate all the time. Why is this? The answer is because JavaScript, generally speaking, is single-threaded. At this point, we need to introduce the concept of threads. Threads A thread is basically a single process that a program can use to
complete tasks. Each thread can only do a single task at once: Task A --> Task B --> Task C Each task will be run sequentially; a task has to
complete before the next one can be started. As we said earlier, many computers now have multiple cores, so can do multiple things at once. Programming languages that can support multiple threads can use multiple cores to
complete multiple tasks simultaneously: Thread 1: Task A --> Task B Thread 2: Task C --> Task D JavaScript is single-threaded JavaScript is traditionally single-threaded. Even with m...
Function return values - Learn web development
all of these below. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps, Functions -- reusable blocks of code. Objective: To understand function return values, and how to make use of them. What are return values? Return values are just what they sound like -- the values 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 on...
...', '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 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 whe...
Arrays - Learn web development
Carlisle']; First of all, to add or remove an item at the end of an array we can use push() and pop() respectively. Let's use push() first -- note that you need to include one or more items that you want to add to the end of your array. Try this: myArray.push('Cardiff'); myArray; myArray.push('Bradford', 'Brighton'); myArray; The new length of the array is returned when the method call
completes. If you wanted to store the new array length in a variable, you could do something like this: let newLength = myArray.push('Bristol'); myArray; newLength; Removing the last item from the array is as simple as running pop() on it. Try this: myArray.pop(); The item that was removed is returned when the method call
completes. To save that item in a new variable, you could do this: let r...
...rms are displayed in the list. When the number of terms goes over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed. Note: In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now. To
complete the app, we need you to: Add a line below the // number 1 comment that adds the current value entered into the search input to the start of the array. This can be retrieved using searchInput.value. Add a line below the // number 2 comment that removes the value currently at the end of the array. Playable code 2 <h2>Live output</h2> <div class="output" style="min-height: 150px;"> <input t...
Test your skills: Strings - Learn web development
JavaScript console, in the case of the downloadable version). Strings 1 In our first strings task, we start off small. You already have half of a famous quote inside a variable called quoteStart; we would like you to: Look up the other half of the quote, and add it to the example inside a variable called quoteEnd. Concatenate the two strings together to make a single string containing the
complete quote. Save the result inside a variable called finalQuote. You'll find that you get an error at this point. Can you fix the problem with quoteStart, so that the full quote displays correctly? Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Strings 2 In this task you are provi...
...re small fix to do -- add a full stop onto the end of the quote, and save the final version in a variable called finalQuote. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Strings 4 In the final string task, we have given you the name of a theorem, two numeric values, and an in
complete string (the bits that need adding are marked with asterisks (*)). We want you to change the value of the string as follows: Change it from a regular string literal into a template literal. Replace the four asterisks with four template literal placeholders. These should be: The name of the theorem. The two number values we have. The length of the hypotenuse of a right-angled triang...
Measuring performance - Learn web development
I for metrics related to all of the navigation events displayed in the didagram below. The Performance API, which provides access to performance-related information for the current page, includes the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. These interfaces allows the accurate measurement of the time it takes for JavaScript tasks to
complete. The PerformanceEntry object is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways; such as loading a resource, like an image. The PerformanceObserver API can be used to observe performance mea...
...ifferent actions. This indicates the features that might be slowing down your web app or site. Conclusion This article provided a brief overview of the web performance metrics to help introduce you to what you can measure on a web app or site. Next up, you'll look at perceived performance and some techniques to make unavoidable performance hits appear less severe to the user, or disguise them
completely. Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
Perceived performance - Learn web development
(and regressions). Relevant measurements include first meaningful paint (FMP), largest contentful paint (LCP), time to interactive (TTI), render start, DOM interactive, and speed index. First paint is reported by the browser and provides the time, in ms, of when the page starts changing; but this change can be a simple background color update or something even less noticable. It doesn't indicate
completeness and may report a time when nothing visible is painted. First Contentful Paint (FCP) reports the time when the browser first rendered anything of signifigance, be that text, foreground or background image, or a canvas or SVG; capturing the very beginning of the loading experience. But, just because there's content, doesn't mean it's useful content or that the user has content to consume. The F...
...ements are visible, the user should be able to interact with them without a lag. Users feel that something is laggy when they take more than 50ms to react. They feel that a page is janky when content repaints slower than 16.67ms (or 60 frames per second) or repaints at uneven intervals. Make things like type-ahead a progressive enhancement: use css to display input modal, JS to add typeahead/auto
complete as it is available Make task initiators appear more interactive Making a content request on keydown rather than waiting for keyup can shave 200ms off the perceived load of the content. Adding an interesting but unobtrusive 200ms animation to that keyup even can reduce another 200ms of the perceived load. You're not saving 400ms of time, but the user doesn't feel like they're waiting for content...
Introduction to the server side - Learn web development
ht, share, and control access to interesting content. Some of the common uses and benefits of server-side programming are listed below. You'll note that there is some overlap! Efficient storage and delivery of information Imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook? Creating a separate static page for each product or post would be
completely impractical. Server-side programming allows us to instead store the information in a database and dynamically construct and return HTML and other types of files (e.g. PDFs, images, etc.). It is also possible to simply return data (JSON, XML, etc.) for rendering by appropriate client-side web frameworks (this reduces the processing burden on the server and the amount of data that needs to be se...
... previously visited or popular locations you may want to look at on a map. Note: Google Maps saves your search and visit history. Frequently visited or frequently searched locations are highlighted more than others. Google search results are optimized based on previous searches. Go to Google search. Search for "football". Now try typing "favourite" in the search box and observe the auto
complete search predictions. Coincidence? Nada! Controlled access to content Server-side programming allows sites to restrict access to authorized users and serve only the information that a user is permitted to see. Real world examples include: Social networks like Facebook allow users to fully control their own data but only allow their friends to view or comment on it. The user determines who ...
Getting started with Ember - Learn web development
crease the efficiency of developers at the cost of having to learn those conventions. As conventions are defined and shared, the opinions that back those conventions help reduce the menial differences between apps -- a common goal among all opinionated frameworks, across any language and ecosystem. Developers are then more easily able to switch between projects and applications without having to
completely relearn the architecture, patterns, conventions, etc. As you work through this series of tutorials, you'll notice Ember's opinions -- such as strict naming conventions of component files. How does Ember relate to vanilla JavaScript? Ember is built on JavaScript technologies and is a thin layer on top of traditional object-oriented programming, while still allowing developers to utilize funct...
...onstrates how < 20% of the JS written is specific to Ember. Getting started The rest of the Ember material you'll find here consists of a multi-part tutorial, in which we'll make a version of the classic TodoMVC sample app, teaching you how to use the essentials of the Ember framework along the way. TodoMVC is a basic to-do tracking app implemented in many different technologies. Here is the
completed Ember version, for reference. A note on TodoMVC and accessibility The TodoMVC project has a few issues in terms of adhering to accessible/default web practices. There are a couple of GitHub issues open about this on the TodoMVC family of projects: Add keyboard access to demos Re-enable Outline on focusable elements Ember has a strong commitment to being accessible by default and there is...
Introduction to client-side frameworks - Learn web development
t is an older framework that has less users than more modern alternatives such as React and Vue, but it still enjoys a fair amount of popularity due to its stability, community support, and some clever coding principles. Start learning Ember Angular Angular is an open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. It is a
complete rewrite from the same team that built AngularJS. Angular was officially released on the 14th of September 2016. Angular is a component-based framework which uses declarative HTML templates. At build time, transparently to developers, the framework's compiler translates the templates to optimized JavaScript instructions. Angular uses TypeScript, a superset of JavaScript that we'll look at in a li...
... a multi-page website -- including any relevant CSS or JavaScript -- so that they can be published in any number of places. The publishing host could be a GitHub pages branch, a Netlify instance, or any private server of your choosing, for example. There are a number of advantages of this approach, mostly around performance (your user's device isn't building the page with JavaScript; it's already
complete) and security (static pages have fewer attack vectors). These sites can still utilize JavaScript where they need to, but they are not dependent upon it. Static site generators take time to learn, just like any other tool, which can be a barrier to your development process. Static sites can have as few or as many unique pages as you want. Just as frameworks empower you to quickly write client-sid...
Getting started with React - Learn web development
of npm. If you have both package managers installed and explicitly want to use NPM, you can add the flag --use-npm when you run create-react-app: npx create-react-app moz-todo-react --use-npm create-react-app will display a number of messages in your terminal while it works; this is normal! This might take a few minutes, so now might be a good time to go make a cup of tea. When the process is
complete, cd into the moz-todo-react directory and run the command npm start. The scripts installed by create-react-app will start being served at a local server at localhost:3000, and open the app in a new browser tab. Your browser will display something like this: Application structure create-react-app gives us everything we need to develop a React application. Its initial file structure looks like ...
... of your app. We won't cover deployment in this tutorial, but you should be able to use a similar solution to that described in our Deploying our app tutorial. The package.json file contains information about our project that Node.js/npm uses to keep it organized. This file is not unique to React applications; create-react-app merely populates it. You don't need to understand this file at all to
complete this tutorial, however, if you'd like to learn more about it, you can read What is the file `package.json`? on NodeJS.org; we also talk about it in our Package management basics tutorial. Exploring our first React component -- <App/> In React, a component 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 sing...
Vue conditional rendering: editing existing todos - Learn web development
onent We can start by creating a separate component to handle the editing functionality. In your components directory, create a new file called ToDoItemEditForm.vue. ...
...dit functionality. Try doing this: Check (or uncheck) one of the todo checkboxes. Press the "Edit" button for that todo item. Cancel the edit by pressing the "Cancel" button. Note the state of the checkbox after you cancel -- not only has the app forgotten the state of the checkbox, but the done status of that todo item is now out of whack. If you try checking (or unchecking) it again, the
completed count will change in the opposite way to what you'd expect. This is because the isDone inside data is only given the value this.done on component load. Fixing this is fortunately quite easy -- we can do this by converting our isDone data item into a computed property -- another advantage of computed properties is that they preserve reactivity, meaning (among other things) that their state is sa...
Styling Vue components with CSS - Learn web development
well. We'll also add the input__lg class to our <input> element. Update your ToDoForm template so that it looks like this: <template> <form @submit.prevent="onSubmit"> <h2 class="label-wrapper"> <label for="new-todo-input" class="label__lg"> What needs to be done? </label> </h2> <input type="text" id="new-todo-input" name="new-todo" auto
complete="off" v-model.lazy.trim="label" class="input__lg" /> <button type="submit" class="btn btn__primary btn__lg"> Add </button> </form> </template> Let's also add the stack-large class to the <ul> tag in our App.vue file. This will help improve the spacing of our to-do items a bit. Update it as follows: <ul aria-labelledby="list-summary" class="stack-large"> Adding ...
... a checkbox class. Last of all, to the <label> add a checkbox-label class. The updated template is below: The app should now have custom checkboxes. Your app should look something like the screenshot below. Summary Our work is done on the styling of our sample app. In the next article we'll return to adding some more functionlity to our app, namely using a computed property to add a count of
completed todo items to our app. Previous Overview: Client-side JavaScript frameworks Next In this module Introduction to client-side frameworks Framework main features React Getting started with React Beginning our React todo list Componentizing our React app React interactivity: Events and state React interactivity: Editing, filtering, conditional rendering Accessibil...
Introduction to automated testing - Learn web development
ed to install it from nodejs.org: Download the installer for your system from the above site. (If you already have Node and npm installed, jump to point 4) Install it like you would any other program. Note that Node comes with Node Package Manager (npm), which allows you to easily install packages, share your own packages with others, and run useful scripts on your projects. Once the install
completes, test that node is installed by typing the following into the terminal, which returns the installed versions of Node and npm: node -v npm -v If you've got Node/npm already installed, you should update them to their latest versions. To update Node, the most reliable way is to download and install an updated installer package from their website (see link above). To update npm, use the followi...
... 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 project is as follows: html-tidy, css-lint, and js-hint to lint and report/fix common HTML/CSS/JS errors (see gulp-htmltidy, gulp-csslint,...
Introduction to cross browser testing - Learn web development
e on all browsers, as long as the core functionality is accessible in some way. On modern browsers you might get something animated, 3D and shiny, whereas on older browsers you might just get a flat graphic representing the same information. As long as the site owner is happy with this, then you have done your job. On the other hand, it is not OK for a site to work fine for sighted users, but be
completely inaccessible for visually impaired users because their screen reader application can't read any of the information stored on it. Second, when we say "across an acceptable number of web browsers", we don't mean 100% of the browsers in the world -- this is just about impossible. You can make some informed calls as to what browsers and devices your users will be using (as we'll discuss in the sec...
...get bigger, as doing all this testing by hand can start to take a really long time. You can set up your own testing automation system (Selenium being the popular app of choice) that could for example load your site in a number of different browsers, and: see if a button click causes something to happen successfully (like for example, a map displaying), displaying the results once the tests are
completed take a screenshot of each, allowing you to see if a layout is consistent across the different browsers. You can also go further than this, if wished. There are commercial tools available such as Sauce Labs, Browser Stack, Endtest, LambdaTest, TestingBot, and CrossBrowserTesting that do this kind of thing for you, without you having to worry about the setup, if you wish to invest some money in...
Strategies for carrying out testing - Learn web development
pt for more details). We should put this into grade B as well. Using analytics A much more accurate source of data, if you can get it, comes from an analytics app like Google Analytics. This is an application that will give you accurate stats on exactly what browsers people are using to browse your site. Of course, this relies on you already having a site to use it on, so it isn't much good for
completely new sites. But an analytics history can be useful for finding support stats to influence say a new version of a company's site, or new features you are adding to an existing site. If you have these available, they are far more accurate than global browser stats like those mentioned above. You may also consider using open source and privacy focussed analytics platforms like Open Web Analytics ...
...ke on a physical machine. Important: You need to make sure you have the operating system image you want to install on the virtual machine available at this point, and install it right away. If you cancel the process at this point, it can render the virtual machine unusable, and make it so you need to delete it and create it again. This is not fatal, but it is annoying. After the process has
completed, you should have a virtual machine running an operating system inside a window on your host computer. You need to treat this virtual operating system installation just like you would any real installation -- for example, as well as installing the browsers you want to test, install an anti-virus program to protect it from viruses. Having multiple virtual machines is very useful, particularly ...
Git and GitHub - Learn web development
f the code base if a problem is discovered later on. The most popular VCS (at least among web developers) is Git, along with GitHub, a site that provides hosting for your repositories and several tools for working with them. This module aims to teach you what you need to know about both of them. Overview VCSes are essential for software development: It is rare that you will work on a project
completely on your own, and as soon as you start working with other people you start to run the risk of conflicting with each other's work -- this is when both of you try to update the same piece of code at the same time. You need to have some kind of mechanism in place to manage the occurences, and help avoid loss of work as a result. When working on a project on your own or with others, you'll want to ...
... example of a VCS, and GitHub is a web site + infrastructure that provides a Git server plus a number of really useful tools for working with git repositories individually or in teams, such as reporting issues with the code, reviewing tools, project management features such as assigning tasks and task statuses, and more. Note: Git is actually a distributed version control system, meaning that a
complete copy of the repository containing the codebase is made on your computer (and everyone else's). You make changes to your own copy, and then push those changes back up to the server, where an administrator will decide whether to merge your changes with the master copy. Looking to become a front-end web developer? We have put together a course that includes all the essential information you n...
Client-side tooling overview - Learn web development
an indicator of its quality. Development-related forums to ask questions on about what tools to use, for example MDN Learn Discourse, or Stack Overflow. When you've chosen a tool to use, the first port of call should be the tool project homepage. This could be a full blown website or it might be a single readme document in a code repository. The date-fns docs for example are pretty good,
complete, and easy to follow. Some documentation however can be rather technical and academic and not a good fit for your learning needs. Instead, you might want to find some dedicated tutorials on getting started with particular types of tools. Great starting places is to search web sites like CSS Tricks, Dev, freeCodeCamp, and Smashing Magazine, as they're tailored to the web development industry. Aga...
... a high level. ...
Understanding client-side web development tools - Learn web development
Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a
complete toolchain example showing you how to get productive. Get started now, with our "Client-side tooling overview" Prerequisites You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Guides 1. Client-side tooling overview In this a...
...to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (CLI) tools. 3. Package management basics In this article we'll look at package managers in some detail to understand how we can use them in our own projects -- to install project tool dependencies, keep them up-to-date, and more. 4. Introducing a
complete toolchain In the final couple of articles in the series we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. We'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on Netlify. In this article we'll introduce the case study, set up our devel...
Accessibility/LiveRegionDevGuide
ypes, namely EVENT_OBJECT_SHOW and EVENT_OBJECT_HIDE. Text Changed The text changed events are quite similar in AT-SPI and IAccessible2 with both having an insert and delete or removal events. The text changed event type in AT-SPI has a similar scheme as the object:children-changed events. In this case, the root event string is object:text-changed with ":delete" and ":insert" being appended to
complete the event type. In IAccessible2, there are two distinct event types - IA2_EVENT_TEXT_REMOVED and IA2_EVENT_TEXT_INSERTED. The text associated with an AT-SPI text changed event is directly in the event object. The event.any_data field holds the entire text string while event.detail1 is the start index while event.detail2 is the text string length. In IAccessible2, IAccessibleText::get_oldText and ...
...ating the "non-live" events, some sort of event filtering logic must be employed. The following is a list of potential filtering techniques: The "event-from-input" object attribute can be used to filter events that were triggered by user action. The ":system" (or lack thereof) can be used to filter events that are system generated. (AT-SPI only) A global variable can be set in a document:load:
complete event listener and reset in a object:state-changed:busy listener. This variable can then be used to quickly determine if an event was triggered by the document being loaded. An event containing an object that does not have state VISIBLE is probably from a hidden tab. An event containing an object that has state SELECTABLE is not a live region. An event containing an object that has the attribu...
Mozilla accessibility architecture
ed in nsIAccessibleEventReceiver.idl. The accessibility client can find out what kind of event occurred as well as what accessible node the event occured on. Table of Gecko Event to Accessible Event Translation Accessible documents listen for DOM events on nodes within them, and consequently fire the appropriate accessible event. This happens in the HandleEvent() method. Note: this chart is not
complete, consult the HandleEvent() method to see the rest. Gecko Events (or callback) Event Type Accessibility Event focus, select Standard HTML DOM event EVENT_FOCUS DOMMenuItemActive, DOMMenuBarActive Mozilla DOM EVENT_FOCUS DOMNodeInserted W3C DOM Mutation event EVENT_CREATE (ATK) EVENT...
... Challenges of the Accessibility Cache There are some tricky issues when dealing with the accessibility cache: Remaining valid: changes in a given document, or the destruction of documents must update or shutdown parts of the cache. We use DOM mutation events to listen for document changes, and invalidate the appropriate part of each cache. We must be careful: if the DOM mutation events are in
complete, then our cache will not be a correct mirror of the DOM. If we do not shut down nodes that go away, we cause more memory footprint than necessary. Accessibles with no DOM node: Some accessible children are generated by the accessible parent, because they have no DOM node. These accessibles cannot be shutdown by traversing the DOM, because their cache entry is not based on their DOM node. Theref...
CSUN Firefox Materials
Internet Explorer for screen reader users. In fact, the same keyboard commands are still available, so users can become comfortable and productive right away. Screen magnifier users can also benefit from Firefox's powerful features today, as caret and focus tracking are fully enabled. Mozilla Corporation is currently reaching out to work with AI Squared, the makers of ZoomText, in order to enable
complete support of advanced ZoomText features such as the Doc Reader and App Reader. Firefox on Linux currently boasts the best onscreen keyboard support in the industry via GOK, the Gnome Onscreen Keyboard. Basic screen reader accessibility is available via Gnopernicus or the Fire Vox extension. Keyboard Support "Mozilla Firefox is a web-browser with superior keyboard support. " - Alan Cantor, Cantor...
...ion. We expect enterprising script writers will eventually fix annoying accessibility issues in popular web pages, and (hopefully) share their tricks with everyone! IE Tab allows you to embed Internet Explorer into Firefox tabs. This extension is useful for making IE specific sites, or site that read better in IE, open directly in Firefox, while using the Internet Explorer engine Tab Mix Plus
completely enhances Firefox's tab browsing capabilities. It includes such features as duplicating tabs, controlling tab focus, tab clicking options, undo closed tabs and windows, plus much more. It also includes a full-featured session manager with crash recovery that can save and restore combinations of opened tabs and windows. Fire Vox is a screen reader extension built just for Firefox which can read...
Links and Resources
r Developers at Adobe - Flash MX accessibility, PDF document accessibility and ActionScript accessibility. Online Accessibility validators There are now a few available and excellent online accessibility validators which check single webpages according to checkpoints of WCAG guidelines and then reports errors or warnings. WebXACT(TM) from Watchfire(R) Corporation WebXACT(TM) is a free and
complete online accessibility validation service that can test single pages for quality, accessibility and privacy issues. The accessibility report will contain errors and warnings for "Automatic Checkpoints" and "Manual Checkpoints"; detailed and useful information (line numbers, instances/occurences, textual references to guidelines) will be included for web authors. Cynthia says(TM) from HiSoftwar...
...l information (line numbers, instances/occurences, textual references to guidelines) will be included for web authors. Cynthia says(TM) from HiSoftware(R) Company "Cynthia says(TM)" is a free online webpage accessibility validation service that identifies accessibility errors in webpage related to Section 508 standards and/or the WCAG guidelines. Just like WebXACT, it can also perform a "
Complete Webpage Quality Check" for accessibility, privacy, searchability, metadata and even alt text attribute quality. Accessibility Valet from WebThing Description and summary to be written. WAVE 3.0 (Web Accessibility Versatile Evaluator) from WebAIM and sponsored by Temple University Institute on Disabilities WAVE 3.0 is another powerful, mature, free online webpage accessibility va...
Index
to follow, as well as offering some pointers to a suitable timeline. 682 Submitting an add-on Add-ons, Beginner, Tutorial, WebExtensions This article walks through the process of publishing an add-on. If you just want to get started, head to the Submit a New Add-on page on AMO. 683 Source code submission Add-ons, Extensions, Review Policy, distribution To
complete the review process at addons.mozilla.org (AMO), reviewers must be able to read the code in your extension. Some build processes render extension code difficult to read. These processes include minifying your code, as well as the use of module bundlers or similar tools, such as webpack. In this case, when you upload your extension to AMO, you will need to provide your source code and instructions ...
...torial, add-on The theme generator on addons.mozilla.org (AMO) guides you through the process of creating a theme for Firefox. Once you have defined the colors and image for your theme, the generator will submit your new theme to AMO. You may submit themes for publishing on AMO or for self-distribution. 688 Third Party Library Usage Add-ons, Extensions, Review Policy To
complete the review process at addons.mozilla.org (AMO), reviewers must be able to verify the code in your extension. You may include third-party libraries in your extension. In that case, when you upload your extension to AMO, you will need to provide links to the library source code. 689 Updates Firefox supports automated updates to add-ons using JSON update manifests. Add-ons host...
Creating reftest-based unit tests
king about and managing the execution of a manual test is fairly high. This is why manual tests tend to get longer, include more steps and ultimately become a long list that actually tests a lot of things. So, create small tests. For example, it occurs to me that we assume that spaces between a element name and an attribute name have no effect, but do we know this is true? Who checks this? It is
completely trivial, but so what. I can create 50 or 100 test files that have spaces between the element name and the attribute of a element for a bunch of different elements, add those to the list of tests to be run, and it causes no problems for anyone. Maybe it will actually take 500 test files to actually check this behavior. It really does not matter. So, my point is, if you have an idea then create ...
...arts of the screen that should change so that the screen displays the correct output the next time it is repainted. Invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen. In order to test invalidation it is important that invalidation tests let the document
completely finish loading and displaying before making the changes for which invalidation and repainting is to be tested. Making the changes before the document has
completely finished loading and painting would mean that the test may not actually test the browser's invalidation logic, since the changed parts of the document may end up displaying correctly purely due to a pending post-load paint. To writ...
Old Thunderbird build
dware requirements At least 4 GB of RAM. 8 GB or more is recommended. While you can build Thunderbird on older hardware it can take quite a bit of time to compile on slower machines with less RAM. Good internet connection for the initial source download. Build prerequisites Depending on your Operating System you will need to carry out a different process to prepare your machine. So firstly
complete the instructions for your OS and then continue following these build instructions. To build on Windows, please read the prerequisites so you don't skip preparing the MAPI headers needed to compile Thunderbird. Windows Build Prerequisites GNU/Linux Build Prerequisites Mac OS X Build Prerequisites Get the source Note: On Windows, you won't be able to build the Thunderbird source code if ...
...cript to do just that. This may take a while, it's a lot of code! First, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout On some types of network connections, "hg clone" might fail because it gets interrupted. It is faster and more efficient to use Mercurial bundles instead the first time you fetch the
complete repo. In this case, you need a bundle for comm-central, and a bundle for mozilla-central. Unbundle mozilla-central into a "mozilla" subdirectory of your comm-central repo after unbundling comm-central. (Make sure the unbundled folder's name is now "mozilla" and not "mozilla-central"). Then run "python client.py checkout" to ensure you are up-to-date. The source code requires 3.6GB of free space...
Simple Sunbird build
Building Sunbird is no longer supported. You can give it a try, but its likely that the build system will present you an error. Instead it is suggested to build Thunderbird with Lightning. Please refer to the Simple Thunderbird build guide. You can build a bleeding-edge, development version of Sunbird using the commands below. For
complete information, see the build documentation. Installing build tools If your system is not listed below, see the build prerequisites page. Ubuntu Linux: sudo apt-get build-dep sunbird sudo apt-get install mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libiw-dev autoconf2.13 cvs Fedora Linux: sudo yum groupinstall 'Development Tools' 'Development Libraries' 'GNOME Software Development' sudo yum install mercurial autoconf213 glibc...
...o easily integrate Lightning into a nightly version of Thunderbird. How to build again later In your comm-central directory, run these commands: # Get the latest source python client.py checkout Then just re-run the "make -f client.mk" command above. make will only recompile files that changed, but it's still a long haul. ...
Simple Thunderbird build
dware requirements At least 4 GB of RAM. 8 GB or more is recommended. While you can build Thunderbird on older hardware it can take quite a bit of time to compile on slower machines with less RAM. Good internet connection for the initial source download. Build prerequisites Depending on your Operating System you will need to carry out a different process to prepare your machine. So firstly
complete the instructions for your OS and then continue following these build instructions. Windows Build Prerequisites GNU/Linux Build Prerequisites macOS Build Prerequisites MAPI Headers On Windows: check that the MAPI header files from https://www.microsoft.com/en-us/download/details.aspx?id=12905 are installed because the MAPI header files (except MAPI.h) are not bundled with Visual Studio 201...
...re! To also build Lightning when building Thunderbird (DEPRECATED) NOTE: The Lightning calendar add-on was integrated into Thunderbird starting with version 74. The `--enable-calendar` option is now deprecated and no longer has any effect. If it is in your `mozconfig` file, you should go ahead and remove it when building Thunderbird 74 or later, since support for it will eventually be removed
completely. Add the following line to your mozconfig file: ac_add_options --enable-calendar To add that line you can do this in the source/ directory: echo 'ac_add_options --enable-calendar' >> mozconfig Building Before you start, make sure that the version you checked out is not busted. For hg tip, you should see green Bs on https://treeherder.mozilla.org/#/jobs?repo=comm-central To start the bu...
The Firefox codebase: CSS Guidelines
follow the style of existing or related code. Other tips Assume ="true" in attribute selectors. Example: Use option[checked], not option[checked="true"]. Avoid ID selectors unless it is really the wanted goal, since IDs have higher specificity and therefore are harder to override. Using descendant selectors is good practice for performance when possible: For example: .auto
complete-item[selected] > .auto
complete-item-title would be more efficient than .auto
complete-item[selected] .auto
complete-item-title Overriding CSS Before overriding any CSS rules, check whether overriding is really needed. Sometimes, when copy-pasting older code, it happens that the code in question contains unnecessary overrides. This could be because the CSS that it was overriding got removed...
... idea for theme support. Never write CSS specially for the built-in light/dark theme in compacttheme.css unless that CSS isn't supposed to affect WebExtension themes. These selectors can be used to target dark areas: :-moz-lwtheme-brighttext: dark window frame. :root[lwt-toolbar-field-brighttext]: dark address bar and searchbar. :root[lwt-popup-brighttext]: dark arrow panels and auto
complete panels. :root[lwt-sidebar-brighttext]: dark sidebars. If you'd like a different shade of a themed area and no CSS variable is adequate, using colors with alpha transparency is usually a good idea, as it will preserve the original theme author's color hue. Variables For clarity, CSS variables that are only used when a theme is enabled have the --lwt- prefix. Layout & performance Layo...
mach
Mach figures out how to execute the tests for you! Check out the linting and analysis tools: $ ./mach lint $ ./mach static-analysis mach and mozconfigs It's possible to use mach with multiple mozconfig files. mach's logic for determining which mozconfig to use is effectively the following: If a .mozconfig file (some say it is the file mozconfig without the dot) exists in th...
...est webconsole/test # Run mochitests in devtools/client/webconsole/test Enable tab completion To enable tab completion in bash, run the following command. You can add the command to your .profile so it will run automatically when you start the shell: source /path/to/mozilla-central/python/mach/bash-completion.sh This will enable tab completion of mach command names, and in the future it may
complete flags and other arguments too. Note: Mach tab completion will not work when running mach in a source directory older than Firefox 24. For zsh, you can call the built-in bashcompinit function before sourcing: autoload bashcompinit bashcompinit source /path/to/mozilla-central/python/mach/bash-completion.sh Frequently Asked Questions Why should I NOT use mach? A real FAQ for a change! Mach i...
Multiple Firefox profiles
dd-ons from your profile for Nightly use while keeping them for use with other profiles. For QA, testing, and bug triaging contributors, you may want to have multiple development versions of Firefox installed, each with its own profile. Creating new profiles for testing can keep you from losing your preferences, bookmarks, and history. It takes little time to set up a new profile, and once it is
complete, all of your Firefox versions will update separately and can be run simultaneously. Available browser development channels There are four available browser channels, each at a different level of stability and development. The four channels are Release, Beta, Developer Edition, and Nightly. The Release channel is recommended for most users, as it is the "official release" channel. However, for t...
...o your desired profile handy, enter a space character, followed by -profile followed by another space character, followed by the full path to the profile folder you wish to launch into. This will launch Firefox immediately. Otherwise, enter a space character followed by --profilemanager. This will present the Profile Manager window in which you can make your selection. Hit return. Here is a
complete example Terminal command from steps 2-3: /Applications/Firefox.app/Contents/macOS/firefox -profile /Users/Suzie/Library/Application\ Support/Firefox/Profiles/r99d1z7c.default If the Profile Manager window does not open, Firefox may have been running in the background, even though it was not visible. Close all instances of Firefox, or restart the computer, and then try again. If you want to...
MozBeforePaint
You may take a look at this example live if you like. ...
...tAnimationFrame(); </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. ...
Embedding Tips
Here is a simple example which demonstrates the principle. The SimplePersist() function takes a string URL and a string file path. In response it creates a persist object, creates a listener and starts the operation. As the operation progresses, methods on the listener such as OnStateChange, OnProgressChange etc. are called, allowing the embedder to know what is happening. When the operation is
completed, the OnStateChange will be notified by a combination of STATE_STOP | STATE_IS_NETWORK state flags. You may also use the progress listener to query the request supplied in OnStateChange for more information. For example, if you wanted to check the server response headers, you might check OnStateChange for STATE_START | STATE_IS_REQUEST flags, and from the nsIRequest argument QI fornsIHttpChanne ...
...Change for more information. For example, if you wanted to check the server response headers, you might check OnStateChange for STATE_START | STATE_IS_REQUEST flags, and from the nsIRequest argument QI fornsIHttpChanne and call methods on that to determine response codes and other information from the server. It is left as an exercise to make this sample synchronous, i.e. wait for persistence to
complete before returning. Hint, add a native message processing loop after the call to SaveURI that terminates when OnStateChange indicates persistence has finished.. How do I print a page? Query the web browser object for nsIWebBrowserPrint. Call the nsIWebBrowserPrint::Print() method supplying a print settings object (e.g. that returned from nsIWebBrowserPrint::GetGlobalPrintSettings) that you wish t...
How to get a stacktrace with WinDbg
*c:\symbols*http://symbols.mozilla.org/firefox;SRV*c:\symbols*http://msdl.microsoft.com/download/symbols .symfix+ c:\symbols .reload /f Now wait for the symbols to download. This may take some time depending on your connection speed; the total size of the Mozilla and Microsoft symbols download is around 1.4GB. WinDbg will show "Busy" at the bottom of the application window until the download is
complete. Once the download is
complete, you need to configure WinDbg to examine child processes, ignore a specific event caused by Flash Player, and record a log of loaded modules. You will also want to open a log file to save data you collect. To do this, enter these four commands, pressing enter after each one. .logopen /t c:\temp\firefox-debug.log .childdbg 1 .tlist sxn gp lm If you see firefox.ex...
...eak. Once the browser has crashed or been stopped, continue with the steps below. After the crash or hang You need to capture the debug information to include in a bug comment or support request. Enter these three commands, one at a time, to get the stacktrace, crash/hang analysis and log of loaded modules. (Again, press Enter after each command.) ~* kp !analyze -v -f lm After these steps are
completed, find the file c:\temp\firefox-debug-(Today's Date).txt on your hard drive. To provide the information to the development community, submit this file with a support request or attach it to a related bug on Bugzilla. Producing a minidump Sometimes the stacktrace alone is not enough information for a developer to figure out what went wrong. A developer may ask you for a "minidump" or a "full mem...
Internationalized Domain Names (IDN) Support in Mozilla Browsers
fault.htm (Domain names in other languages) On July 10, 2003 and thereafter, you can access a large number of Japanese domain name sites under the .jp top domain with no further setting on Netscape 7.1/Mozilla 1.4: http://mitsuketa-nihongo.jp RACE (Row-based ASCII Compatible Encoding) Almost all IDN registration data are expected to change to Punycode by the end of 2003. Some country will
complete the conversion quickly, e.g. Japan as mentioned above, but others such as the ones under the .com and .net top domains may take longer. Most of the existing sites currently use the ASCII-compatible encoding known as RACE or Row-based ASCII Compatible Encoding, which was not accepted as a standard by IETF. If you find IDN test sites under the .com and .net top domains, and if you cannot successfu...
...m and .net top domains may take longer. Most of the existing sites currently use the ASCII-compatible encoding known as RACE or Row-based ASCII Compatible Encoding, which was not accepted as a standard by IETF. If you find IDN test sites under the .com and .net top domains, and if you cannot successfully access these sites, you can use the following workaround until the conversion to Punycode is
completed for these top domains: Using Netscape 7.1 or Mozilla 1.4: Type about:config into the location/URL bar. This will list all the preferences for your current profile. These preferences can be modified or new ones can be created without quitting the browser using the steps described below. Create a new preference item using the menu New > String via a right-mouse click. The name of the preferen...
AddonInstall
ll if the add-on is coming from the Internet and has yet to be downloaded. progress integer The progress of any necessary downloads. maxProgress integer The expected size of any necessary downloads or -1 if unknown. certificate nsIX509Cert If the add-on to be installed is signed this is the certificate of the signer. Only available after downloading is
complete. certName string If the add-on to be installed is signed this is 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...
... to be installed is signed this is 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. 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 InstallListen...
InstallListener
nloadProgress() Called as data is received during a download. Check the progress property for the amount of data downloaded and the maxProgress property for the total data expected. A listener may return false to cancel the download. void onDownloadProgress( in AddonInstall install ) Parameters install The AddonInstall representing the install onDownloadEnded() Called when downloading
completes successfully for an add-on install. Only called for add-ons that need to be downloaded. void onDownloadEnded( in AddonInstall install ) Parameters install The AddonInstall representing the install onDownloadCancelled() Called when downloading is cancelled. Only called for add-ons that need to be downloaded. void onDownloadCancelled( in AddonInstall install ) Parameters install ...
...Failed( in AddonInstall install ) Parameters install The AddonInstall representing the install onInstallStarted() Called when installation of an add-on begins. A listener may return false to cancel the install. void onInstallStarted( in AddonInstall install ) Parameters install The AddonInstall representing the install onInstallEnded() Called when installation of an add-on is
complete. The newly installed add-on may require a restart in order to become active. void onInstallEnded( in AddonInstall install in Addon addon ) Parameters install The AddonInstall representing the install addon The Addon addon that has been installed onInstallCancelled() Called when installation is cancelled. void onInstallCancelled( in AddonInstall install ) Parameters install ...
UpdateListener
e 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(in Addon addon, in AddonInstall install) void onNoUpdateAvailable(in Addon addon) void onUpdateFinished(in Addon addon, in integer error) Methods onCompatibilityUpdateAvailable() Called when the ...
... void onUpdateFinished( in Addon addon, in integer error ) Parameters addon The Addon that was being checked for updates error Any error from the update checkAddon ...
CustomizableUI.jsm
d been moved to a different position!) onWidgetUndoMove(aNode, aContainer) Fired after undoing a reset to default placements moves a widget's node to a different location. aNode is the widget's node, aContainer is the area it was moved into (NB: it might already have been there and been moved to a different position!) onAreaReset(aArea, aContainer) Fired after a reset to default placements is
complete on an area's DOM node. Note that this is fired for each DOM node. aArea is the area that was reset, aContainer the DOM node that was reset. onAreaNodeUnregistered(aArea, aNode, aReason) Fired when an area's DOM node is unregistered. aArea is the area for which a node was unregistered, aNode the DOM node which was unregistered, and aReason indicates whether the area as a whole was unregistered (...
...s that tab), it doesn't give it the 32x32 icon it needs (i have to figure out how and update the docs, its probably onWidgetRemoved or something) Giving the button an icon via style sheet method The above code creates your widget with click functionality. However it will not have an icon. We have to register a style sheet for that. This example here uses nsIStyleSheetService to do so. ...
DownloadTarget
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 to disable the use of a ".part" file ...
...e 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 to disable the use of a ".part" file to keep partially downloaded data. size Read only Number The size of the target file, in bytes, or zero if the download has not yet been
completed. It is possible for this property to have a non-zero value even if the target file no longer exists, if the value is available in download metadata. If that metadata is no longer available and the file has been deleted, then this value is zero. For single-file downloads, this property's value will always match the actual size of the file on disk, while the Download.totalBytes property,...
FxAccountsOAuthClient.jsm
th 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. on
Complete 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 FxAccountsOAuthClient( Object options Object parameters String client_id String state Str...
... Call this function to manually release all channels and callbacks that are in use by this client. ...
Interfacing with the Add-on Repository
e user clicks a toolbar button to initiate the query, the following code gets run to start the request: AddonRepository.retrieveRecommendedAddons(10, this); This asks the repository to fetch up to 10 add-ons, using the object this as the target for callbacks. The callback object needs to implement the SearchCallback interface, providing the methods that get called when a search either fails or
completes successfully. Handling failed requests The callback object must have a searchFailed() method; this gets called when a repository search fails to execute. 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.showNotific...
...("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. The important thing to note is that this will handle the failure case. Handling successful requests The callback object's searchSucceeded() method gets called when a search
completes successfully. It receives a list of the matching addons, the number of add-ons returned, and the total number of add-ons that matched the query (in case the returned number is smaller than the requested number, for example). For example: searchSucceeded: function(addons, addonCount, totalResults) { var num = Math.floor(Math.random() * addonCount); this.showNotification("Would you like to ...
Following the Android Toasts Tutorial from a JNI Perspective
he third argument of LoadClass for fields, we will only need static_fields. Fields do not accept arguments, so the "method format" is not used, we simply tell the sig the type of the field, which we find out from the Android documentation website. ...
...etContext method; DXR showed that this method accepted no arguments and returns a Context, and we already had the sig for Context in our SIG object. var geckoAppShell = JNI.LoadClass(my_jenv, SIG.GeckoAppShell.substr(1, SIG.GeckoAppShell.length - 2), { static_methods: [ { name: 'getContext', sig: '()' + SIG.Context } ] }); Porting the Java code Now that all the declarations are
complete, we can now side-by-side port the Java code to JNI. // Context context = getApplicationContext(); var context = geckoAppShell.getContext(); // CharSequence text = 'Hello toast!'; var text = 'Hello toast!'; // int duration = Toast.LENGTH_SHORT; var duration = Toast.LENGTH_SHORT; // Toast toast = Toast.makeText(context, text, duration); var toast = Toast.makeText(context, text, duration); // t...
NetUtil.jsm
eamToString(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. aSink The output stream to which to copy the data. This must be an nsIOutputStream based object. aCallback An optional function that will be called when the copy operation is
completed. The callback rec...
...fied as an nsIChannel. Note: Support for specifying an nsIInputStream as the input source was added in Gecko 5. asyncFetch( aSource, aCallback ); Parameters aSource The source to open asynchronously. This may be specified as an nsIURI, nsIFile, nsIChannel, nsIInputStream or as a string specifying the URL to open. aCallback A function that will be called when the open operation is
completed. The callback receives three parameters: the input stream containing the data, if any (implementing nsIInputStream), an nsresult status code for the open operation, and a reference to the nsIRequest object. Exceptions thrown This method throws an exception with the message "Must have a source and a callback" if either aSource or aCallback is null. Example This example shows the basic code c...
PromiseWorker.jsm
ad Setup. // Main thread // Define a custom error prototype. function CustomError(message) { this.message = message; } CustomError.fromMsg = function(msg) { return new CustomError(msg.message); }; // Register a constructor. myWorker.ExceptionHandlers['CustomError'] = CustomError.fromMsg; This is seen in a simple demo at GitHub :: PromiseWorker Custom Errors Demo - Worker Side Setup. The
complete demo is found here: GitHub :: PromiseWorker Custom Errors Demo Catching the Promise From the worker, it is not possible, as of Firefox 40, to cause the promise on the main thread catch. Any developer errors on the worker side, such as syntax errors, type errors, and so forth, will cause the promise to reject. A catch will trigger if there is a developer error in the main thread resolve or rejec...
... here: GitHub :: PromiseWorker Custom Errors Demo Catching the Promise From the worker, it is not possible, as of Firefox 40, to cause the promise on the main thread catch. Any developer errors on the worker side, such as syntax errors, type errors, and so forth, will cause the promise to reject. A catch will trigger if there is a developer error in the main thread resolve or reject callbacks.
Complete example Following example provides resolveTest function, which resolves the promise when true is passed as an argument, and rejects the promise when false is passed as an argument, and post messages to it from the main thread. Worker file myWorker.js importScripts('resource://gre/modules/workers/require.js'); let PromiseWorker = require('resource://gre/modules/workers/PromiseWorker.js'); let...
Sqlite.jsm
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 is because SQLite will need to page the database back into memory from disk. Therefore, caution should be exercised before calling this function. This returns a promise that is resolved when the operation
completes. discardCachedStatements() This function is used to discard cached statement instances, freeing memory in the process. Active cached statements will not be discarded. Therefore, it is safe to call this any time. This returns an integer count of the number of cached statements that were discarded. Table and Schema Management These APIs deal with management of tables and database schema. get...
...rocessed. }); } catch (err) { // An error occurred. console.log(err); // Error, Oh noes! if (callback) { callback(err); } } // All accounts returned successfully, so do something with them. console.log(result); // It worked! if (callback) { callback(null, accounts); } Note: the then parameters can be anonymous functions (i.e. function() ), and only are labeled as onStatement
Complete and onError for readability. This example demonstrates retrieving a row without using the onRow function parameter, and instead, using the conn.execute result. This example also demonstrates retrieving the primary key row id of the last inserted row. async function () { try { conn = await Sqlite.openConnection({ path: dbFile.path }); let statement = "INSERT INTO accounts (username, ...
Task.jsm
ou 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: 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...
... Any other unhandled exception that is thrown inside the task is reported by Components.utils.reportError. ...
Index
Guide, Localization, Mozilla This guide provides details on what a localization technical review is, what criteria are used for the technical reviews, and the process for requesting one and following its progress. 19 Localization: Frequently asked questions FAQ, Guide, Internationalization, Localization, Mozilla This page lists tweaks and tips that may not require a
complete page on its own. For more detailed documentation about localization in general, see our Localization page. 20 Localizing XLIFF files for iOS OASIS, Translate, XLIFF, XML, iOS Firefox for iOS uses the XLIFF XML-based file format to hold and transfer localization data. XLIFF (eXtensible Localisation Interchange File Format) is a localization standard governed by the OASIS stand...
...the Mercurial version control system (Hg) to manage our source code and localizations. Mercurial allows localizers to work locally (on their machines) and then push (an Hg term) changes to a remote repository, which usually is hosted on the Mozilla servers (hg.mozilla.org). Localizing current versions of Firefox, Thunderbird and SeaMonkey includes working with Mercurial. If the documentation is in
complete or you have questions, please drop by the #l10n or #hg channels on irc.mozilla.org. The Mercurial FAQ are also worth a read, should you run into trouble. 25 Localizing with Mozilla Translator Guide, Localization, Translator, l10n No summary! 26 Localizing with Pontoon Junk, Localization Pontoon is a web-based, What-You-See-Is-What-You-Get (WYSIWYG), local...
Localizing with Koala
: Add "MDC Search" Manage Search Engines... There is also a tooltip that appears when you hover over the magnifying glass icon on the right side of the bar. Requirements Mercurial, Linux, Windows or Mac OS X. Instructions Preparation Install Komodo Edit. Install Koala extension. Go to Tools > Add-ons. Search for "Koala". Click Add to Komodo Edit... Restart Komodo when the installation is
complete. You should see a new button in Komodo's toolbar, with two options: Startpage and Management. Before you can use them, you need to create a new Koala project. Creating a new project Create a new Koala project by going to File > New > New Project From Template... Choose "koala" in the Categories list. Choose "koala" in the Templates list. Choose a name for your project (e.g. l10n.kpf). Choo...
... localization files with the newest en-US reference and display the results in the sidebar on the left. Filter the files list in the sidebar to only display files containing "search" in their name. You'll see that search.properties is now marked as "modified" (before it was "added) and the entity counts have changed. Also, searchbar.dtd is no longer displayed in the "compare" view, as it has been
completely translated. Here's a quick summary of what the output of the comparison means: files: "unmodified" - the file is
completely translated. "added" - the file need to be added to the locale's file structure (it is present in en-US, but not in the locale files). "modified" - the file needs to be modified (it is present in both en-US and the locale files, but the locale's version is outdated). "r...
Localization technical reviews
ry user who downloads your localized Mozilla application receives all of your hard work in a functional product. Each QA review helps us in these ways: Ensures that your L10n work is visible and functional within the Mozilla application. Allows us to understand how each L10n team is performing their localization work. Allows us to discover potential bugs within L10n tools. Overview You've
completed most, if not all, of your localization work. The merge date for migrating from one product release channel to the next (e.g., aurora to beta, or beta to release) is rapidly approaching. You need to make sure that your work can effectively be compiled into a build for the next release channel. Here is a detailed overview of what a technical review is and who it's meant for: A technical review: ...
...uage packs. region.properties Though locales might like to specify changes from the beginning, the region.properties files will be reverted to en-US. Changes will be discussed in productization bugs filed for each locale. Search plugins Similar to the region.properties files, the list.txt file should be reverted to en-US and amended accordingly as the search plugin productization bugs are
completed. For this initial review, all XML files should be removed. String lengths in pipnss.properties There are some character limits in the security/manager/chrome/pipnss/pipnss.properties file that you should be aware of. It is best to look into each of these files to see if the localizer's strings might be too long. This is something to look for, but can be difficult to diagnose immediately. For ...
Updates
This page is not maintained frequently. Please follow our Monthly IRC Meeting for the latest updates. March 22, 2011 Firefox 4.0 has been released! This new version comes with several bug fixes and new features for MathML. Some improvements are particularly worth noting: A new HTML parser, which lets you use MathML inside non-XHTML documents.
Complete support for STIX fonts 1.0. Better rendering of mathematical symbols, especially stretchy operators. October 21, 2010 MathML 3.0 is now a W3C recommendation! June 11, 2010 STIX Fonts Version 1.0 are now compatible with trunk. May 28, 2010 STIX Fonts Version 1.0 Released. April 2010 New Web pages for the Mozilla MathML Project! Documentation is now available on MDC and wiki.mozilla.org. Feel free to
complete and improve it! M...
...ctober 21, 2010 MathML 3.0 is now a W3C recommendation! June 11, 2010 STIX Fonts Version 1.0 are now compatible with trunk. May 28, 2010 STIX Fonts Version 1.0 Released. April 2010 New Web pages for the Mozilla MathML Project! Documentation is now available on MDC and wiki.mozilla.org. Feel free to
complete and improve it! May 8, 2007 Mozilla CEO speaks out on the future of Firefox: the
complete 8,000 word interview. Interview to the APC Magazine where Mitchell Baker mentions Roger Sidje's work on MathML. June 5, 2002 Mozilla 1.0 Released "By virtue of embedding Gecko, Mozilla 1.0 and products based on Mozilla code support more web standards, more deeply, more consistently across more platforms than any others. Mozilla 1.0 features full support for HTML 4.0, XML 1.0, Resource Descrip...
Mozilla DOM Hacking Guide
Mozilla gives you the opportunity not only to use very powerful and
complete DOM support, but also to work on a world-class implementation of one of the greatest Internet technologies ever created. Mozilla's DOM is coded almost entirely in C++. Seriously hacking on it requires excellent knowledge of C++ and XPCOM, Mozilla's own component model. In this document I will try to outline the main aspects of the implementation, beginning with the Class Info mechanism, which lies at the heart of the DOM, then with the description of various interfaces and classes. Since I am myself still learning how it works, don't expect this to be a
complete reference quite yet. If you can contribute any time or knowledge to this document, it is greatly appreciated! Target audience: People interested in lear...
...inition. For us, it is: 1225 DOM_CLASSINFO_MAP_ENTRY(nsIDOMHTMLDOMImplementation) Add the new interface to the makefiles, manifests, etc. Recompile. Nuke components.reg if you build optimized. Wonder at the beauty of DOMClassInfo. How to expose a new DOM object to JavaScript Let's now go a step further. Not only do we want to add a new interface to an object, but we also want to expose a
completely new object to JavaScript. DOMClassInfo does almost everything for you, from prototypes to implementing a default ToString() method on your object. We will again take the example of the DOMImplementation object. It is accessible using document.implementation. It is defined in the W3C DOM Level 1 Core spec. The requirements include that the global constructor DOMImplementation be accessible, th...
DMD
y, symbolication will fail, but you can at least get some information. In a local build, dmd.py will be located in the directory $OBJDIR/dist/bin/. Some platforms (Linux, Mac, Android) require stack fixing, which adds missing filename, function name and line number information. This will occur automatically the first time you run dmd.py on the output file. This can take 10s of seconds or more to
complete. (This will fail if your build does not contain symbols. However, if you have crash reporter symbols for your build -- as tryserver builds do -- you can use this script instead: clone the whole repo, edit the paths at the top of resymbolicate_dmd.py and run it.) The simplest way to do this is to just run the dmd.py script on your DMD report while your working directory is $OBJDIR/dist/bin. This w...
...ive, cumulative, and scan. Another interesting one is --stacks. Acceptable values are partial (the default) and full. In the former case most blocks will not have an allocation stack trace recorded. However, because larger blocks are more likely to have one recorded, most allocated bytes should have an allocation stack trace even though most allocated blocks do not. Use --stacks=full if you want
complete information, but note that DMD will run substantially slower in that case. The options may also be put in the environment variable DMD, or set DMD to 1 to enable DMD with default options (dark-matter and partial stacks). The MOZ_DMD_SHUTDOWN_LOG environment variable, if set, triggers a DMD run at shutdown; its value must be a directory where the logs will be placed. Which processes get logged i...
JS::PerfMeasurement
ap directly to "generic events" in the Linux 2.6.31+ <linux/perf_event.h> interface, and so unfortunately are a little vague in their specification; for instance, we can't tell you exactly which level of cache you get misses for if you measure CACHE_MISSES. We also can't guarantee that all platforms will support all event types, once we have more than one back end for this interface. Here is the
complete C++-level API: PerfMeasurement::EventMask This is an enumeration defining all of the bit mask values in the above table. You bitwise-OR the ones you want together and pass them to the constructor. PerfMeasurement::ALL In a constructor call, this special value means "measure everything that can possibly be measured." PerfMeasurement::NUM_MEASURABLE_EVENTS This constant equals the total number of...
...ent object that it created in that argument slot. The jsval you receive points to a JavaScript wrapper object. To extract the C++-level PerfMeasurement object, call this function. It will return NULL if JavaScript passed in something with the wrong dynamic type. JSObject* JS::RegisterPerfMeasurement(JSContext* cx, JSObject* global) You shouldn't need to use this function, but we mention it for
completeness. It initializes the JavaScript wrapper interface for this API and pokes the constructor function into the global object you provide. ...
Leak-hunting strategies and tips
ince these entrain many smaller objects), then on smaller reference-counted object graphs, and then on any remaining individual objects or small object graphs that don't entrain other objects. Because (1) large graphs of leaked objects tend to include some objects pointed to by global variables that confuse GC-based leak detectors, which can make leaks look smaller (as in bug 99180) or hide them
completely and (2) large graphs of leaked objects tend to hide smaller ones, it's much better to go after the large graphs of leaks first. A good general pattern for finding and fixing leaks is to start with a task that you want not to leak (for example, reading email). Start finding and fixing leaks by running part of the task under nsTraceRefcnt logging, gradually building up from as little as possible...
...2) large graphs of leaked objects tend to hide smaller ones, it's much better to go after the large graphs of leaks first. A good general pattern for finding and fixing leaks is to start with a task that you want not to leak (for example, reading email). Start finding and fixing leaks by running part of the task under nsTraceRefcnt logging, gradually building up from as little as possible to the
complete task, and fixing most of the leaks in the first steps before adding additional steps. (By most of the leaks, I mean the leaks of large numbers of different types of objects or leaks of objects that are known to entrain many non-logged objects such as JS objects. Seeing a leaked GlobalWindowImpl, nsXULPDGlobalObject, nsXBLDocGlobalObject, or nsXPCWrappedJS is a sign that there could be significant...
AsyncTestUtils extended framework
This is likely to happen when I/O is involved or a potentially expensive process wants to break itself up into smaller chunks (like a search operation) so that the UI stays responsive. In the Mozilla platform, the "top level" of a program is the event loop...
...ecution on the next line when resumed. This allows 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 i...
Optimizing Applications For NSPR
vel of service across the platforms it supports. This has proven to be quite challenging, a challenge that was met to a large degree, but there is always room for improvement. The casual client may not encounter a need to know the details of the shortcomings to the level described here, but if and when clients become more sophisticated, these issues will certainly surface. This memo is by no way
complete. Multiplatform Do not call any blocking system call from a local thread. The only exception to this rule is the <tt>select()</tt> and <tt>poll()</tt> system calls on Unix, both of which NSPR has overridden to make sure they are aware of the NSPR local threads. In the combined (MxN) model, which includes NT, IRIX (sprocs), and pthreads-user, the primordial thread is always a local thread. Ther...
...nsider that the Windows stack is swapped in and out with each thread switch. The thread that created a stack variable sees his own stack variables correctly across thread switches. However, another thread does not see the data as intended because the stack has been swapped out to the shadow stack and the current thread's stack now occupies the Windows stack. This can be difficult to diagnose. For
complete cross platform portability, do not take the address of a stack variable and make that address available to another thread. For more details, see the memo on Automatic Addresses. Windows 3.1 does not support 64 bit file offsets. The NSPR 64 bit file offset APIs map to Windows 3.1 32 bit file offset APIs. You may use NSPR's 64bit file offset APIs in your Windows 3.1 applications for cross platfor...
Introduction to NSPR
n by relying on their containing process to manage most of the resources that they access. This, and the fact that threads share an address space with other threads in the same process, makes it important to remember that threads are not processes . NSPR threads are scheduled in two separate domains: Local threads are scheduled within a process only and are handled entirely by NSPR, either by
completely emulating threads on each host operating system (OS) that doesn't support threads, or by using the threading facilities of each host OS that does support threads to emulate a relatively large number of local threads by using a relatively small number of native threads. Global threads are scheduled by the host OS--not by NSPR--either within a process or across processes on the entire host. G...
... implies that the monitored invariant must be reinstated before calling PR_WaitCondVar. Failure to do this will cause subtle but painful bugs. To modify monitored data safely, a thread must be in the monitor. Since no other thread may modify or (in most cases) even observe the protected data from outside the monitor, the thread can safely make any modifications needed. When the changes have been
completed, the thread notifies the condition associated with the data and exits the monitor using PR_NotifyCondVar. Logically, each such notification promotes one thread that was waiting on the condition to a ready state. An alternate form of notification (PR_NotifyAllCondVar) promotes all threads waiting on a condition to the ready state. If no threads were waiting, the notification is a no-op. Waiting ...
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. Descri...
...ng 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_TransmitFile
Syntax #include <prio.h> PRInt32 PR_TransmitFile( PRFileDesc *networkSocket, PRFileDesc *sourceFile, const void *headers, PRInt32 hlen, PRTransmitFileFlags flags, PRIntervalTime timeout); Parameters The function has the following parameters: networkSocket A pointer to a PRFileDesc object representing the connected socket to send data over. sourceFile A pointer to a PRFileDesc object representing the file to send. headers A pointer to the buffer holding the headers to be sent before sending data. hlen Length of the headers buffer in bytes. flags One of the following flags: PR_TRANSMITFILE_KEEP_OPEN indicates that the socket will be kept open after the data is sent. ...
...n of the transmit operation. Returns A positive number indicates the number of bytes successfully written, including both the headers and the file. The value -1 indicates a failure. If an error occurs while sending the file, the PR_TRANSMITFILE_CLOSE_SOCKET flag is ignored. The reason for the failure can be obtained by calling PR_GetError. Description The PR_TransmitFile function sends a
complete file (sourceFile) across a connected socket (networkSocket). If headers is non-NULL, PR_TransmitFile sends the headers across the socket before sending the file. The enumeration PRTransmitFileFlags, used in the flags parameter, is defined as follows: typedef enum PRTransmitFileFlags { PR_TRANSMITFILE_KEEP_OPEN = 0, PR_TRANSMITFILE_CLOSE_SOCKET = 1 } PRTransmitFileFlags; ...
NSS 3.21 release notes
name string, module parameters string, NSS specific parameters string, and NSS configuration parameter string. The module represented by the module structure is not loaded. The difference with SECMOD_CreateModule is the new function handles NSS configuration parameter strings. ...
...cipher suites CKM_TLS12_KEY_SAFE_DERIVE and CKM_TLS_KDF are identifiers for additional PKCS#12 mechanisms for TLS 1.2 that are currently unused in NSS. ...
Overview of NSS
Open Source Crypto Libraries Proven Application Security Architecture If you want to add support for SSL, S/MIME, or other Internet security standards to your application, you can use Network Security Services (NSS) to implement all your security features. NSS provides a
complete open-source implementation of the crypto libraries used by AOL, Red Hat, Google, and other companies in a variety of products, including the following: Mozilla products, including Firefox, Thunderbird, SeaMonkey, and Firefox OS. AOL Instant Messenger (AIM) Open source client applications such as Evolution, Pidgin, Apache OpenOffice, and LibreOffice. Server products from Red Hat: Red Hat Directory Server, Red Hat Certificate System, and the mod_nss SSL module for the Apache web server. Server products from...
...by the Public-Key Infrastructure (X.509) working group of the IETF (known at PKIX) for a public-key infrastructure for the Internet. RSA, DSA, ECDSA, Diffie-Hellman, EC Diffie-Hellman, AES, Triple DES, DES, RC2, RC4, SHA-1, SHA-256, SHA-384, SHA-512, MD2, MD5, HMAC: Common cryptographic algorithms used in public-key and symmetric-key cryptography. FIPS 186-2 pseudorandom number generator. For
complete details, see Encryption Technologies. FIPS 140 Validation and NISCC Testing The NSS software crypto module has been validated three times for conformance to FIPS 140 at Security Levels 1 and 2. For more information, see the NSS FIPS page (Or this one). The NSS libraries passed the NISCC TLS/SSL and S/MIME test suites (1.6 million test cases of invalid input data).
Complete Software Developmen...
Python binding for NSS
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 no...
...ssages 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 written like an expect script reacting to prompts read from a pseudo terminal but it was fragile and would hang on some systems. New version uses temporary password file and writes hardcoded responses to the stdin of certuil and modutil. setup_certs now creates a new sql sytle NSS database (sq...
NSS tools : ssltab
s used with -h, two separate parts are printed for each record: the plain hex/ASCII output, and the parsed SSL output. -x Turn on hex/ASCII printing of undecoded data inside parsed SSL records. Used only with the -s option. This option uses the same output format as the -h option. -l prefix Turn on looping; that is, continue to accept connections rather than stopping after the first connection is
complete. -p port Change the default rendezvous port (1924) to another port. The following are well-known port numbers: * HTTP 80 * HTTPS 443 * SMTP 25 * FTP 21 * IMAP 143 * IMAPS 993 (IMAP over SSL) * NNTP 119 * NNTPS 563 (NNTP over SSL) Usage and Examples You can use the SSL Debugging Tool to intercept any connection information. Although you can run the tool at its most basic by issuing the ssltap comm...
...eft arrow"-- [ data ] The raw data stream is sent to standard output and is not interpreted in any way. This can result in peculiar effects, such as sounds, flashes, and even crashes of the command shell window. To output a basic, printable interpretation of the data, use the -h option, or, if you are looking at an SSL connection, the -s option. You will notice that the page you retrieved looks in
complete in the browser. This is because, by default, the tool closes down after the first connection is
complete, so the browser is not able to load images. To make the tool continue to accept connections, switch on looping mode with the -l option. The following examples show the output from commonly used combinations of options. Example 1 $ ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt Output Co...
NSS tools : ssltap
s used with -h, two separate parts are printed for each record: the plain hex/ASCII output, and the parsed SSL output. -x Turn on hex/ASCII printing of undecoded data inside parsed SSL records. Used only with the -s option. This option uses the same output format as the -h option. -l prefix Turn on looping; that is, continue to accept connections rather than stopping after the first connection is
complete. -p port Change the default rendezvous port (1924) to another port. The following are well-known port numbers: * HTTP 80 * HTTPS 443 * SMTP 25 * FTP 21 * IMAP 143 * IMAPS 993 (IMAP over SSL) * NNTP 119 * NNTPS 563 (NNTP over SSL) Usage and Examples You can use the SSL Debugging Tool to intercept any connection information. Although you can run the tool at its most basic by issuing the ssltap comm...
...eft arrow"-- [ data ] The raw data stream is sent to standard output and is not interpreted in any way. This can result in peculiar effects, such as sounds, flashes, and even crashes of the command shell window. To output a basic, printable interpretation of the data, use the -h option, or, if you are looking at an SSL connection, the -s option. You will notice that the page you retrieved looks in
complete in the browser. This is because, by default, the tool closes down after the first connection is
complete, so the browser is not able to load images. To make the tool continue to accept connections, switch on looping mode with the -l option. The following examples show the output from commonly used combinations of options. Example 1 $ ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt Output Co...
TLS Cipher Suite Discovery
ite is represented by a 16-bit number. The number of well-defined cipher suites grows with time, and no TLS implementation offers all known cipher suites at all times. An implementation that claimed to offer all defined Cipher Suites would only be able to make that claim for a short time until another new Cipher Suite was defined. At any time, any real implementation implements some subset of the
complete set of well-defined cipher suites. Each new release of a TLS implementation may contain support for new Cipher Suites not supported in previous versions. When a new version of a TLS Implementation is made available for use by applications, those applications may wish to immediately use the newly supported Cipher Suites found in the new version, without the application needing to be modified and ...
...RUint16 effectiveKeyBits; /* MAC info */ const char * macAlgorithmName; SSLMACAlgorithm macAlgorithm; PRUint16 macBits; PRUintn isFIPS : 1; PRUintn isExportable : 1; PRUintn nonStandard : 1; PRUintn reservedBits :29; } SSLCipherSuiteInfo; (Unfinished, To be
completed here) ...
NSS Tools ssltap
ion is used with -h, two separate parts are printed for each record: the plain hex/ASCII output, and the parsed SSL output. -x Turn on hex/ASCII printing of undecoded data inside parsed SSL records. Used only with the -s option. This option uses the same output format as the -h option. -l Turn on looping; that is, continue to accept connections rather than stopping after the first connection is
complete. -p port Change the default rendezvous port (1924) to another port. The following are well-known port numbers: HTTP 80 HTTPS 443 SMTP 25 FTP 21 IMAP 143 IMAPS 993 (IMAP over SSL) NNTP 119 NNTPS 563 (NNTP over SSL) Examples You can use the SSL Debugging Tool to intercept any connection information. Although you can run the tool at its most basic by issuing the sslta...
...bols: <-- [ data ] The raw data stream is sent to standard output and is not interpreted in any way. This can result in peculiar effects, such as sounds, flashes, and even crashes of the command shell window. To output a basic, printable interpretation of the data, use the -h option, or, if you are looking at an SSL connection, the -s option. You will notice that the page you retrieved looks in
complete in the browser. This is because, by default, the tool closes down after the first connection is
complete, so the browser is not able to load images. To make the tool continue to accept connections, switch on looping mode with the -l option. The following examples show the output from commonly used combinations of options. Example 1 The s and x options in this example turn on SSL parsing...
certutil
if it contains spaces. -q pqgfile Read an alternate PQG value from the specified file when generating DSA key pairs. If this argument is not used, certutil generates its own PQG value. PQG files are created with a separate DSA utility. -q curve-name Set the elliptic curve name to use when generating ECC key pairs. A
complete list of ECC curves is given in the help (-H). -r Display a certificate's binary DER encoding when listing information about that certificate with the -L option. -s subject Identify a particular certificate owner for new certificates or certificate requests. Bracket this string with quotation marks if it contains spaces. The subject ...
...hile it is being upgraded. -@ pwfile Give the name of a password file to use for the database being upgraded. Usage and Examples Most of the command options in the examples listed here have more arguments available. The arguments included in these examples are the most common ones or are used to illustrate a specific scenario. Use the -H option to show the
complete list of arguments for each command option. Creating New Security Databases Certificates, keys, and security modules related to managing certificates are stored in three related databases: o cert8.db or cert9.db o key3.db or key4.db o secmod.db or pkcs11.txt These databases must be created before certificates or keys can be generated. certutil -N -d [sql:]dire...
NSS tools : ssltap
x/ASCII output, and the parsed SSL output. -x Turn on hex/ASCII printing of undecoded data inside parsed SSL records. Used only with the -s option. This option uses the same output format as the -h option. -l prefix Turn on looping; that is, continue to accept connections rather than stopping after the first connection is
complete. -p port Change the default rendezvous port (1924) to another port. The following are well-known port numbers: * HTTP 80 * HTTPS 443 * SMTP 25 * FTP 21 * IMAP 143 * IMAPS 993 (IMAP over SSL) * NNTP 119 * NNTPS 563 (NNTP over SSL) Usage and Examples You can use the SSL D...
...data ] The raw data stream is sent to standard output and is not interpreted in any way. This can result in peculiar effects, such as sounds, flashes, and even crashes of the command shell window. To output a basic, printable interpretation of the data, use the -h option, or, if you are looking at an SSL connection, the -s option. You will notice that the page you retrieved looks in
complete in the browser. This is because, by default, the tool closes down after the first connection is
complete, so the browser is not able to load images. To make the tool continue to accept connections, switch on looping mode with the -l option. The following examples show the output from commonly used combinations of options. Example 1 $ ssltap.exe -sx -p 444 interzone.mcom.com:4...
Necko Architecture
Is and URLs. If you want to provide your own resource implementation for foo URLs, you simply need to implement the nsIURI interface. nsIIOService acts as the central point of access to URLs and channels (nsIChannel) in Necko. Given a string representation of a URL, you can ask the nsIIOService for a URL instance representing that string. Once you have a URL interface in hand (nsIURL), you have a
completely parsed representation of the original URL string, and you can query for the various parts of the URL. Handlers & channels nsIChannel provides a data access interface which allows you to read or write data from or to a URI. There is a 1-to-1 relationship between URIs and channels (if you go so far as to create a channel from a URI, which is not required if all you need is a parsed representat...
...synchronous 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 each type of I/O. Necko implements a file transport and a socket transport that the protocol implementations (channels) use to actually move bytes to and from. How do I add my own protocol handler? Adding your own protocol handler is a straig...
Tracing JIT
is always an option in tracemonkey, and on abort the monitor simply discards the recorder and its fragment and returns to monitoring mode. The monitor also keeps track of how many times it has attempted to record a trace starting at each PC value, so if a particular PC causes too many aborted recordings, the monitor blacklists the PC and will not attempt recording it any longer. If the recorder
completes recording at a backward branch back to the initial PC value that triggered recording mode, it is said to have successfully closed the loop. A closed loop is passed through the nanojit Assembler and thereby compiled to native machine code. The associated fragment is placed in the monitor's fragment table and the monitor returns to monitoring mode, with a high likelihood of immediately transitioni...
...r function written in C -- and that native happens to re-enter the interpreter to interpret yet more bytecode, and furthermore if that bytecode itself contains a hot PC that has not yet been traced, the trace monitor may be asked to begin nested recording. This is the same as normal recording mode, except that the outermost recorder is placed on a deferred-abort stack. When the innermost recorder
completes -- successfully or otherwise -- every recorder on the deferred abort stack is aborted. This process is called deep aborting the suspended recorders. Executing When the monitor interprets a backward jump to a PC that it has a compiled trace of machine code for, the monitor enters executing mode. This mode is relatively simple compared to recording mode. First the monitor allocates a native ...
JSAPI User Guide
ntime. Support for multiple JSContexts per JSRuntime will be removed in the future. If your application creates multiple runtimes, the application may need to know which runtime a context is associated with. In this case, use JS_GetRuntime. Use JS_SetContextPrivate and JS_GetContextPrivate to associate application-specific data with a context. Initializing built-in and global JS objects For a
complete list of built-in objects provided by SpiderMonkey, see JS_InitStandardClasses. The global object that an application provides to scripts largely determines what those scripts can do. For example, the Firefox browser uses its own global object, window. To change the global object for your application, call JS_SetGlobalObject. Creating and initializing custom objects In addition to using the eng...
...teUCScript or 2.) compile the script once with a call to JS_CompileScript or JS_CompileUCScript, and then execute it repeatedly with individual calls to JS_ExecuteScript. The "UC" versions of these calls provide support for Unicode-encoded scripts. An object you create using a script only can be made available only during the lifetime of the script, or can be created to persist after the script
completes execution. Ordinarily, once script execution is
complete, its objects are destroyed. In many cases, this behavior is just what your application needs. In other cases, however, you will want object persistence across scripts, or for the lifetime of your application. In these cases you need to embed object creation code directly in your application, or you need to tie the object directly to the gl...
JS_DecompileFunction
If successful, JS_DecompileFunction returns a string containing the text of the function. Otherwise, it returns NULL. ...
...Context *cx, JS::Handle<JSFunction*> fun); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. fun JS::Handle<JSFunction*> Function to decompile. Description JS_DecompileFunction generates the
complete source code of a function declaration from a function's compiled form, fun. If successful, JS_DecompileFunction returns a string containing the text of the function. Otherwise, it returns NULL. If you decompile a function that does not make a native C call, then the text created by JS_DecompileFunction is a
complete function declaration suitable for re-parsing. If you decompile a function that ...
Parser API
Recent builds of the standalone SpiderMonkey shell include a reflection of the SpiderMonkey parser, made available as a JavaScript API. This makes it easier to write tools in JavaScript that manipulate JavaScript source programs, such as syntax highlighters, static analyses, translators, compilers, obfuscators, etc. NOTE: This page describes SpiderMonkey-specific behavior and might be in
complete. Visit ESTree spec for a community AST standard that includes latest ECMAScript features and is backward-compatible with SpiderMonkey format. Example: > var expr = Reflect.parse("obj.foo + 42").body[0].expression > expr.left.property ({loc:null, type:"Identifier", name:"foo"}) > expr.right ({loc:{source:null, start:{line:1, column:10}, end:{line:1, column:12}}, type:"Literal", value:42}) It is al...
... Functions interface Function <: Node { id: Identifier | null; params: [ Pattern ]; defaults: [ Expression ]; rest: Identifier | null; body: BlockStatement | Expression; generator: boolean; expression: boolean; } A function declaration or expression. The body of the function may be a block statement, or in the case of an expression closure, an e...
SpiderMonkey 1.8.8
The Mozilla JavaScript team is pleased to announce the release of SpiderMonkey 1.8.8. You can download full source code here: INSERT-ACTUAL-LINK-WHEN-THE-RELEASE-HAPPENS (MD5 checksum: INSERT-ACTUAL-HASH-HERE). SpiderMonkey 1.8.8 is the JavaScript engine that shipped in Firefox 10.0. It continues to improve performance over previous SpiderMonkey releases, with ongoing JIT compilation work and with the introduction of type inference to enable faster JITted code. ...
... :-) ...
SpiderMonkey 17
The Mozilla JavaScript team is pleased to announce the release of SpiderMonkey 17. You can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/mozjs17.0.0.tar.gz (MD5 checksum: 20b6f8f1140ef6e47daa3b16965c9202). SpiderMonkey 17 is the JavaScript engine that shipped in Firefox 17. It continues to improve performance over previous SpiderMonkey releases, with ongoing JIT compilation work and with the introduction of type inference to enable faster JITted code. ...
...ay to replace JSD. In the future every API is going to take Handles instead of raw pointers. Exact Stack Rooting is requirement for a (moving) Generational Garbage Collector. Release Notes Errata This is a list of changes which need to be made to the release notes ASAP. Feel free to fix any problems you spot -- this is a Wiki! Don't add anything here -- this is for after the release notes are
completed. :-) ...
SpiderMonkey 24
The Mozilla JavaScript team is pleased to announce the release of SpiderMonkey 24. You can download full source code here: https://ftp.mozilla.org/pub/mozilla.org/js/mozjs-24.2.0.tar.bz2 (SHA1: ce779081cc11bd0c871c6f303fc4a0091cf4fe66) SpiderMonkey 24 is the JavaScript engine that shipped in Firefox 24. It continues to improve performance over previous SpiderMonkey releases, with a significantly improved garbage collector, a new JIT compilation mode, and other features. It also contains new language and API features described in detail below. ...
... :-) ...
SpiderMonkey 38
The Mozilla JavaScript team is pleased to announce the release of SpiderMonkey 38. SpiderMonkey 38 is the JavaScript engine that shipped in Firefox 38. It continues to improve performance over previous SpiderMonkey releases, with XXX blah blah blah. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. Or file bugs at bugzilla.mozilla.org under Product: Core, Component: JavaScript engine. ...
...ctness as primary concerns instead. JS_THREADSAFE is going away, with future versions supporting only thread-safe builds A new debugging API is on the way to replace JSD. Release Notes Errata This is a list of changes which need to be made to the release notes ASAP. Feel free to fix any problems you spot -- this is a Wiki! Don't add anything here -- this is for after the release notes are
completed. :-) ...
SpiderMonkey 45
The Mozilla JavaScript team is pleased to announce the release of SpiderMonkey 45. You can download full source code from https://ftp.mozilla.org/pub/spidermonkey/releases/45.0.2/mozjs-45.0.2.tar.bz2 SHA256: 570530b1e551bf4a459d7cae875f33f99d5ef0c29ccc7742a1b6f588e5eadbee MD5: 2ca34f998d8b5ea79d8616dd26b5fbab SpiderMonkey 45 is the JavaScript engine that shipped in Firefox 45. It continues to improve performance over previous SpiderMonkey releases. It also contains new language and API features described in detail below. ...
...edderTimeFunction (bug 1159507) JS_GetCurrentEmbedderTime (bug 1159507) JS_MayResolveStandardClass (bug 1155946) JS_GetIteratorPrototype (bug 1225392) JS_GlobalLexicalScope (bug 1202902) JS_HasExtensibleLexicalScope (bug 1202902) JS_ExtensibleLexicalScope (bug 1202902) JS_InitReflectParse (bug 987514) JS::ToPrimitive (bug 1206168) JS::GetFirstArgumentAsTypeHint (bug 1054756) JS::ObjectTo
CompletePropertyDescriptor (bug 1144366) JS_SetImmutablePrototype (bug 1211607) JS_GetOwnUCPropertyDescriptor (bug 1211607) JS_HasOwnPropertyById (bug 1211607) JS_HasOwnProperty (bug 1211607) JS_DeleteUCProperty (bug 1211607) JS::NewFunctionFromSpec (bug 1054756) JS::CompileForNonSyntacticScope (bug 1165486) JS_CheckForInterrupt (bug 1058695) JS::MapDelete (bug 1159469) JS::MapForEach (bug 11594...
Thread Sanitizer
# If it's not already in your $PATH, then uncomment this next line: #export LLVM_SYMBOLIZER="/path/to/llvm-symbolizer" # Add TSan to our compiler flags export CFLAGS="-fsanitize=thread -fPIC -pie" export CXXFLAGS="-fsanitize=thread -fPIC -pie" # Additionally, we need the TSan flag during linking. Normally, our C/CXXFLAGS would # be used during linking as...
...ymbols to symbolize TSan traces export MOZ_DEBUG_SYMBOLS=1 ac_add_options --enable-debug-symbols ac_add_options --disable-install-strip # Settings for an opt build ac_add_options --enable-optimize="-O2 -gline-tables-only" ac_add_options --disable-debug Starting the build process Now you start the build process using the regular make -f client.mk command. Starting Firefox After the build has
completed, you can start Firefox from the objdir as usual. Building only the JavaScript shell If you want to build only the JavaScript shell instead of doing a full Firefox build, the build script below will probably help you to do so. Before using it, you must of course adjust the path name for LLVM_ROOT to match your setup. Once you have adjusted everything, execute this script in the js/src/ subdirec...
Web Replay
wake up from the idle state they see the main thread has prepared a new stack to restore to, so they longjmp to the new register state and copy in the new stack's contents. Managing system resources When the child process restores a snapshot, the state of any system resources it has open is unchanged. Care must be taken to make sure these resources are coherent to the process after the restore
completes. This is done in the following ways: Instead of creating or destroying threads on demand, while recording/replaying all threads which will be needed are created during process initialization. If during the recording the content tries to create more threads than were spawned up front, then the recording fails. These threads idle until the recording/replaying content tries to 'create' them, ...
...is no JS on the stack). There is a new onPopFrame handler, which is needed when doing reverse-step-in operations. Operations on the debuggee which require interaction with the system will fail. These operations may be property accesses, evals, or object calls, and an example is accessing the font property of a CanvasRenderingContext2D. Failed operations currently just produce a placeholder "IN
COMPLETE" result. Operations on the debuggee which have side effects -- eval("x.f = 3") -- should be avoided. When the process resumes forward or backward these side effects will be lost (the process reverts to its original state) and while paused at a breakpoint these effects can cause some strange behavior -- after the above eval, getting the x.f property directly could produce a different value from ...
Gecko events
Is Supported: yes EVENT_DOCUMENT_RELOAD The document contents are being reloaded. Is Supported: yes EVENT_DOCUMENT_LOAD_STOPPED The loading of the document was interrupted. Is Supported: yes EVENT_DOCUMENT_ATTRIBUTES_CHANGED The document wide attributes of the document object have changed. Is Supported: no EVENT_DOCUMENT_CONTENT_CHANGED The cont...
... Is Supported: yes EVENT_DOCUMENT_RELOAD The document contents are being reloaded. Is Supported: yes EVENT_DOCUMENT_LOAD_STOPPED The loading of the document was interrupted. Is Supported: yes EVENT_DOCUMENT_ATTRIBUTES_CHANGED The document wide attributes of the document object have changed. Is Supported: no EVENT_DOCUMENT_CONTENT_CHANGED The contents of the document have changed. Is Sup...
Gecko Roles
ll objects sharing a single parent that have this attribute are assumed to be part of single mutually exclusive group. ROLE_COMBOBOX Represents a combo box; an edit control with an associated list box that provides a set of predefined choices. ROLE_DROPLIST Represents the calendar control. ROLE_PROGRESSBAR Represents a progress bar, dynamically showing the user the percent
complete of an operation in progress. ROLE_DIAL Represents a dial or knob whose purpose is to allow a user to set a value. ROLE_HOTKEYFIELD Represents a hot-key field that allows the user to enter a combination or sequence of keystrokes. ROLE_SLIDER Represents a slider, which allows the user to adjust a setting in given increments between minimum and maximum values. ROLE_SPINBU...
...t usually used in a scroll pane. It represents the portion of the entire data that the user can see. As the user manipulates the scroll bars, the contents of the viewport can change. ROLE_HEADER Header of a document page. ROLE_FOOTER Footer of a document page. ROLE_PARAGRAPH A paragraph of text. ROLE_RULER A ruler such as those used in word processors. ROLE_AUTO
COMPLETE A text entry having dialog or list containing items for insertion into an entry widget, for instance a list of words for completion of a text entry. ROLE_EDITBAR An editable text object in a toolbar. ROLE_ENTRY An control whose textual content may be entered or modified by the user. ROLE_CAPTION A caption describing another object. ROLE_DOCUMENT_FRAME A visual ...
XPCOM array guide
des ensures that we only append an nsINode* void NodeContainer::AddNode(nsINode* node) { mNodes.AppendObject(node); } nsCOMArray<T> can also be declared on the stack to collect a temporary list of objects and manipulate them. When the object goes out of scope, all its members are released. ...
...ipulate them. When the object goes out of scope, all its members have their destructors called. Note that if the nsTArray<T> holds pointers to objects, the objects will not be deleted (and hence not have their destructors called). You can work around this by using nsTArray<UniquePtr<T>> instead. ...
Component Internals
XPCOM sends a notification that it's beginning startup. XPCOM finds and processes the component manifest (see Component Manifests below). XPCOM finds and processes the type library manifest (see Type Library Manifests below). If there are new components, XPCOM registers them: XPCOM calls autoregistration start. XPCOM registers new components. XPCOM calls autoregistration end.
Complete XPCOM startup: XPCOM notifies that it's begun. Component manifests and type library manifests are described in the following section, XPCOM Registry Manifests. XPCOM Registry Manifests XPCOM uses special files called manifests to track and persist information about the components to the local system. There are two types of manifests that XPCOM uses to track components: Component Manifests ...
...ver. When the registration process begins, XPCOM broadcasts to all registered observers a notification that says XPCOM has begun the registration of new components. After all components are registered, another notification is fired saying that XPCOM is done with the registration step. The nsIObserver interface that handles this notification is discussed in Starting WebLock. Once registration is
complete and the notifications have fired, XPCOM is ready to be used by the application. If XPCOM registered your component, then it will be available to other parts of the XPCOM system. The XPCOM Initialization section in this chapter describes registration in more detail. Autoregistration The term autoregistration is sometimes used synonymously with registration in XPCOM. In the What Is XPCOM Registra...
Finishing the Component
create an object which implements an nsIURI interface. The two nsnull parameters passed to NewURI are used to specify the charset of the string and any base URI to use, respectively. We are assuming here that the charset of the URL string is UTF-8, and also assuming that every URL string is absolute. See the intro to the HTML 4 specification for more information about relative URLs. ...
...er_AddRefs(uri)); // if anything bad happens, just abort if (NS_FAILED(rv)) return rv; nsEmbedCString host; uri->GetHost(host); if (strcmp(hostToLoad.get(), host.get()) == 0) { // match found. Allow this nsIURI to load *_retval = PR_TRUE; return NS_OK; } node = node->next; } return NS_OK; } At this point, all of the backend work is
complete. You can of course improve this backend in many ways, but this example presents the basic creation of what is commonly referred to as a "browser helper object" like WebLock. The next chapter looks at how to tie this into the front end - specifically, how to use XPConnect to access and control this component from JavaScript in the user interface. << PreviousNext >> Copyright (c) 2003 by D...
Packaging WebLock
sers, where new installs, user configurable data, skins, and other information are related to one another and the application itself. JavaScript APIs from the XPInstall Install object download the JAR in which the installable files appear and call registration methods that tell Mozilla about the new component and the UI it uses to access the WebLock component. WebLock Installation Script is the
completetrigger installation script, which can be launched from a web page. The files themselves are stored in the JAR file weblock.jar, which is simple a ZIP file with the XPI extension that sometimes also contains an internal installation file called install.js. Once you have the component and the other resources for Weblock packaged properly (see the following section, Archiving Resources), the instal...
...isterChrome(SKIN, getFolder(cf, "weblock.xpi"),"weblock"); // perform the installation if there are no errors if (err==SUCCESS) performInstall(); else cancelInstall(err); The WebLock Trigger Script The trigger script is the script placed on a web page that actually initiates an XPInstall installation and calls the installation script that appears 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. <!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'...
Mozilla internal string guide
to code within the Mozilla codebase (code which is linked into libxul). Introduction The string classes are a library of C++ classes which are used to manage buffers of wide (16-bit) and narrow (8-bit) character strings. The headers and implementation are in the xpcom/string directory. All strings are stored as a single contiguous buffer of characters. The 8-bit and 16-bit string classes have
completely separate base classes, but share the same APIs. As a result, you cannot assign a 8-bit string to a 16-bit string without some kind of conversion helper class or routine. For the purpose of this document, we will refer to the 16-bit string classes in class documentation. Every 16-bit class has an equivalent 8-bit class: Naming convention for wide and narrow string classes Wide Narr...
...ng.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 value to the string. .Append(string) - Appends a value to the string. .Insert(string, position) - Inserts the given string before the code unit at position. .Truncate(length) - shortens the string to the given length.
Complete documentation can be found in the Appendix. Read-only strings The const attribute on a string determines if the string is writable. If a string is defined as a const nsAString then the data in the string cannot be manipulated. If one tries to call a non-const method on a const string the compiler will flag this as an error at build time. For example: void nsFoo::ReverseCharacters(nsAString& s...
XPCOM Stream Guide
per segment, is far too small for practical use. */ store.init(64, 64, null); var out = store.getOutputStream(0); NetUtil.asyncCopy(baseInputStream, out, function(status) { if (status != Components.results.NS_OK) return; /* Due to a crash, we can't create input streams until the storage output stream * has some data in it. * * Also, baseInputStream has been
completely consumed at this point, so we * shouldn't read from it anymore. (However, because baseInputStream is an * nsStringInputStream, it is also a seekable stream...so we could go to * the beginning if we wanted to.) */ var str1 = store.newInputStream(0); var d1 = new InputStream(str1); // d1 has a
complete copy of baseInputStream's original contents. var d2 = new ...
... from it anymore. (However, because baseInputStream is an * nsStringInputStream, it is also a seekable stream...so we could go to * the beginning if we wanted to.) */ var str1 = store.newInputStream(0); var d1 = new InputStream(str1); // d1 has a
complete copy of baseInputStream's original contents. var d2 = new InputStream(store.newInputStream(0)); // d2 has a
complete copy of baseInputStream's original contents. }); } Parsing a DOM document from an input stream ...
Components.utils.schedulePreciseGC
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. ...
...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. ...
IAccessibleTable
sing the attributes string returned by calling IAccessible2.attributes() on the cell object. columnIndex Returns the 0 based column index of the cell of the specified child or the index of the first column if the child spans multiple columns. Return value E_INVALIDARG if bad [in] passed, [out] value is 0. 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] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value...
...lected( [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] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is
completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selected
completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isSelected() Returns a boolean value indicating whethe...
IAccessibleTable2
hich 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] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value...
...lected( [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] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is
completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selected
completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. modelChange() Returns the type and extents describing ...
imgIDecoderObserver
etween "load" and "decode" notifications. Load notifications are fired as the image is loaded from the network or filesystem. Decode notifications are fired as the image is decoded. If an image is decoded on load and not visibly discarded, decode notifications are nested logically inside load notifications as one might expect. However, with decode-on-draw, the set of decode notifications can come
completely after the load notifications, and can come multiple times if the image is discardable. Moreover, they can be interleaved in various ways. In general, any presumed ordering between load and decode notifications should not be relied upon. Decode notifications may or may not be synchronous, depending on the situation. If imgIDecoder::FLAG_SYNC_DECODE is passed to a function that triggers a decode,...
...s useless and going away. void onStopContainer( in imgIRequest aRequest, in imgIContainer aContainer ); Parameters aRequest The request on which data is available, or null if being called for an imgIDecoder object. aContainer Missing Description onStopDecode() In theory a decode notification, but currently a load notification. Ideally this would be called when the decode is
complete. Unfortunately, this is currently the only way to signal decoding errors to consumers, and the only decoding errors that consumers care about (indeed, the only ones that they're prepared to hear about) are failures to instantiate the decoder (<img src="foo.html"> for example). Thus, currently this is just a companion to onStopRequest to signal success or failure. You probably want onStopContainer...
mozIVisitInfoCallback
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. handleR...
...o be processed. handleResult() Called for each visit added, title change, or GUID change when passed to mozIAsyncHistory.updatePlaces(). If more than one operation is done for a given visit, this method is only called once (for all changes at once). void handleResult( in mozIPlaceInfo aPlaceInfo ); Parameters aPlaceInfo The information that was entered into the database. on
Complete() Obsolete since Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) Called for each visit added, title change, or GUID change when passed to mozIAsyncHistory.updatePlaces(). void on
Complete( in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo ); Parameters aResultCode nsresult of the change indicating success or failure reason. aPlaceInfo The informa...
nsIAccessibleRole
:input@type="radio", role="radio". ROLE_COMBOBOX 46 Represents a combo box; an edit control with an associated list box that provides a set of predefined choices. It is used for html:select, xul:menulist, role="combobox". ROLE_DROPLIST 47 Represents the calendar control. It is used for date xforms:input. ROLE_PROGRESSBAR 48 Represents a progress bar, dynamically showing the user the percent
complete of an operation in progress. It is used for xul:progressmeter, role="progressbar". ROLE_DIAL 49 Represents a dial or knob whose purpose is to allow a user to set a value. ROLE_HOTKEYFIELD 50 Represents a hot-key field that allows the user to enter a combination or sequence of keystrokes. ROLE_SLIDER 51 Represents a slider, which allows the user to adjust a setting in given increments betwee...
... data that the user can see. As the user manipulates the scroll bars, the contents of the viewport can change. Also refer to ROLE_SCROLL_PANE. ROLE_HEADER 96 Header of a document page. Also refer to ROLE_FOOTER. ROLE_FOOTER 97 Footer of a document page. Also refer to ROLE_HEADER. ROLE_PARAGRAPH 98 A paragraph of text. ROLE_RULER 99 A ruler such as those used in word processors. ROLE_AUTO
COMPLETE 100 A text entry having dialog or list containing items for insertion into an entry widget, for instance a list of words for completion of a text entry. It is used for xul:textbox@auto
complete. ROLE_EDITBAR 101 An editable text object in a toolbar. ROLE_ENTRY 102 An control whose textual content may be entered or modified by the user. ROLE_CAPTION 103 A caption describing another object. ...
nsICookieService
sIURI 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 preferences are honored. ...
...n 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, in nsIChannel aCha...
nsIDownloadObserver
netwerk/base/public/nsIDownloader.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onDownload
Complete(in nsIDownloader downloader, in nsIRequest request, in nsISupports ctxt, in nsresult status, in nsIFile result); Methods onDownload
Complete() Called to signal a download that has
completed. ...
... netwerk/base/public/nsIDownloader.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onDownload
Complete(in nsIDownloader downloader, in nsIRequest request, in nsISupports ctxt, in nsresult status, in nsIFile result); Methods onDownload
Complete() Called to signal a download that has
completed. ...
nsIFaviconDataCallback
toolkit/components/places/public/nsIFaviconService.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) Method overview void on
Complete(in nsIURI aURI, in unsigned long aDataLen, [const,array,size_is(aDataLen)] in octet aData, in AUTF8String aMimeType); Methods on
Complete() Called when the required favicon's information is available. It's up to the invoking method to state if the callback is always invoked, or called on success only. Check the method documentation to ensure that. The caller will receive the most information we can gather on the icon, but it's not guaranteed that all of them will be set. For some met...
...aller will receive the most information we can gather on the icon, but it's not guaranteed that all of them will be set. For some method we could not know the favicon's data (it could just be too expensive to get it, or the method does not require we actually have any data). It's up to the caller to check aDataLen > 0 before using any data-related information like mime-type or data itself. void on
Complete( in nsIURI aURI, in unsigned long aDataLen, [const,array,size_is(aDataLen)] in octet aData, in AUTF8String aMimeType ); Parameters aURI Receives the "favicon URI" (not the "favicon link URI") associated to the requested page. This can be null if there is no associated favicon URI, or the callback is notifying a failure. aDataLen Size of the icon data in byte...
nsIHttpActivityObserver
ST_HEADER 0x5001 The HTTP request is about to be queued for sending. Observers can look at request headers in aExtraStringData ACTIVITY_SUBTYPE_REQUEST_BODY_SENT 0x5002 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 aActivityTy...
...eflect the number of bytes transmitted in that chunk. HTTP transaction activity For activity notifications of type ACTIVITY_TYPE_HTTP_TRANSACTION, there are three activities that include extra data: ACTIVITY_SUBTYPE_REQUEST_HEADER aExtraStringData contains the text of the header. ACTIVITY_SUBTYPE_RESPONSE_HEADER aExtraStringData contains the text of the response header. ACTIVITY_SUBTYPE_RESPONSE_
COMPLETE aExtraSizeData contains the total number of bytes received. See also HTTP Monitoring HTTP activity nsIHttpActivityDistributor ...
nsIMsgFolder
oolean matchOrChangeFilterDestination(in nsIMsgFolder folder,in boolean caseInsensitive); boolean confirmFolderDeletionForFilter(in nsIMsgWindow msgWindow); void alertFilterChanged(in nsIMsgWindow msgWindow); void throwAlertMsg(in string msgName, in nsIMsgWindow msgWindow); AString getStringWithFolderNameFromBundle(in string msgName); void notifyCompact
Completed(); long compareSortKeys(in nsIMsgFolder msgFolder); [noscript] void getSortKey(out octet_ptr key, out unsigned long length); boolean callFilterPlugins(in nsIMsgWindow aMsgWindow); ACString getStringProperty(in string propertyName); void setStringProperty(in string propertyName, in ACString propertyValue); boolean isAncestorOf(in nsIMsgFolder ...
...nfirmFolderDeletionForFilter() boolean confirmFolderDeletionForFilter(in nsIMsgWindow msgWindow); alertFilterChanged() void alertFilterChanged(in nsIMsgWindow msgWindow); throwAlertMsg() void throwAlertMsg(in string msgName, in nsIMsgWindow msgWindow); getStringWithFolderNameFromBundle() AString getStringWithFolderNameFromBundle(in string msgName); notifyCompact
Completed() void notifyCompact
Completed(); compareSortKeys() long compareSortKeys(in nsIMsgFolder msgFolder); getSortKey() [noscript] void getSortKey(out octet_ptr key, out unsigned long length); callFilterPlugins() boolean callFilterPlugins(in nsIMsgWindow aMsgWindow); getStringProperty() ACString getStringProperty(in string propertyName); setStringProperty...
nsIURL
ethod overview AUTF8String getCommonBaseSpec(in nsIURI aURIToCompare); AUTF8String getRelativeSpec(in nsIURI aURIToCompare); Attributes Attribute Type Description directory AUTF8String Directory portion of a URL. If the URL denotes a path to a directory and not a file, for example http://host/foo/bar/, then the Directory attribute accesses the
complete /foo/bar/ portion, and the FileName is the empty string. If the trailing slash is omitted, then the Directory is /foo/ and the file is bar (that is this is a syntactic, not a semantic breakdown of the Path). And hence don't rely on this for something to be a definitely be a file. But you can get just the leading directory portion for sure. Some characters may be escaped. fileBaseName ...
... may be escaped. fileExtension AUTF8String File extension portion of a filename in a url. If a file extension does not exist, the empty string is returned. Some characters may be escaped. fileName AUTF8String File name portion of a URL. If the URL denotes a path to a directory and not a file, for example http://host/foo/bar/, then the Directory attribute accesses the
complete /foo/bar/ portion, and the FileName is the empty string. Note that this is purely based on searching for the last trailing slash. And hence don't rely on this to be a definite file. Some characters may be escaped. filePath AUTF8String Path including the directory and file portions of a URL. For example, the filePath of "http://host/foo/bar.html#baz" is "/foo/bar.html". Some charact...
nsIUpdate
This object also contains information about the update that the front end and other application services can use to learn more about what is going on. 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 nsIUpdatePatch getPatchAt(in unsigned long index); ...
...tch. WRITE_ERROR (7) An error occurred while writing the patched application. UNEXPECTED_ERROR (8) An unanticipate type of error occurred. extensionVersion AString The add-on version of this update. Used by the extension system to track compatibility of installed add-ons with this update. Obsolete since Gecko 2.0 installDate long long The date and time at which the update was installed. is
CompleteUpdate boolean true if the update is a
complete replacement of the existing installation; false if the update is a patch representing the difference between the new version and the existing version. isSecurityUpdate boolean true if the update is a security update. If the update is a security update, a more seriously-worded user interface message is used to present the update to the user. licen...
nsIUpdateCheckListener
ps/update/nsIUpdateService.idlScriptable An interface describing an object that listens to the progress of an update check operation. This object is notified as the check continues, finishes and if it has an error. ...
...ecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void onCheck
Complete(in nsIXMLHttpRequest request, [array, size_is(updateCount)] in nsIUpdate updates, in unsigned long updateCount); void onError(in nsIXMLHttpRequest request, in nsIUpdate update); void onProgress(in nsIXMLHttpRequest request, in unsigned long position, in unsigned long totalSize); Methods onCheck
Complete() Called when the update check is
completed. void onCheck
Complete( 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. onErro...
nsIWindowMediator
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 loading, after that it fires a function. IMPORTANT: This will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing Ctrl + N and then in the new window, selecting tabs will fire the alert. var {Cc: classes, Ci: interfaces} = Components; var windowListener = { onOpenWindow: f...
...xpect this to be called from callbacks originating in native window code. They are expected to hand us comparison values which are pulled from general storage in the native widget, and may not correspond to an nsIWidget at all. For that reason this interface requires only objects one step removed from the native window (nsIWidgets), and its implementation must be very understanding of what may be
completely invalid pointers in those parameters. boolean calculateZPosition( in nsIXULWindow inWindow, in unsigned long inPosition, in nsIWidget inBelow, out unsigned long outPosition, out nsIWidget outBelow ); Parameters inWindow The window in question. inPosition Requested position one of the zLevel constants. zLevelTop send the window to the top window, zLevelBottom to the bottom. If...
nsIZipWriter
Y_EXISTS The specified path already exists in the Zip file. NS_ERROR_IN_PROGRESS The Zip writer is already performing another operation. close() Closes the Zip file. void close(); Parameters None. Exceptions thrown NS_ERROR_NOT_INITIALIZED No Zip file is open. NS_ERROR_IN_PROGRESS The Zip writer is already performing another operation. Other errors may be thrown if a failure to
complete the Zip file occurs. getEntry() Returns a specified entry or null if there is no such entry in the current Zip file. nsIZipEntry getEntry( in AUTF8String aZipEntry ); Parameters aZipEntry The path of the file entry to get. Return value An nsIZipEntry object describing the specified entry, or null if there is no such entry. hasEntry() Determines whether or not a specific entry exis...
... not exist. NS_ERROR_FILE_CORRUPTED The specified file is not a recognizable Zip file. Other errors may be thrown upon failing to open the file, such as if the file is corrupt or in an unsupported format. processQueue() Processes all queued items until the entire queue has been processed or an error occurs. The observer is notified when the first operation begins and when the last operation
completes. Any failures are passed to the observer. The Zip writer will be busy until the queue is
complete or an error halts processing of the queue early. In the event of an early failure, the remaining items stay in the queue; calling processQueue() again will continue where operations left off. void processQueue( in nsIRequestObserver aObserver, in nsISupports aContext ); Parameters aObser...
XPCOM Interface Reference
bleTextIAccessibleValueIDispatchIJSDebuggeramIInstallCallbackamIInstallTriggeramIWebInstallInfoamIWebInstallListeneramIWebInstallPromptamIWebInstallerimgICacheimgIContainerimgIContainerObserverimgIDecoderimgIDecoderObserverimgIEncoderimgILoaderimgIRequestinIDOMUtilsjsdIStackFramemozIAsyncFaviconsmozIAsyncHistorymozIColorAnalyzermozIJSSubScriptLoadermozIPersonalDictionarymozIPlaceInfomozIPlacesAuto
CompletemozIRegistrymozIRepresentativeColorCallbackmozISpellCheckingEnginemozIStorageAggregateFunctionmozIStorageAsyncStatementmozIStorageBindingParamsmozIStorageBindingParamsArraymozIStorageCompletionCallbackmozIStorageConnectionmozIStorageErrormozIStorageFunctionmozIStoragePendingStatementmozIStorageProgressHandlermozIStorageResultSetmozIStorageRowmozIStorageServicemozIStorageStatementmozIStorageStateme...
...plicationCachensIApplicationCacheChannelnsIApplicationCacheContainernsIApplicationCacheNamespacensIApplicationCacheServicensIApplicationUpdateServicensIArraynsIAsyncInputStreamnsIAsyncOutputStreamnsIAsyncStreamCopiernsIAsyncVerifyRedirectCallbacknsIAuthInformationnsIAuthModulensIAuthPromptnsIAuthPrompt2nsIAuthPromptAdapterFactorynsIAuthPromptCallbacknsIAuthPromptProvidernsIAuthPromptWrappernsIAuto
CompleteControllernsIAuto
CompleteInputnsIAuto
CompleteItemnsIAuto
CompleteListenernsIAuto
CompleteObservernsIAuto
CompleteResultnsIAuto
CompleteSearchnsIBadCertListener2nsIBidiKeyboardnsIBinaryInputStreamnsIBinaryOutputStreamnsIBlocklistPromptnsIBlocklistServicensIBoxObjectnsIBrowserBoxObjectnsIBrowserHistorynsIBrowserSearchServicensICRLInfonsICRLManagernsICachensICacheDeviceInfonsICacheEntryDescriptornsICache...
Address book sync client design
: #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). * aCookie - hmmm...cooookies! */ void OnStopAuthOperation(i...
... * * This method is called regardless of whether the the operation was * successful. * * aTransactionID - the ID for this particular request * aStatus - Status code for the sync request * aMsg - A text string describing the error (if any). */ void OnStopOperation(in PRInt32 aTransactionID, in nsresult aStatus, ...
Mail event system
getService(Components.interfaces.nsIMsgMailSession); mailSession.addListener(folderListener); // now test to see if integer stuff is firing at all // let's say "folder" is a folder we know about // first we need an at...
... copying a message into this folder or something. Then we could // verify that our listener fired by checking if listenerHasFired and // totalMessagesListenerHasFired are true // this is left as an exercise for the reader. Future plans The notification system has two duplicate methods which could be implemented with OnItemEvent/NotifyItemEvent: FolderLoaded , and DeleteOrMoveMessages
Completed . Both of these could be done by making atoms for each of these events and just firing it with NotifyItemEvent.
Completed There are some of redundant methods between the nsIMsgMailSession and the nsIFolderListener interfaces. nsIMsgMailSession also contains a number of other methods that are
completely unrealted to folder notification. It would make sense to collapse the nsIMsgMailSession sim...
Activity Manager examples
roup this activity by account process.contextObj = folder.server; // account in question gActivityManager.addActivity(process); // Step 2: Showing some progress let percent = 50; process.setProgress(percent, "Junk processing 25 of 50 messages", 25, 50); // Step 3: Removing the process and adding an Event using Process' attributes process.state = Components.interfaces.nsIActivityProcess.STATE_
COMPLETED; gActivityManager.removeActivity(process.id); let event = Components.classes["@mozilla.org/activity-event;1"].createInstance(nsIAE); // Localization is omitted, initiator is omitted event.init(folder.prettiestName + " is processed", null, "No junk found", process.startTime, // start time Date.now()); // completion time event.contextType = pr...
... // subject of the delete operation is the imap folder // wrap it in a nsvariant component nsCOMPtr<nsIWritableVariant> srcFolder = do_CreateInstance(NS_VARIANT_CONTRACTID); srcFolder->SetAsISupports(reinterpret_cast<nsISupports*>(imapFolder)); copyEvent->AddSubject(srcFolder); copyEvent->Init(NS_LITERAL_STRING("Message copy event"), initiator, NS_LITERAL_STRING("
Completed successfully"), PR_Now() / PR_USEC_PER_MSEC, // start time PR_Now() / PR_USEC_PER_MSEC); // completion time // Do not forget to increase the ref counter if needed copyEvent->SetUndoHandler(undoHandler); //////////////////////////////////////////////////////////////// //// Adding the event into Activity Manager nsCOMPtr<nsIActivityManager> activityMgr(do_Get...
Using COM from js-ctypes
ULONG* pulStreamNumber); void* SpeakStream; void* GetStatus; void* Skip; void* SetPriority; void* GetPriority; void* SetAlertBoundary; void* GetAlertBoundary; void* SetRate; void* GetRate; void* SetVolume; void* GetVolume; void* WaitUntilDone; void* SetSyncSpeakTimeout; void* GetSyncSpeakTimeout; void* Speak
CompleteEvent; void* IsUISupported; void* DisplayUI; /* end ISpVoice */ }; int main(void) { if (SUCCEEDED(CoInitialize(NULL))) { struct MyISpVoice* pVoice = NULL; HRESULT hr = CoCreateInstance(&CLSID_SpVoice, NULL, CLSCTX_ALL, &IID_ISpVoice, (void**)&pVoice); if (SUCCEEDED(hr)) { pVoice->lpVtbl->Speak(pV...
...}, { 'SetAlertBoundary': ctypes.voidptr_t }, { 'GetAlertBoundary': ctypes.voidptr_t }, { 'SetRate': ctypes.voidptr_t }, { 'GetRate': ctypes.voidptr_t }, { 'SetVolume': ctypes.voidptr_t }, { 'GetVolume': ctypes.voidptr_t }, { 'WaitUntilDone': ctypes.voidptr_t }, { 'SetSyncSpeakTimeout': ctypes.voidptr_t }, { 'GetSyncSpeakTimeout': ctypes.voidptr_t }, { 'Speak
CompleteEvent': ctypes.voidptr_t }, { 'IsUISupported': ctypes.voidptr_t }, { 'DisplayUI': ctypes.voidptr_t } // end ISpVoice ]); // FUNCTIONS // http://msdn.microsoft.com/en-us/library/windows/desktop/ms695279%28v=vs.85%29.aspx let CoInitializeEx = lib.declare('CoInitializeEx', WINABI, HRESULT, // result LPVOID, // pvReserved DWORD // dwCoInit ); // http://msdn.micro...
Standard OS Libraries
arguments in the js-ctypes code. This article allows you to find out what types to give to values/arguments by supplying links to the documentation of the OS libraries. Windows Windows has many Standard OS Libraries. The most common, found on all Windows OS version, is "WinAPI". Windows also has the "WinAPILists" and ".NET Framework" (I'm not sure if it can be accessed JSCtypes but probably). A
complete list of Windows APIs can be found at the MSDN API Index. WinAPI This is the one that is most commonly used by js-ctypes. This comes shipped by default with all installations of Windows operating systems since Win98. It's also known as WinAPI32 or just WinAPI. A list of all the functions available through this API can be found at the MSDN WinAPI Index. For finding out the values and types of arg...
...-ctypes snippets that can be copied and pasted to scratchpad Android Android runs on Java and can be used by js-ctypes through the JNI libraries. Thankfully all the js-ctypes was abstracted away into JNI.jsm. Undrestanding js-ctypes is important as arrays and other features used in JNI.jsm will require us to create arrays from the types available to the ctypes.jsm module. Although JNI is done
completely through js-ctypes, a JSM was created to abstract away the js-ctypes so developers can focus on the JNI aspect. Therefore elaboration on this technique is not done in the js-ctypes section but it is done in the JNI.jsm article. This article links to a fully funcitonal demo that can be copied and pasted into scratchpad, as a quick reference here is the link to that demo: Following the Android Toa...
Drawing and Event Handling - Plugins
alue is the native window on which the plug-in drawing occurs (NPNVnetscapeWindow). The value parameter contains the name of the plug-in. You can also use NPN_GetValue to help create a menu or dialog box for a windowless plug-in. Windowed Plug-ins The browser gives each windowed plug-in its own native window, often a child window of the the browser window itself, to draw into. The plug-in has
complete control over drawing and event handling within that window. On Mac OS, the browser does not give a windowed plug-in a native window, because the Mac OS platform does not support child windows. Instead, the windowed plug-in draws into the graphics port associated with the browser window, at the offset that the browser specifies. On MS Windows and Unix, the browser creates a child window for each...
... then show the drag highlight and handle drops when they occur within the instance rectangle. The browser is also responsible for sending the plug-in all events targeted to an instance, such as mouse clicks when the cursor is within the instance rectangle or suspend and resume events when the application is switched in and out. Events are sent to the plug-in with a call to NPP_HandleEvent; for a
complete list of event types, see the reference entry for NPEvent. Windows On Windows, the browser registers a window class and creates an instance of that class for the plug-in instance. The plug-in can then subclass the window to receive any events it needs. If the plug-in needs to receive periodic time messages (for example, for animation), it should use a timer or a separate thread. Unix On Unix, ...
Plug-in Basics - Plugins
the browser encounters a MIME type, it always searches for a registered plug-in first. If there are no matches for the MIME type, it looks for a helper application. Plug-ins and helper applications fill different application needs. For more information about helper applications, refer to the Netscape online help. How plug-ins work The life cycle of a plug-in, unlike that of an application, is
completely controlled by the web page that calls it. This section gives you an overview of the way that plug-ins operate in the browser. When Gecko starts, it looks for plugin modules in particular places on the system. For more information about where Gecko looks for plugin modules on different systems, see How Gecko Finds Plug-ins. When the user opens a page that contains embedded data of a media type...
...type="audio/x-aiff" class="hiddenObject"></object> A full-page plug-in is a visible plug-in that is not part of an HTML page. The server looks for the media (MIME) type registered by a plug-in, based on the file extension, and starts sending the file to the browser. Gecko looks up the MIME type and loads the appropriate plug-in if it finds a plug-in registered to that type. This type of plug-in
completely fills the web page. Full-page plug-ins are commonly used for document viewers, such as Adobe Acrobat. Note: The browser does not display scroll bars automatically for a full-page plug-in. The plug-in must draw its own scroll bars if it requires them. The browser user interface remains relatively constant regardless of which type of plug-in is displayed. The part of the application window th...
Debugger.Memory - Firefox Developer Tools
referent was allocated. Allocation Logging Ifdbg is a Debugger instance, and dbg.memory.trackingAllocationSites is set to true, then the JavaScript engine logs each object allocated bydbg's debuggee code. You can retrieve the current log by calling dbg.memory.drainAllocationsLog. You can control the limit on the log's size by setting dbg.memory.maxAllocationsLogLength. Censuses A census is a
complete traversal of the graph of all reachable memory items belonging to a particular Debugger's debuggees. It produces a count of those items, broken down by various criteria. Ifdbg is a Debugger instance, you can call dbg.memory.takeCensus to conduct a census of its debuggees' possessions. Accessor Properties of the Debugger.Memory.prototype Object Ifdbg is a Debugger instance, then <i>dbg</i>.memor...
...s initially undefined. Any value assigned to a debugging handler must be either a function or undefined; otherwise a TypeError is thrown. Handler functions run in the same thread in which the event occurred. They run in the compartment to which they belong, not in a debuggee compartment. onGarbageCollection(statistics) A garbage collection cycle spanning one or more debuggees has just been
completed. The statistics parameter is an object containing information about the GC cycle. It has the following properties: collections The collections property's value is an array. Because SpiderMonkey's collector is incremental, a full collection cycle may consist of multiple discrete collection slices with the JS mutator running interleaved. For each collection slice that occurred, there i...
DevTools API - Firefox Developer Tools
{toolId}-init(frame) A tool is about to be loaded. The frame is the <iframe> element that has been created for the tool. {toolId}-build(panel) The frame for a tool has loaded and the ToolPanel.build() method has been called but the asynchronous initialization has not started. The parameter is a ToolPanel object. {toolId}-ready(panel) The asynchronous initialization for a tool has
completed and it is ready to be used. The parameter is a ToolPanel object. {toolId}-selected(panel) A tool has been selected. The parameter is a ToolPanel object. {toolId}-destroy(panel) A tool is about to be destroyed. The parameter is a ToolPanel object. destroy The Toolbox is about to be destroyed. destroyed The Toolbox has been destroyed. ToolDefinition A ToolDefinition obje...
...l the promise has been fulfilled. Return value: The method should return a Promise that is resolved with the ToolPanel object once it's ready to be used. destroy() A method that is called when the toolbox is closed or the tool is unregistered. If the tool needs to perform asynchronous operations during destruction the method should return a Promise that is resolved once the process is
complete. Return value: A Promise if the function performs asynchronous operations, otherwise undefined. Example Here's a basic template for a ToolPanel implementation. // In the ToolDefintion object, do // build: (window, target) => new MyPanel(window, target), function MyPanel(window, target) { // The window object that has loaded the URL defined in the ToolDefinition this.window = wind...
Migrating from Firebug - Firefox Developer Tools
g you have to right-click into the Style side panel and choose Edit Element Style... from the context menu. The DevTools display an element {} rule for this purpose, which requires a single click into it to start editing the properties. Auto-completion of CSS As in Firebug, the Rules view provides an auto-completion for the CSS property names and their values. A few property values are not auto-
completed yet, which is tracked in bug 1337918. Copy & paste CSS Firebug's Style side panel as well as the DevTools' Rules side panel provide options within their context menus to copy the CSS rule or the style declarations. The DevTools additionally provide an option to copy the selector of a rule and copy disabled property declarations as commented out. They are missing the option to copy the whole st...
... 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 information than just the JavaScript performance. E.g. it also provides information about HTML parsing or layout. This is the part where Firebug and the DevTools differ the most, because the outputs are
completely different. While Firebug focuses on JavaScript performance and provides detailed information about JavaScript function calls during the profiling session, the Performance Tool in the DevTools offers a broad spectrum of information regarding a website's performance but doesn't go into detail regarding JavaScript function calls. View JavaScript call performance What comes nearest to Firebug's p...
Examine and edit HTML - Firefox Developer Tools
The breadcrumbs bar has its own keyboard shortcuts. Searching The Page Inspector's search box matches all markup in the current document and in any frames. To start searching the markup, click in the search box to expand it or press Ctrl + F , or Cmd + F on a Mac. ...
...re performed automatically depending on what you enter, a full text search, a CSS selector search, and an XPath search. Full text search The full text search will always be executed, independently of what you enter. That allows you to find CSS selectors and XPath expressions occurring within the text. CSS selector search You can search elements by entering a CSS selector. As you type, an auto
complete popup shows any class or ID attributes that match the current search term: Press Up and Down to cycle through suggestions, Tab to choose the current suggestion, then Enter to select the first node with that attribute. To cycle through matches, press Enter. You can cycle backwards through matches using Shift + Enter. XPath search It is also possible to search via XPaths. This allows you t...
Waterfall - Firefox Developer Tools
peration is labeled "layout" but is also sometimes called "reflow". Paint: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition". This sequence needs to fit into a single frame, since the screen isn't updated until it is
complete. It's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. For a rate of 60 frames per second, that gives the browser 16.7 milliseconds to execute the
complete flow. Importantly for responsiveness, the browser doesn't always have to go through every step: CSS animations update the page without having to run any JavaScript. Not all CSS property chang...
...or long green markers. Garbage collection Red markers in the Waterfall represent garbage collection (GC) events, in which SpiderMonkey (the JavaScript engine in Firefox) walks the heap looking for memory that's no longer reachable and subsequently releasing it. GC is relevant to performance because while it's running the JavaScript engine must be paused, so your program is suspended and will be
completely unresponsive. To help reduce the length of pauses, SpiderMonkey implements incremental GC: this means that it can perform garbage collection in fairly small increments, letting the program run in between. Sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish. In trying to avoid GC events, and especially non-incremental GC eve...
Console messages - Firefox Developer Tools
e specific HTTP request method. If the request was made as an XMLHttpRequest, there's an additional "XHR" tag indicating this. If more information is available, a disclosure triangle lets you display it, in an embedded panel that is identical to the Network Monitor request details. URI The target URI. Summary The HTTP version, response code, and time taken to
complete. Clicking the response code takes you to the reference page for that code. The context menu for network messages includes a few extra items in addition the globally-available ones: Copy link location Acts as you would expect, copying the URL into the clipboard Open in Network Panel Switches context to the Network tab, selects the request and shows you the details Resend Request ...
... invalidated by a previous write call, you force a synchronous reflow. Security The security messages shown in the Web Console help developers find potential or actual vulnerabilities in their sites. Additionally, many of these messages help educate developers because they end with a "Learn More" link that takes you to a page with background information and advice for mitigating the issue. The
complete list of security messages is as follows: Message Details Blocked loading mixed active content The page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser blocked this active content. See Mixed Content for more details. Blocked loading mixed display c...
Using images - Web APIs
t source path If you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. It's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind. Embedding an image via data: URL Another possible way to include images is via the data: url. Data URLs allow you to
completely define an image as a Base64 encoded string of characters directly in your code. var img = new Image(); // Create new img element img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw=='; One advantage of data URLs is that the resulting image is available immediately without another round trip to the server. Another potential adv...
...his does, it may help to look at the image to the right. The first four parameters define the location and size of the slice on the source image. The last four parameters define the rectangle into which to draw the image on the destination canvas. Slicing can be a useful tool when you want to make compositions. You could have all elements in a single image file and use this method to composite a
complete drawing. For instance, if you want to make a chart you could have a PNG image containing all the necessary text in a single file and depending on your data could change the scale of your chart fairly easily. Another advantage is that you don't need to load every image individually, which can improve load performance. Example: Framing an image In this example, we'll use the same rhino as in the ...
Clipboard - Web APIs
sions using the Permissions API and the "clipboard-read" or "clipboard-write" permission as appropriate. Note: In reality, at this time browser requirements for access to the clipboard vary significantly. Please see the section Clipboard availability for details. All of the Clipboard API methods operate asynchronously; they return a Promise which is resolved once the clipboard access has been
completed. The promise is rejected if clipboard access is denied. The clipboard is a data buffer that is used for short-term, data storage and/or data transfers, this can be between documents or applications It is usually implemented as an anonymous, temporary data buffer, sometimes called the paste buffer, that can be accessed from most or all programs within the environment via defined programming i...
... the system clipboard. This asynchronous operation signals that it's finished by resolving the returned Promise. writeText() Writes text to the system clipboard, returning a Promise which is resolved once the text is fully copied into the clipboard. Clipboard availability The asynchronous clipboard API is a relatively recent addition, and the process of implementing it in browsers is not yet
complete. Due to both potential security concerns and technical complexities, the process 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 clipbo...
Document: DOMContentLoaded event - Web APIs
Bubbles Yes Cancelable Yes (although specified as a simple event that isn't cancelable) Interface Event Event handler property None A different event, load, should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate. Synchronous JavaScript pauses parsing of the DOM. ...
...fully loaded and parsed'); }); Delaying DOMContentLoaded <script> document.addEventListener('DOMContentLoaded', (event) => { console.log('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. function doSomething() { console.info('DOM loaded'); } if (document.readyState === 'loading') { // Loading hasn't finished yet document.addEventListener('DOMContentLoaded', doSomething); } else { // `DOMContentLoaded` has already fired doSomething(); } Live example HTML...
Document.getElementsByClassName() - Web APIs
You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). Syntax var elements = document.getElementsByClassName(names); // or: var elements = rootElement.getElementsByClassName(names); elements is a live HTMLCollection of found elements. ...
... JavaScript // getElementsByClassName only selects elements that have both given classes var allOrangeJuiceByClass = document.getElementsByClassName('orange juice'); var result = "document.getElementsByClassName('orange juice')"; for (var i=0, len=allOrangeJuiceByClass.length|0; i<len; i=i+1|0) { result += "\n " + allOrangeJuiceByClass[i].textContent; } // querySelector only selects full
complete matches var allOrangeJuiceQuery = document.querySelectorAll('.orange.juice'); result += "\n\ndocument.querySelectorAll('.orange.juice')"; for (var i=0, len=allOrangeJuiceQuery.length|0; i<len; i=i+1|0) { result += "\n " + allOrangeJuiceQuery[i].textContent; } document.getElementById("resultArea").value = result; Result Specifications Specification Status Comment ...
EffectTiming - Web APIs
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". duration Optional The number of milliseconds each iteration of the animation takes to
complete. Defaults to 0. Although this is technically optional, keep in mind that your animation will not run if this value is 0. easing Optional The rate of the animation's change over time. Accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The numbe...
....42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The number of milliseconds to delay after the end of an animation. This is primarily of use when sequencing animations based on the end time of another animation. Defaults to 0. fill Optional Dictates whether the animation's effects should be reflected by the element(s) prior to playing ("backwards"), retained after the animation has
completed playing ("forwards"), or both. Defaults to "none". iterationStart Optional Describes at what point in the iteration the animation should start. 0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration. Defaults to 0.0. iterations Optional The number of times the animation s...
Element.animate() - Web APIs
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". duration Optional The number of milliseconds each iteration of the animation takes to
complete. Defaults to 0. Although this is technically optional, keep in mind that your animation will not run if this value is 0. easing Optional The rate of the animation's change over time. Accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The numbe...
....42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The number of milliseconds to delay after the end of an animation. This is primarily of use when sequencing animations based on the end time of another animation. Defaults to 0. fill Optional Dictates whether the animation's effects should be reflected by the element(s) prior to playing ("backwards"), retained after the animation has
completed playing ("forwards"), or both. Defaults to "none". iterationStart Optional Describes at what point in the iteration the animation should start. 0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration. Defaults to 0.0. iterations Optional The number of times the animation s...
ElementCSSInlineStyle.style - Web APIs
tyle attribute returns a CSSStyleDeclaration object which is also read-only. Instead, styles can be set by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...') as using elt.style.cssText = '...' or elt.setAttribute('style', '...') sets the
complete inline style for the element by overriding the existing inline styles. Note that the property names are in camel-case and not kebab-case while setting the style using elt.style.<property> (i.e., elt.style.fontSize, not elt.style.font-size). A style declaration is reset by setting it to null or an empty string, e.g., elt.style.color = null. Internet Explorer requires setting it to an empty string...
...d does not do anything when setting it to null. Examples // Set multiple styles in a single statement elt.style.cssText = "color: blue; border: 1px solid black"; // Or elt.setAttribute("style", "color:red; border: 1px solid blue;"); // Set specific style while leaving other inline style values untouched elt.style.color = "blue"; Getting style information 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. To get the values of all CSS properties for an element you should use Window.getComputedStyle() instead. The following code snippet demons...
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. The activate events in service workers use waitUntil() to buff...
...re 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. 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). Syntax extendableEvent.waitUntil(promise); Parameters A Promise. Return value undefined. Example Using wai...
FileReader.result - Web APIs
The result types are described below. Method Description readAsArrayBuffer() The result is a JavaScript ArrayBuffer containing binary data. ...
... 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. ...
FileSystemEntry.copyTo() - Web APIs
ntry.copyTo(newParent[, newName][, successCallback][, errorCallback]); Parameters newParent A FileSystemDirectoryEntry object specifying the destination directory for the copy operation. newName Optional If this parameter is provided, the copy is given this string as its new file or directory name. successCallback Optional A function which is called when the copy operation is succesfully
completed. Receives a single input parameter: a FileSystemEntry based object providing the copied item's new details. errorCallback Optional An optional callback which is executed if an error occurs while copying the items. There's a single parameter: a FileError describing what went wrong. Return value undefined. Errors FileError.INVALID_MODIFICATION_ERR The requested operation involves an impo...
...g. Return value undefined. Errors FileError.INVALID_MODIFICATION_ERR The requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. FileError.QUOTA_EXCEEDED_ERR The operation exceeded the user's storage quota, or there isn't enough storage space left to
complete the operation. Example This example shows how a temporary log file might be moved into a more permanent "log" directory. workingDirectory.getFile("tmp/log.txt", {}, function(fileEntry) { workingDirectory.getDirectory("log", {}, function(dirEntry) { fileEntry.copyTo(dirEntry); }, handleError); }, handleError); Browser compatibility The compatibility table on this page is generated fr...
FileSystemEntry.moveTo() - Web APIs
(newParent[, newName][, successCallback][, errorCallback]); Parameters newParent A FileSystemDirectoryEntry object specifying the destination directory for the move operation. newName Optional If this parameter is provided, the entry is renamed to have this string as its new file or directory name. successCallback Optional A function which is called when the move operation is succesfully
completed. Receives a single input parameter: a FileSystemEntry based object providing the moved item's new details. errorCallback Optional An optional callback which is executed if an error occurs while moving the items. There's a single parameter: a FileError describing what went wrong. Return value undefined. Errors FileError.INVALID_MODIFICATION_ERR The requested operation involves an imposs...
...g. Return value undefined. Errors FileError.INVALID_MODIFICATION_ERR The requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. FileError.QUOTA_EXCEEDED_ERR The operation exceeded the user's storage quota, or there isn't enough storage space left to
complete the operation. Example This example shows how a temporary log file might be moved into a more permanent "log" directory when it exceeds a megabyte in size. workingDirectory.getFile("tmp/log.txt", {}, function(fileEntry) { fileEntry.getMetadata(function(metadata) { if (metadata.size > 1048576) { workingDirectory.getDirectory("log", {}, function(dirEntry) { fileEntry.moveTo(...
Using the Gamepad API - Web APIs
Querying the Gamepad object As you can see, the gamepad events discussed above include a gamepad property on the event object, which returns a Gamepad object. We can use this in order to determine which gamepad (i.e., its ID) had caused the event, since multiple gamepads might be connected at once. We can do much more with the Gamepad...
...You can find a working demo and look at the full source code on Github. var haveEvents = 'ongamepadconnected' in window; var controllers = {}; function connecthandler(e) { addg...
GlobalEventHandlers.ontransitionend - Web APIs
The ontransitionend property of the GlobalEventHandlers mixin is an EventHandler that processes transitionend events. The transitionend event is sent to when a CSS transition
completes. If the transition is removed from its target node before the transition
completes execution, the transitionend event won't be generated. One way this can happen is by changing the value of the transition-property attribute which applies to the target. Another is if the display attribute is set to none. ...
...ionend event won't be generated. One way this can happen is by changing the value of the transition-property attribute which applies to the target. Another is if the display attribute is set to none. Syntax var transitionEndHandler = target.ontransitionend; target.ontransitionend = Function Value A Function to be called when a transitionend event occurs indicating that a CSS transition has
completed on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: a TransitionEvent object describing the event which occurred; the event's TransitionEvent.elapsedTime property's value should be the same as the value of transition-duration. elapsedTime does not include time prior to the transitio...
HTMLElement - Web APIs
r by assigning an event listener to the oneventname property of this interface. 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. Also available via the onanimationcancel property. animationend Fired when an animation has
completed normally. Also available via the onanimationend property. animationiteration Fired when an animation iteration has
completed. Also available via the onanimationiteration property. animationstart Fired when an animation starts. Also available via the onanimationstart property. Input events beforeinput Fired when the value of an <input>, <select>, or <textarea> element is about to be ...
...Fired when a pointer is moved into an element's hit test boundaries. Also available via the onpointerover property. pointerup Fired when a pointer is no longer active. Also available via the onpointerup property. Transition events transitioncancel Fired when a CSS transition is canceled. Also available via the ontransitioncancel property. transitionend Fired when a CSS transition has
completed. Also available via the ontransitionend property. transitionrun Fired when a CSS transition is first created. Also available via the ontransitionrun property. transitionstart Fired when a CSS transition has actually started. Also available via the ontransitionstart property. Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe ...
HTMLImageElement - Web APIs
accepts optional width and height parameters. When called without parameters, new Image() is equivalent to calling document.createElement("img"). Properties Inherits properties from its parent, HTMLElement. HTMLImageElement.alt A DOMString that reflects the alt HTML attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. HTMLImageElement.
complete Read only Returns a Boolean that is true if the browser has finished fetching the image, whether successful or not. That means this value is also true if the image has no src value indicating an image to load. HTMLImageElement.crossOrigin A DOMString specifying the CORS setting for this image element. See CORS settings attributes for further details. This may be null if CORS is not used. HTM...
...'HTMLImageElement' in that specification. Recommendation A constructor (with 2 optional parameters) has been added. The following properties are now obsolete: name, border, align, hspace, vspace, and longdesc. The following properties are now unsigned long, instead of long: height, and width. The following properties have been added: crossorigin, naturalWidth, naturalHeight, and
complete. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLImgElement' in that specification. Obsolete The lowSrc property has been removed. The following properties are now long, instead of DOMString: height, width, hspace, and vspace. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLImgElement' in that specification. Obsol...
HTMLMediaElement.seekToNextFrame() - Web APIs
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). Possible uses for this method include filtering and editing of video content. This method returns immediately, returning a Promise, whose fulfillment handler is called when the seek operation 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 seek
CompletePromise = HTMLMediaElement.seekToNextFrame(); HTMLMediaEl...
...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 seek
CompletePromise = 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. ...
Drag Operations - Web APIs
This event will fire if the drag was successful[1] or if it was cancelled. However, you can use the dropEffect property to determine which drop operation occurred. If the dropEffect property has the value none during a dragend, then the drag was cancelled. Otherwise, the effect specifies whi...
... drag was cancelled for other reasons such as an invalid drop target, or if it was successful. A drop can occur inside the same window or over another application. The dragend event will always fire regardless. The event's screenX and screenY properties will be set to the screen coordinates where the drop occurred. After the dragend event has finished propagating, the drag and drop operation is
complete. [1]: In Gecko, dragend is not dispatched if the source node is moved or removed during the drag (e.g. on drop or dragover). Bug 460801 See also HTML Drag and Drop API (Overview) Dragging and Dropping Multiple Items Recommended Drag Types HTML5 Living Standard: Drag and Drop ...
IDBObjectStore.autoIncrement - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.autoIncrement); // Make a request t...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.autoIncrement); // Make a request to add our newItem object to the object store var objectStoreReques...
IDBObjectStore.clear() - Web APIs
se in the db variable. ...
...quest.result; // Clear all the data form the object store clearData(); }; function clearData() { // open a read/write db transaction, ready for clearing the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.on
complete = function(event) { note.innerHTML += '<li>Transaction
completed.</li>'; }; transaction.onerror = function(event) { note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // Make a request to clear all the data out of the object store var objectStoreRequest = objectStore.clear(); objectStoreReques...
IDBObjectStore.get() - Web APIs
ble. ...
.../ Run the getData() function to get the data from the database getData(); }; function getData() { // open a read/write db transaction, ready for retrieving the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.on
complete = function(event) { note.innerHTML += '<li>Transaction
completed.</li>'; }; transaction.onerror = function(event) { note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // Make a request to get a record by key from the object store var objectStoreRequest = objectStore.get("Walk dog"); objectStor...
IDBObjectStore.indexNames - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.indexNames); // Make a request to ad...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.indexNames); // Make a request to add our newItem object to the object store var objectStoreRequest = ...
IDBObjectStore.keyPath - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.keyPath); // Make a request to add ou...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.keyPath); // Make a request to add our newItem object to the object store var objectStoreRequest = obje...
IDBObjectStore.name - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.name); // Make a request to add our n...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.name); // Make a request to add our newItem object to the object store var objectStoreRequest = objectS...
IDBObjectStore.transaction - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.transaction); // Make a request to ...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.transaction); // Make a request to add our newItem object to the object store var objectStoreRequest ...
IDBObjectStore - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // make a request to add our newItem object to the object store var objectStor...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); objectStoreRequest.onsucc...
IDBTransaction.abort() - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem...
IDBTransaction.db - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to ...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[...
IDBTransaction.mode - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to ...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[...
IDBTransaction.objectStore() - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to ...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[...
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. Syntax timeRemaining = IdleDeadline.timeRemaining(); Return value A DOMHighResTimeStamp value (which is a floating-point number) representin...
... Specifications Specification Status Comment Cooperative Scheduling of Background Tasks Proposed Recommendation ...
Checking when a deadline is due - Web APIs
s, 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 in
complete.</li>'; return; } In this segment, we check to see if the form fields have all been filled in. If not, we drop a message into our developer notifications pane (see the bottom left of the app UI) to tell the user what is going on, and exit out of the function. This step is mainly for browsers that don't support HTML form validation (I have used the required attribute in my HTML to force va...
...Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to t...
KeyframeEffectOptions - Web APIs
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". duration Optional The number of milliseconds each iteration of the animation takes to
complete. Defaults to 0. Although this is technically optional, keep in mind that your animation will not run if this value is 0. easing Optional The rate of the animation's change over time. Accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The numbe...
....42, 0, 0.58, 1)". Defaults to "linear". endDelay Optional The number of milliseconds to delay after the end of an animation. This is primarily of use when sequencing animations based on the end time of another animation. Defaults to 0. fill Optional Dictates whether the animation's effects should be reflected by the element(s) prior to playing ("backwards"), retained after the animation has
completed playing ("forwards"), or both. Defaults to "none". iterationStart Optional Describes at what point in the iteration the animation should start. 0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration. Defaults to 0.0. iterations Optional The number of times the animation s...
Payment Request API - Web APIs
users. It is not a new way for paying for things; rather, it's a way for users to select their preferred way of paying for things, and make that information available to a merchant. Payment Request concepts and usage Many problems related to online shopping-cart abandonment can be traced to checkout forms, which can be difficult and time consuming to fill out and often require multiple steps to
complete. The Payment Request API is meant to reduce the number of steps needed to
complete a payment online, potentially doing away with checkout forms. It aims to make the checkout process easier, by remembering a user's details, which are then passed along to a merchant hopefully without requiring a HTML form. Advantages of using the Payment Request API with "basic-card" (card-based payments): Fast...
...rom the merchant (e.g, "we only accept Visa or Mastercard"), or allow the user to say which is their default/favorite card. To request a payment, a web page creates a PaymentRequest object in response to a user action that initiates a payment, such as clicking a "Purchase" button. The PaymentRequest allows the web page to exchange information with the user agent while the user provides input to
complete the transaction. You can find a
complete guide in Using the Payment Request API. Note: The API is available inside cross-origin <iframe> elements only if they have had the allowpaymentrequest attribute set on them. Interfaces PaymentAddress An object that contains address information; used for billing and shipping addresses, for example. PaymentRequest An object that provides the API f...
PerformanceNavigationTiming.loadEventEnd - Web APIs
The loadEventEnd read-only property returns a timestamp which is equal to the time when the load event of the current document is
completed. Syntax perfEntry.loadEventEnd; Return Value A timestamp representing the time when the load event of the current document is
completed. Example The following example illustrates this property's usage. ...
... // Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.domInteractive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } ...
PerformanceNavigationTiming - Web APIs
igationTiming.loadEventEnd and PerformanceEntry.startTime properties. This interface also extends following PerformanceResourceTiming properties for navigation performance entry types by qualifying and constraining them as follows: PerformanceResourceTiming.initiatorTypeRead only Returns "navigation". The interface also supports the following properties: PerformanceNavigationTiming.dom
Complete Read only A DOMHighResTimeStamp representing a time value equal to the time immediately before the browser sets the current document readiness of the current document to
complete. PerformanceNavigationTiming.domContentLoadedEventEnd Read only A DOMHighResTimeStamp representing the time value equal to the time immediately after the current document's DOMContentLoaded event
completes. Perform...
...formanceNavigationTiming.domInteractive Read only A DOMHighResTimeStamp representing a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive. PerformanceNavigationTiming.loadEventEnd Read only A DOMHighResTimeStamp representing the time when the load event of the current document is
completed. PerformanceNavigationTiming.loadEventStart Read only A DOMHighResTimeStamp representing the time value equal to the time immediately before the load event of the current document is fired. PerformanceNavigationTiming.redirectCount Read only A number representing the number of redirects since the last non-redirect navigation under the current browsing context. If there was no redirect, or...
RTCIceTransport: gatheringstatechange event - Web APIs
mple creates a handler for gatheringstatechange events on each RTCRtpSender associated with a given RTCPeerConnection. ...
....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 Between BrowsersThe definition of 'gatheringstatechange' in that specification. Candidate Recommendation ...
RTCIceTransport.ongatheringstatechange - Web APIs
determine the new state, examine the value of gatheringState. The gathering state indicates whether or not the ICE agent has begun gathering candidates, and if so, whether or not gathering has finished. Its possible values are: "new" The RTCIceTransport is newly created and has not yet started to gather ICE candidates. "gathering" The transport is in the process of gathering candidates. "
complete" The transport has finished gathering ICE candidates and has sent the end-of-candidates indicator to the remote device. The transport won't gather any further candidates unless an ICE restart occurs, at which point the gathering process starts over from scratch. Example This snippet establishes a handler for the gatheringstatechange event that checks to see if the state has changed to "comple...
... Example This snippet establishes a handler for the gatheringstatechange event that checks to see if the state has changed to "
complete", indicating that all ICE candidates from both the local and remote peers have been received and processed. var iceTransport = pc.getSenders()[0].transport.transport; iceTransport.ongatheringstatechange = function(event) { if (iceTransport.gatheringState == "
complete") { allCandidatesReceived(pc); } } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceTransport.ongatheringstatechange' in that specification. Candidate Recommendation Initial specification. ...
RTCIceTransport - Web APIs
ers the following properties: component Read only The ICE component being used by the transport. The value is one of the strings from the RTCIceTransport enumerated type: "RTP" or "RTSP". gatheringState Read only A DOMString indicating which gathering state the ICE agent is currently in. The value is one of those included in the RTCIceGathererState enumerated type: "new", "gathering", or "
complete". role Read only Returns a DOMString whose value is one of the members of the RTCIceRole enumerated type: "controlling" or "controlled"; this indicates whether the ICE agent is the one that makes the final decision as to the candidate pair to use or not. state Read only A DOMString indicating what the current state of the ICE agent is. The value of state can be used to determine whether the...
...olled"; this indicates whether the ICE agent is the one that makes the final decision as to the candidate pair to use or not. state Read only A DOMString indicating what the current state of the ICE agent is. The value of state can be used to determine whether the ICE agent has made an initial connection using a viable candidate pair ("connected"), made its final selection of candidate pairs ("
completed"), or in an error state ("failed"), among other states. See the RTCIceTransportState enumerated type for a
complete list of states. Methods Also includes methods from EventTarget, the parent interface. getLocalCandidates() Returns an array of RTCIceCandidate objects, each describing one of the ICE candidates that have been gathered so far for the local device. These are the same candidate...
RTCIceTransportState - Web APIs
candidates pairings to consider, and there may still be gathering underway on one or both of the two devices. The transport may revert from the "connected" state to the "checking" state if either peer decides to cancel consent to use the selected candidate pair, and may revert to "disconnected" if there are no candidates left to check but one or both clients are still gathering candidates. "
completed" The transport has finished gathering local candidates and has received a notification from the remote peer that no more candidates will be sent. In addition, all candidate pairs have been considered and a pair has been selected for use. If consent checks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" The ICE agent has determined that conne...
...ed. This is a terminal state, indicating that the connection cannot be achieved or maintained. "closed" The transport has shut down and is no longer responding to STUN requests. Usage notes If an ICE restart occurs, the candidate gathering and connectivity check process is started over again; this will cause a transition from the "connected" state if the restart occurred while the state was "
completed". If the restart occured during a transient "disconnected" state, the state transitions to "checking" The disconnected state "disconnected" is a transient state that occurs when the connection between the two peers fails in a manner that the WebRTC infrastructure can automatically correct once the connection is available again. It is not a failure state. Instead, you can think of "disconnecte...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
ng 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. That 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. Note: This property's value is determined once the local ...
...when // it isn't known whether it supports trickle ICE. ...
RTCPeerConnection.setRemoteDescription() - Web APIs
s called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). Because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by calling setRemoteDescription() does not immediately take effect. Instead, the current connection configuration remains in place until negotiation is
complete. Only then does the agreed-upon configuration take effect. Syntax aPromise = rtcPeerConnection.setRemoteDescription(sessionDescription); Parameters sessionDescription An RTCSessionDescriptionInit or RTCSessionDescription which specifies the remote peer's current offer or answer. This value is an offer or answer received from the remote peer through your implementation of The sessionDes...
...w offer. In either of those two cases, we're at the beginning of the negotiation process, and the offer is set as the remote description. On the other hand, if we're in the middle of an ongoing negotiation and an offer is passed into setRemoteDescription(), the ICE agent automatically begins an ICE rollback in order to return the connection to a stable signaling state, then, once the rollback is
completed, sets the remote description to the specified offer. This begins a new negotiation session, with the newly-established offer as the starting point. Upon starting the new negotiation with the newly-established offer, the local peer is now the callee, even if it was previously the caller. This happens instead of throwing an exception, thereby reducing the number of potential errors which might oc...
RTCPeerConnection.signalingState - Web APIs
ate, which indicates where in the process of signaling the exchange of offer and answer the connection currently is. Constant Description "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 th...
...emote 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 established by calling setLocalDescription(). "closed" The connection is closed. Note: This value moved into the RTCPeerConnectionState enum...
RTCPeerConnection: signalingstatechange event - Web APIs
Connection.onsignalingstatechange Examples Given an RTCPeerConnection, pc, and an updateStatus() function that presents status information to the user, this code sets up an event handler to let the user know when the ICE negotiation process finishes up. ...
...w when the ICE negotiation process finishes up. pc.addEventListener("signalingstatechange", ev => { switch(pc.signalingState) { case "stable": updateStatus("ICE negotiation
complete"); break; } }, false); Using onsignalingstatechange, it looks like this: pc.onsignalingstatechange = ev => { switch(pc.signalingState) { case "stable": updateStatus("ICE negotiation
complete"); break; } }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'signalingstatechange' in that specification. Candidate Recommendation ...
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); Parameter...
...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) { console.log("Stream
complete"); reader.cancel(); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; ...
Using the Screen Capture API - Web APIs
e You can then use the captured stream, captureStream, for anything that accepts a stream as input. The examples below show a few ways to make use of the stream. Visible vs logical display surfaces For the purposes of the Screen Capture API, a display surface is any content object that can be selected by the API for sharing purposes. ...
...How these are handled by the Screen Capture API varies. Generally, the browser will provide an image which obscures the hidden portion of the logical display surface in some way, such as by blurring or replacing with a color or pattern. ...
Service Worker API - Web APIs
access to push notifications and background sync APIs. Service worker concepts and usage A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you
complete control over how your app behaves in certain situations (the most obvious one being when the network is not available). A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can'...
... The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker. Your service worker can respond to requests using the FetchEvent event. You can modify the response to these requests in any way you want, using the FetchEvent.respondWith method. Note: Because oninstall/onactivate could take a while to
complete, the service worker spec provides a waitUntil method, once this is called oninstall or onactivate, it passes a promise. Functional events are not dispatched to the service worker until the promise is successfully resolved. For a
complete tutorial to show how to build up your first basic example, read Using Service Workers. Other use case ideas Service workers are also intended to be used for ...
Using readable streams - Web APIs
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) { console.log("Stream
complete"); para.textContent = result; return; } charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read()...
...em); result += chunk; // Read some more, and call this function again return reader.read().then(processText); }); } Closing and cancelling streams We've already shown examples of using ReadableStreamDefaultController.close() to close a reader. As we said before, any previously enqueued chunks will still be read, but no more can be enqueued because it is closed. If you wanted to
completely get rid of the stream and discard any enqueued chunks, you'd use ReadableStream.cancel() or ReadableStreamDefaultReader.cancel(). Teeing a stream Sometimes you might want to read a stream twice, simultaneously. 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...
SubtleCrypto.decrypt() - Web APIs
ationError 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 decrypts ciphertext using AES in CTR mode. Note that counter must match the value that was used for encryption. See the
complete code on GitHub. function decryptMessage(key, ciphertext) { return w...
...ust 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-CTR", counter, length: 64 }, key, ciphertext ); } AES-CBC This code decrypts ciphertext using AES in CBC 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-CBC", iv: iv }, key, ciphertext ); } AES-GCM This code decrypts ciphertext using AES in 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.
SubtleCrypto.deriveBits() - Web APIs
ion, or if the algorithm requested for the derived key doesn't define a key length. Supported algorithms See the Supported algorithms section of the deriveKey() documentation. Examples Note: You can try the working examples on GitHub. ECDH In this example Alice and Bob each generate an ECDH key pair. We then use Alice's private key and Bob's public key to derive a shared secret. See the
complete code on GitHub. async function deriveSharedSecret(privateKey, publicKey) { const sharedSecret = await window.crypto.subtle.deriveBits( { name: "ECDH", namedCurve: "P-384", public: publicKey }, privateKey, 128 ); const buffer = new Uint8Array(sharedSecret, 0, 5); const sharedSecretValue = document.querySelector(".ecdh .derived-bits-value"); sharedSecre...
...on.addEventListener("click", () => { // Alice then generates a secret using her private key and Bob's public key. // Bob could generate the same secret using his private key and Alice's public key. deriveSharedSecret(alicesKeyPair.privateKey, bobsKeyPair.publicKey); }); }); PBKDF2 In this example we ask the user for a password, then use it to derive some bits using PBKDF2. See the
complete code on GitHub. let salt; /* Get some key material to use as input to the deriveBits 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", ...
SubtleCrypto.deriveKey() - Web APIs
this makes it harder for an attacker to use brute-force to discover the key using a dictionary attack. PBKDF2 is specified in RFC 2898. Examples Note: You can try the working examples on GitHub. ECDH In this example Alice and Bob each generate an ECDH key pair, then exchange public keys. They then use deriveKey() to derive a shared AES key, that they could use to encrypt messages. See the
complete code on GitHub. /* Derive an AES key, given: - our ECDH private key - their ECDH public key */ function deriveSecretKey(privateKey, publicKey) { return window.crypto.subtle.deriveKey( { name: "ECDH", public: publicKey }, privateKey, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"] ); } async function agreeSharedSecretKey() {...
... encrypt(alicesSecretKey); }); // Bob can use his copy to decrypt the message. let decryptButton = document.querySelector(".ecdh .decrypt-button"); decryptButton.addEventListener("click", () => { decrypt(bobsSecretKey); }); } PBKDF2 In this example we ask the user for a password, then use it to derive an AES key using PBKDF2, then use the AES key to encrypt a message. See the
complete code on GitHub. /* Get some key material to use as input to the deriveKey method. The key material is a password supplied by the user. */ function getKeyMaterial() { let password = window.prompt("Enter your password"); let enc = new TextEncoder(); return window.crypto.subtle.importKey( "raw", enc.encode(password), "PBKDF2", false, ["deriveBits", "deriveKey"] ); } asy...
SubtleCrypto.generateKey() - Web APIs
en the following exception is encountered: SyntaxError Raised when the result is a CryptoKey of type secret or private but keyUsages is empty. SyntaxError Raised when the result is a CryptoKeyPair and its privateKey.usages attribute is empty. Examples Note: You can try the working examples on GitHub. RSA key pair generation This code generates an RSA-OAEP encryption key pair. See the
complete code on GitHub. let keyPair = window.crypto.subtle.generateKey( { name: "RSA-OAEP", modulusLength: 4096, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["encrypt", "decrypt"] ); Elliptic curve key pair generation This code generates an ECDSA signing key pair. See the
complete code on GitHub. let keyPair = window.crypto.subtle.generateKey( { n...
...Array([1, 0, 1]), hash: "SHA-256" }, true, ["encrypt", "decrypt"] ); Elliptic curve key pair generation This code generates an ECDSA signing key pair. See the
complete code on GitHub. let keyPair = window.crypto.subtle.generateKey( { name: "ECDSA", namedCurve: "P-384" }, true, ["sign", "verify"] ); HMAC key generation This code generates an HMAC signing key. See the
complete code on GitHub. let key = window.crypto.subtle.generateKey( { name: "HMAC", hash: {name: "SHA-512"} }, true, ["sign", "verify"] ); AES key generation This code generates an AES-GCM encryption key. See the
complete code on GitHub. let key = window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"] ); Specifications ...
SubtleCrypto.unwrapKey() - Web APIs
ncrypted using the AES-KW algorithm, with a key derived from a password. To unwrap, we ask the user for the password and use PBKDF2 and some salt to derive the AES-KW unwrapping key. The salt needs to be the same as the salt that was used to derive the original AES-KW key wrapping key. Once we have the unwrapping key we pass it into unwrapKey() with the wrapped key and other parameters. See the
complete code on GitHub. /* Salt that is to be used in derivation of the key-wrapping key, alongside the password the user supplies. This must match the salt value that was originally used to derive the key. */ const saltBytes = [89,113,135,234,168,204,21,36,55,93,1,132,242,242,192,156]; /* The wrapped key itself. */ const wrappedKeyBytes = [171,223,14,36,201,233,233,120,164,68,217,192,226,80, 224,3...
...nwrapping key. The salt needs to be the same as the salt that was used to derive the original AES-GCM key wrapping key. Once we have the unwrapping key we pass it into unwrapKey() with the wrapped key and other parameters. Note that when using AES-GCM we have to pass the iv value into unwrapKey(), and this must be the same as the iv that was used in the corresponding wrapKey() operation. See the
complete code on GitHub. /* Salt that is to be used in derivation of the key-wrapping key, alongside the password the user supplies. This must match the salt value that was originally used to derive the key. */ const saltBytes = [180,253,62,216,47,35,90,55,218,233,103,10,172,143,161,177]; /* IV that is to be used in decrypting the key to unwrap. This must the the same IV that was originally used to encr...
WebGL2RenderingContext.fenceSync() - Web APIs
The WebGL2RenderingContext.fenceSync() method of the WebGL 2 API creates a new WebGLSync object and inserts it into the GL command stream. Syntax WebGLSync gl.fenceSync(condition, flags); Parameters condition A GLenum specifying the condition that must be met to set the sync object's state to signaled. Must be gl.SYNC_GPU_COMMANDS_
COMPLETE. ...
... Editor's Draft Initial definition for WebGL. ...
WebGL2RenderingContext.getSyncParameter() - Web APIs
ync object. pname A GLenum specifying which information to return. Possible values: gl.OBJECT_TYPE: Returns a GLenum indicating the type of the sync object (always gl.SYNC_FENCE). gl.SYNC_STATUS: Returns a GLenum indicating the status of the sync object (gl.SIGNALED or gl.UNSIGNALED). ...
... Editor's Draft Initial definition for WebGL. ...
Adding 2D content to a WebGL context - Web APIs
This project uses the glMatrix library to perform its matrix operations, so you will need to include that in your project. We're loading a copy from a CDN in our HTML's <head>. ...
...nits from the camera to be rendered. Then we establish the position of the square plane by loading the identity position and translating away from the camera by 6 units. After that, we bind the square's vertex buffer to the attribute the shader is using for aVertexPosition and we tell WebGL how to pull the data out of it. Finally we draw the object by calling the drawArrays() method. View the
complete code | Open this demo on a new page Matrix utility operations Matrix operations might seem complicated but they are actually pretty simple if you take them one step at a time. Generally people use a matrix library rather than writing their own. In our case we're using the popular glMatrix library. See also Matrices on WebGLFundamentals Matrices on Wolfram MathWorld Matrix on Wikipedia ...
Lifetime of a WebRTC session - Web APIs
tablishing the connection The Internet is big. Really big. It's so big that years ago, smart people saw how big it was, how fast it was growing, and the limitations of the 32-bit IP addressing system, and realized that something had to be done before we ran out of addresses to use, so they started working on designing a new 64-bit addressing system. But they realized that it would take longer to
complete the transition than 32-bit addresses would last, so other smart people came up with a way to let multiple computers share the same 32-bit IP address. Network Address Translation (NAT) is a standard which supports this address sharing by handling routing of data inbound and outbound to and from devices on a LAN, all of which are sharing a single WAN (global) IP address. The problem for users is t...
...he communication channel, and to handle errors. Information needed in order to set up the connection: the IP addressing and port information needed for the peers to be able to talk to one another. Media capability negotiation: what codecs and media data formats can the peers understand? These need to be agreed upon before the WebRTC session can begin. Only once signaling has been successfully
completed can the true process of opening the WebRTC peer connection begin. It's worth noting that the signaling server does not actually need to understand or do anything with the data being exchanged through it by the two peers during signaling. The signaling server is, in essence, a relay: a common point which both sides connect to knowing that their signaling data can be transferred through it. The s...
Using WebRTC data channels - Web APIs
g of outbound data. This is handled automatically. While there's no way to control the size of the buffer, you can learn how much data is currently buffered, and you can choose to be notified by an event when the buffer starts to run low on queued data. This makes it easy to write efficient routines that make sure there's always data ready to send without over-using memory or swamping the channel
completely. <<<write more about using bufferedAmount, bufferedAmountLowThreshold, onbufferedamountlow, and bufferedamountlow here>>> ... Understanding message size limits For any data being transmitted over a network, there are size restrictions. At a fundamental level, the individual network packets can't be larger than a certain value (the exact number depends on the network and the transport layer ...
...call the library and react to errors it returns. When two users running Firefox are communicating on a data channel, the message size limit is much larger than when Firefox and Chrome are communicating because Firefox implements a now deprecated technique for sending large messages in multiple SCTP messages, which Chrome does not. Chrome will instead see a series of messages that it believes are
complete, and will deliver them to the receiving RTCDataChannel as multiple messages. Messages smaller than 16kiB can be sent without concern, as all major user agents handle them the same way. Beyond that, things get more complicated. Concerns with large messages Currently, it's not practical to use RTCDataChannel for messages larger than 64kiB (16kiB if you want to support cross-browser exchange of d...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
adding a fourth component to the vector: the perspective component, called w. The value of w is applied by dividing each of the other three components by it to get the final position or vector; that is, for a coordinate given as (x, y, z, w), the point in the 3D space is actually (x/w, y/w, z/w, 1) or simply (x/w, y/w, z/w). If you're not using perspective, w is always 1. In that situation, the
complete coordinates for an object located at (1, 0, 3) are (1, 0, 3, 1). But the location isn't enough to describe an object in 3D space because an object's state in space isn't only about its location, but about its rotation or facing direction, otherwise known as its orientation. The orientation can be represented using a 3D vector, which is typically normalized so that its length is 1.0. For example,...
...reate(); quat.fromEuler(axisQuat, pitchAngle, yawAngle, rollAngle); mat4.fromQuat(rotateMatrix, axisQuat); mat4.multiply(viewMatrix, viewMatrix, rotateMatrix); This converts the Euler angles for pitch, yaw, and roll into a quaternion representing all three rotations. This is then converted into a rotation transform matrix; then, finally, the view matrix is multiplied by the rotation transform to
complete the rotations. Representing 3D with WebXR WebXR takes 3D graphics a step further, allowing them to be presented using special visual hardware such as goggles or a headset to create 3D graphics that appear to actually exist in three dimensions, potentially within the context of the real world (in the case of augmented reality). In order to perceive depth, it's necessary to have two perspectives...
Fundamentals of WebXR - Web APIs
, and the combined view blends the two into a 3D shape. Generally, only the horizontal FOV is specifically defined and managed by applications. For more details about this, see The optics of 3D in Rendering and the WebXR frame animation callback. Field of view and mixed reality devices To achieve a wide enough field of view that the user's eyes are tricked into believing that the virtual world
completely surrounds them, the FOV needs to at least approach the width of the binocular vision area. Basic headsets typically start around 90? or so, while the best headsets generally have a field of view of around 150?. Because the FOV is a matter of the size of the lenses and how close they are to the user's eyes, there are limitations on how wide the FOV can get without installing lenses into the user...
... real world, overlaying the rendered image on top of the user's physical environment. This is done without digitally reproducing the world, as would be necessary with a full headset. Instead, the display surface is transparent, and if not displaying anything is essentially identical to wearing regular eyeglasses. When objects are drawn, they are drawn onto the goggles' lenses, either partially or
completely blocking the physical environment from being seen through the obscured portion of the lens. CAVEs A Cave Automated Virtual Environment (CAVE) is an immersive VR environment in which the scene is projected or otherwise displayed on the walls (as well as possibly the ceiling and/or floor), thus
completely surrounding the user with the simulation and allowing them to be immersed in the scene. Th...
Web Authentication API - Web APIs
orResponse.clientDataJSON and AuthenticatorAttestationResponse.attestationObject. The PublicKeyCredential is sent back to the server using any desired formatting and protocol (note that the ArrayBuffer properties need to be be base64 encoded or similar). ...
...Assuming that the checks pan out, the server will store the new public key associated with the user's account for future use -- that is, whenever the user desires to use the public key for authentication. ...
Web Locks API - Web APIs
b app running in multiple tabs wants to ensure that only one tab is syncing data between the network and Indexed DB, each 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...
...0 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. await do_something_with_lock...
Window: popstate event - Web APIs
cument's scroll position, the values of form inputs, and other such data. If new-entry has a different Document object than current-entry, the browsing context is updated so that its document property refers to the document referred to by new-entry, and the context's name is updated to match the context name of the now-current document. ...
... has a different Document object than current-entry, the browsing context is updated so that its document property refers to the document referred to by new-entry, and the context's name is updated to match the context name of the now-current document. Each form control within new-entry's Document that has auto
complete configured with its autofill field name set to off is reset. See The HTML auto
complete attribute for more about the auto
complete field names and how auto
complete works. If new-entry's document is already fully loaded and ready--that is, its readyState is
complete--and the document is not already visible, it's made visible and the pageshow event is fired at the document with the PageTransitionEvent's persisted attribute set to true. The document's URL is set to that of new-entry. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
The queueMicrotask() method, which is exposed on the Window or Worker interface, queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. 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. The importance of microtasks comes in its ability to perfo...
...y useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. queueMicrotask() is exposed on the WindowOrWorkerGlobalScope mixin. Syntax scope.queueMicrotask(function); Parameters function A function to be executed when the browser engine determines it is safe to call your code. Enqueued microtasks are executed after all pending tasks have
completed but before yielding control to the browser's event loop. Return value undefined. Examples self.queueMicrotask(() => { // function contents here }) Taken from the queueMicrotask spec: MyElement.prototype.loadData = function (url) { if (this._cache[url]) { queueMicrotask(() => { this._setData(this._cache[url]); this.dispatchEvent(new Event("load")); }); } else { ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
var __nativeSI__ = window.setInterval; window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. ...
...ut() has terminated. For example: function foo() { console.log('foo has been called'); } setTimeout(foo, 0); console.log('After setTimeout'); Will write to the console: After setTimeout foo has been called This is because even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. Currently-executing code must
complete before functions on the queue are executed, thus the resulting execution order may not be as expected. Deferral of timeouts during pageload Starting in Firefox 66, Firefox will defer firing setTimeout and setInterval timers while the current tab is loading. Firing is deferred until the MainThread is deemed idle (similar to window.requestIdleCallback()), or until the load event is fired. Maxi...
XMLHttpRequest.readyState - Web APIs
s 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. UNSENT The XMLHttpRequest client has been created, but the open() method hasn't been called yet. OPENED open() method has been invoked. During this state, the request headers can be set using the setRequestHeader() method and the send() method can be called which will initiate the fetch. HEADERS_RECEIVED send() has been called and the response headers have been received. LOADING ...
...he request headers can be set using the setRequestHeader() method and the send() method can be called which will initiate the fetch. HEADERS_RECEIVED send() has been called and the response headers have been received. LOADING Response's body is being received. If responseType is "text" or empty string, responseText will have the partial text response as it loads. DONE The fetch operation is
complete. This could mean that either the data transfer has been
completed successfully or failed. The state names are different in versions of Internet Explorer earlier than 11. Instead of UNSENT, OPENED, HEADERS_RECEIVED, LOADING and DONE, the names READYSTATE_UNINITIALIZED (0), READYSTATE_LOADING (1), READYSTATE_LOADED (2), READYSTATE_INTERACTIVE (3) and READYSTATE_
COMPLETE (4) are used. Example ...
XMLHttpRequestEventTarget.onload - Web APIs
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. ...
...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. ...
XMLHttpRequestEventTarget.onprogress - Web APIs
Event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
... Event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
XRInputSource - Web APIs
izes when the user squeezes their fist, that action is called a primary squeeze action. A primary squeeze action should correspond to a gripping act in reality, such as taking hold of an object or pressing a trigger on a tool or weapon. When a squeeze action begins, such as by the user pressing the trigger or tightening their grip, a squeezestart event is sent to the XRSession. Once the action is
completed and the user has released the trigger or the grip, a squeeze event is sent. This is followed by a squeezeend, which is also sent if the action is aborted rather than
completed. If the device has a button or other pressable input control, it is a primary input source, and this button is a primary action. A primary action may occur when the user presses a button, clicks on a touchpad or the top b...
...a button or other pressable input control, it is a primary input source, and this button is a primary action. A primary action may occur when the user presses a button, clicks on a touchpad or the top button of a thumb stick, or uses a hand gesture or spoken command that invokes the button-like action. When a primary action begins, a selectstart event is sent to the XRSession. When the action has
completed (such as when the user releases the button), a select event is sent. Finally, once that is done--or if the user aborts the action--a selectend event is sent to the session object. An action may be aborted either by the user in some device-specific fashion or if the input device is disconnected before the action is
completed. Local coordinate system Each input source has its own local coordina...
XRInputSourceEvent() - Web APIs
. Permitted values are listed under Event types below. eventInitDict An object based on the XRInputSourceEventInit dictionary which contains the values to assign to the new event's properties. Return value A new XRInputSourceEvent object representing the event described by the given type and eventInitDict. Event types select Sent to an XRSession when the sending input source has fully
completed a primary action. selectend Sent to an XRSession when an ongoing primary action ends, or when an input source with an ongoing primary action has been disconnected from the system. selectstart Sent to an XRSession when an input source begins its primary action, indicating that the user has begun a command-like input, such as pressing a trigger or button, issuing a spoken command, tapping on a...
...en an input source with an ongoing primary action has been disconnected from the system. selectstart Sent to an XRSession when an input source begins its primary action, indicating that the user has begun a command-like input, such as pressing a trigger or button, issuing a spoken command, tapping on a touchpad, or the like. squeeze Sent to an XRSession when the sending input source has fully
completed a primary squeeze action. squeezeend Sent to an XRSession when an ongoing primary squeeze action ends or when an input source with an ongoing primary squeeze action is disconnected. squeezestart Sent to an XRSession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. Examples The code below sets up handlers f...
XRInputSourceEvent - Web APIs
e 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. selectend Sent to an XRSession when an ongoing primary action ends, or when an input source with an ongoing primary action has been disconnected from the system. selectstart Sent to an XRSession when an input source begins its primary action, indicating that the user has begun a command-like input, such as pressing a trigger or button, issuing a spoken command, tapping on a...
...en an input source with an ongoing primary action has been disconnected from the system. selectstart Sent to an XRSession when an input source begins its primary action, indicating that the user has begun a command-like input, such as pressing a trigger or button, issuing a spoken command, tapping on a touchpad, or the like. squeeze Sent to an XRSession when the sending input source has fully
completed a primary squeeze action. squeezeend Sent to an XRSession when an ongoing primary squeeze action ends or when an input source with an ongoing primary squeeze action is disconnected. squeezestart Sent to an XRSession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. Examples The code below sets up handlers f...
XRSession.onsqueezeend - Web APIs
The XRSession interface's onsqueezeend event handler property is a function to be invokedn when the squeezeend event sent to an XRSession when a primary squeeze action ends. This is sent immediately after the squeeze event, which announces the successful completion of the squeeze action. The squeezeend event handler is where you handle closing out a squeeze action whether it was successfully
completed or not. To learn more about how the sequence of squeeze events works, see Primary squeeze actions in Inputs and input sources. Syntax xrSession.onsqueezeend = squeezeendHandlerFunction; Value A function to be invoked whenever the XRSession receives a squeezestart event, indicating the ending of a primary squeeze action. Examples This snippet of code adds a simple handler for the squeezeend ...
...s takes care of the situation in which the drag is aborted or canceled. xrSession.onsqueezeend = event => { if (event.inputSource.handedness == user.handedness) { let targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, myRefSpace; if (user.heldObject) { cancelObjectDrag(user.heldObject); } } }; This code presumes that if the user actually intentionally
completed the drag, user.heldObject will be null here. That's because (in this example, at least) the handler for the squeeze event has already dropped the object into its new location and then cleared the value of heldObject to indicate that the user is no longer holding anything. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.onsque...
ARIA: textbox role - Accessibility
ria-owns attribute, it indicates when that element has focus, when it is part of a composite widget such as a combobox. For example, in a combobox, focus may remain on the textbox while the value of aria-activedescendant on the textbox element refers to a descendant of a popup listbox that is controlled by the textbox.This attribute must be updated programmatically as the focus changes. ...
... none (default): Predicted text is not offered. If list or both is set, the aria-controls and aria-haspopup attributes should also be included. The value of aria-controls is the ID of the element that contains the list of suggested values. ...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
's what happens when the play() function gets called: The box's list of CSS classes is reset to simply "box". This has the effect of removing any other classes currently applied to the box, including the "changing" class that handles animation. In other words, we're removing the animation effect from the box. However, changes to the class list don't take effect until the style recomputation is
complete and a refresh has occurred to reflect the change. To be sure that the styles are recalculated, we use window.requestAnimationFrame(), specifying a callback. Our callback gets executed just before the next repaint of the document. The problem for us is that because it's before the repaint, the style recomputation hasn't actually happened yet! So... Our callback cleverly calls requestAnimationFra...
... repaint will start the animation once again. Of course, we also need to add an event handler to our "Run" button so it'll actually do something: document.querySelector(".runButton").addEventListener("click", play, false); Result Stopping an animation Simply removing the animation-name applied to an element will make it jump or cut to its next state. If instead you'd like the animation to
complete and then come to a stop you have to try a different approach. The main tricks are: Make your animation as self-contained as possible. This means you should not rely on animation-direction: alternate. Instead you should explicitly write a keyframe animation that goes through the full animation in one forward repetition. Use JavaScript and clear the animation being used when the animationiterat...
Using CSS animations - CSS: Cascading Style Sheets
onfigure the actual appearance of the animation, which is done using the @keyframes at-rule as described in Defining the animation sequence using keyframes below. The sub-properties of the animation property are: animation-name Specifies the name of the @keyframes at-rule describing the animation's keyframes. animation-duration Configures the length of time that an animation should take to
complete one cycle. animation-timing-function Configures the timing of the animation; that is, how the animation transitions through keyframes, by establishing acceleration curves. animation-delay Configures the delay between the time the element is loaded and the beginning of the animation sequence. animation-iteration-count Configures the number of times the animation should repeat; you can specif...
...2334 New loop started at time 6.00600004196167 Ended: elapsed time is 9.234000205993652 Note that the times are very close to, but not exactly, those expected given the timing established when the animation was configured. Note also that after the final iteration of the animation, the animationiteration event isn't sent; instead, the animationend event is sent. The HTML Just for the sake of
completeness, here's the HTML that displays the page content, including the list into which the script inserts information about the received events: <h1 id="watchme">Watch me move</h1> <p> This example shows how to use CSS animations to make <code>H1</code> elements move across the page. </p> <p> In addition, we output some text each time an animation event fires, so you can see them in action. ...
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
use the content keyword as the flex-basis. This will result in the flex-basis being taken from the content size even if there is a width set on the item. This is a newer keyword and has less browser support, however you can always get the same effect by using auto as the flex-basis and ensuring that your item does not have a width set, in order that it will be auto-sized. If you want flexbox to
completely ignore the size of the item when doing space distribution then set flex-basis to 0. This essentially tells flexbox that all the space is up for grabs, and to share it out in proportion. We will see examples of this as we move on to look at flex-grow. The flex-grow property The flex-grow property specifies the flex grow factor, which determines how much the flex item will grow relative to the ...
...iner -- increasing it to 700px for example -- and then reduce the flex item width, you can see that the first two items will wrap, however they will never become smaller than that min-content size. As the box gets smaller space is then just removed from the third item. In practice the shrinking behaviour does tend to give you reasonable results. You don't usually want your content to disappear
completely or for boxes to get smaller than their minimum content, so the above rules make sense in terms of sensible behaviour for content that needs to be shrunk in order to fit into a container. Giving items different flex-shrink factors In the same way as flex-grow, you can give flex-items different flex-shrink factors. This can help change the default behaviour if, for example, you want an item to ...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
justification, and also distribution of space along an axis. The reason that the Box alignment properties remain detailed in the flexbox specification as well as being in box alignment is to ensure that completion of the flexbox spec is not held up by box alignment, which has to detail these methods for all layout types. There is a note in the flexbox spec stating that in the future, once it is
completed, the definitions in Box Alignment Level 3 will supersede those of flexbox: "Note: While the alignment properties are defined in CSS Box Alignment [CSS-ALIGN-3], Flexible Box Layout reproduces the definitions of the relevant ones here so as to not create a normative dependency that may slow down advancement of the spec. These properties apply only to flex layout until CSS Box Alignment Level 3 ...
...ions of the relevant ones here so as to not create a normative dependency that may slow down advancement of the spec. These properties apply only to flex layout until CSS Box Alignment Level 3 is finished and defines their effect for other layout modes. Additionally, any new values defined in the Box Alignment module will apply to Flexible Box Layout; in otherwords, the Box Alignment module, once
completed, will supercede the definitions here." In a later article in this series -- Aligning items in a flex container -- we will take a thorough look at how the Box Alignment properties apply to flex items. The gap properties A recent addition to the Box Alignment specification has been the row-gap and column-gap properties, along with the shorthand gap. These properties were initially defined in t...
Variable fonts guide - CSS: Cascading Style Sheets
riable ones are like and how they compare. Standard (or Static) fonts In the past, a typeface would be produced as a number of individual fonts, and each font would represent one specific width/weight/style combination. So you would have separate files for 'Roboto Regular', 'Roboto Bold', and 'Roboto Bold Italic' -- meaning that you could end up with 20 or 30 different font files to represent a
complete typeface (it could be several times that for a large typeface that has different widths as well). In such a scenario, in order to use a typeface for typical use on a site for body copy you would need at least four files: regular, italic, bold, and bold italic. If you wanted to add more weights, like a lighter one for captions or a heavier one for extra emphasis, that would mean several more file...
...erformance reasons alone). A note about font families, weights, and variants You might notice that we have been talking about having a specific font file for every weight and style (i.e. bold and italic and bold italic), rather than relying upon the browser to synthesize them. The reason for this is that most typefaces have very specific designs for bolder weights and italics that often include
completely different characters (lower-case 'a' and 'g' are often quite different in italics, for example). In order to most accurately reflect the typeface design and avoid differences between browsers and how they may or may not synthesize the different styles, it's more accurate to load the specific font files where needed when using a non-variable font. You may also find that some variable fonts come...
Grid template areas - CSS: Cascading Style Sheets
s="header">Header</div> <div class="sidebar">Sidebar</div> <div class="content">Content</div> <div class="footer">Footer</div> </div> Using this method we do not need to specify anything at all on the individual grid items, everything happens on our grid container. We can see the layout described as the value of the grid-template-areas property. Leaving a grid cell empty We have
completely filled our grid with areas in this example, leaving no white space. However you can leave grid cells empty with this method of layout. To leave a cell empty use the full stop character, '.'. If I want to only display the footer directly under the main content I would need to leave the three cells underneath the sidebar empty. .header { grid-area: hd; } .footer { grid-area: ft; } .conte...
...This means that you must have the same number of cells for each row, if empty with a full stop character demonstrating that the cell is to be left empty. You will also create an invalid grid if your areas are not rectangular. Redefining the grid using media queries As our layout is now contained in one part of the CSS, this makes it v...
The stacking context - CSS: Cascading Style Sheets
ked according to the same rules previously explained. Importantly, the z-index values of its child stacking contexts only have meaning in this parent. Stacking contexts are treated atomically as a single unit in the parent stacking context. In summary: Stacking contexts can be contained in other stacking contexts, and together create a hierarchy of stacking contexts. Each stacking context is
completely independent of its siblings: only descendant elements are considered when stacking is processed. Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context. Note: The hierarchy of stacking contexts is a subset of the hierarchy of HTML elements because only certain elements create stac...
...e In this example, every positioned element creates its own stacking context, because of their positioning and z-index values. The hierarchy of stacking contexts is organized as follows: Root DIV #1 DIV #2 DIV #3 DIV #4 DIV #5 DIV #6 It is important to note that DIV #4, DIV #5 and DIV #6 are children of DIV #3, so stacking of those elements is
completely resolved within DIV#3. Once stacking and rendering within DIV #3 is
completed, the whole DIV #3 element is passed for stacking in the root element with respect to its sibling's DIV. Notes: DIV #4 is rendered under DIV #1 because DIV #1's z-index (5) is valid within the stacking context of the root element, while DIV #4's z-index (6) is valid within the stacking context of DIV #3. So, DIV #...
Using CSS transitions - CSS: Cascading Style Sheets
transform 1s; } You can play with this here: http://jsfiddle.net/9h261pzo/291/ Detecting the start and completion of a transition You can use the transitionend event to detect that an animation has finished running. This is a TransitionEvent object, which has two added properties beyond a typical Event object: propertyName A string indicating the name of the CSS property whose transition
completed. elapsedTime A float indicating the number of seconds the transition had been running at the time the event fired. This value isn't affected by the value of transition-delay. As usual, you can use the addEventListener() method to monitor for this event: el.addEventListener("transitionend", updateTransition, true); You detect the beginning of a transition using transitionrun (fires before ...
... Specifications Specification Status Comment CSS Transitions Working Draft Initial definition ...
Getting Started - Developer guides
State === XMLHttpRequest.DONE) { // Everything is good, the response was received. } else { // Not ready yet. } The full list of the readyState values is documented at XMLHTTPRequest.readyState and is as follows: 0 (uninitialized) or (request not initialized) 1 (loading) or (server connection established) 2 (loaded) or (request received) 3 (interactive) or (processing request) 4 (
complete) or (request finished and response is ready) Next, check the HTTP response status codes of the HTTP response. The possible codes are listed at the W3C. In the following example, we differentiate between a successful and unsuccessful AJAX call by checking for a 200 OK response code. if (httpRequest.status === 200) { // Perfect! } else { // There was a problem with the request. // Fo...
... This is repeated every 5 seconds, using a setInterval() call. The idea would be that a server-side script of some kind would continually update the text file with new timestamps, and our XHR code would be used to report the latest timestamp on the client-side. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>XHR log...
Cross-browser audio basics - Developer guides
lash and Silverlight code require that the user has the appropriate plugin installed, and that the browser cannot guarantee the security aspects of code running on those plugin platforms. These are also deprecated, and soon won't work in any modern browsers. Manipulating the Audio Element with JavaScript In addition to being able to specify various attributes in HTML, the <audio> element comes
complete with several properties and methods that you can manipulate via JavaScript. Given the following HTML: <audio id="my-audio" src="audiofile.mp3"> ... </audio> You can grab the <audio> element like this: var myAudio = document.getElementById('my-audio'); Alternatively, you can create a new element. Here's an example of creating an <audio> element, setting the media to play, playing and paus...
...vent to detect should you want to determine whether the media is ready to play. You could, for example, disable custom controls until this event occurs. myAudio.addEventListener("canplay", function() { //audio is ready to play }); canplaythrough canplaythrough is similar to canplay but it lets you know that the media is ready to be played all the way through (that is to say that the file has
completely downloaded, or it is estimated that it will download in time so that buffering stops do not occur). myAudio.addEventListener("canplaythrough", function() { //audio is ready to play all the way through }); Media loading event order To recap, the order of the media loading events are: loadstart > durationchange > loadedmetadata > loadeddata > progress > canplay > canplaythrough Loading int...
Mouse gesture events - Developer guides
pdated status information. The event's delta value represents the amount by which the gesture has moved since the MozMagnifyGestureStart or MozMagnifyGestureUpdate event. Note: This event is sent whenever the movement of the user's fingers exceeds the number of pixels indicated by the browser.gesture.pinch.threshold preference. MozMagnifyGesture The MozMagnifyGesture event is sent when the user
completes a "pinch" gesture. If you only care about the end results of the pinch gesture, you can simply watch for this event; however, if you want to provide feedback during the handling of the gesture, you should also watch the MozMagnifyGestureStart and MozMagnifyGestureUpdate events. The delta value is the cumulative change over the course of handling the entire sequence of magnify gesture events. Moz...
...de updated status information. The event's delta value represents the amount by which the gesture has moved since the MozRotateGestureStart or MozRotateGestureUpdate event. Note: This event is sent whenever the movement of the user's fingers exceeds the number of pixels indicated by the browser.gesture.pinch.threshold preference. MozRotateGesture The MozRotateGesture event is sent when the user
completes a rotate gesture. If you only care about the end results of the rotate gesture, you can simply watch for this event; however, if you want to provide feedback during the handling of the gesture, you should also watch the MozRotateGestureStart and MozRotateGestureUpdate events. The delta value is the cumulative change over the course of handling the entire sequence of rotate gesture events. Event ...
Rich-Text Editing in Mozilla - Developer guides
us on the button itself, which breaks the editing flow. ...
... Resources mozilla.org's rich-text editing Specification mozilla.org's rich-text editing Demo Converting an app using document.designMode from IE to Mozilla at mozilla.org designMode MSDN: How to Create an HTML Editor Application A closed source, cross-browser rich-text editing demo xbDesignMode; a JavaScript helper class for easier cross-browser development usi...
Making content editable - Developer guides
You can enable them by setting the preferences shown below using about:config: user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capability.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); oD...
... ...
HTML5 Parser - Developer guides
closing comment marker is omitted (see preceding point). You can avoid such problems by using the character code for the initial '<' instead. (It is valid to use an escape character, e.g., <\/script>, but this strategy does not work for <script and <!--, because \s and \! are not valid JavaScript escapes; the character code strategy is more general-purpose.) Inline SVG and MathML support As a
completely new parsing feature, HTML5 introduced support for inline SVG and MathML in text/html. This means that you can now use SVG and MathML inline in text/html similarly to what has previously been possible in application/xhtml+xml. <svg>...</svg> is assigned to the SVG namespace in the DOM. <math>...</math> is assigned to the MathML namespace in the DOM. foreignObject and annotation-xml (and var...
...context. This may make some typos have surprising effects. Performance improvement with speculative parsing Unrelated to the requirements of HTML5 specification, the Gecko 2 parser uses speculative parsing, in which it continues parsing a document while scripts are being downloaded and executed. This results in improved performance compared to older parsers, because most of the time, Gecko can
complete these tasks in parallel. To best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call document.write(), you write a balanced sub-tree within that chunk of script. A balanced sub-tree is HTML code in which any elements that are opened are also closed, so that after the script, the elements left open are the same ones that were open b...
Separate sites for mobile and desktop - Developer guides
r phone and optimized for speed. Conceptually simple, this is the easiest option to add to an existing site, especially if you are using a CMS or Web application that supports templates. Since only the mobile-specific content, styles, and scripts are sent to mobile users, this method also provides for the best performance out of any of the other options presented here. Finally, it also allows for
completely different user experiences on desktop and mobile -- they're two different sites, after all! The bad Unfortunately, this approach is not without its drawbacks. For starters, you are now maintaining two different pages for every page on your site that you would like to expose to mobile users. If you are using a CMS, it is possible to arrange your site templates in a way that minimizes this duplic...
... instead understand formats like XHTML-MP or the older WML. This factor aside, there is one case where this strategy really shines over other methods. If the functionality you would like to provide to your users on mobile devices is extremely different from that on a desktop, then using separate sites is simply likely to be the most practical choice. This is because you have the option of sending
completely separate HTML, JavaScript, and CSS to phones and PCs. Another case where you may be forced to use this approach is if you cannot, for whatever reason, modify your existing desktop site, and need to have a 100% separate mobile site. Though it's not ideal, at least you have this option. Examples Most of the major Web applications you see in the wild have chosen this path, including Facebook, YouT...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
ss The input buffer of a ScriptProcessorNode is ready to be processed. canplay The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. canplaythrough 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 delayed due to lack of data. ratechange The playback rate has changed. seeked A seek operation
completed. seeking A seek operation began. stalled The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend Media data loading has been suspended. timeupdate The time indicated by the currentTime attribute has been updated. volumechange The volume has changed. waiting Playback has stopped because...
<button>: The Button element - HTML: Hypertext Markup Language
tted ARIA roles checkbox, link, menuitem, menuitemcheckbox, menuitemradio, option, radio, switch, tab DOM interface HTMLButtonElement Attributes This element's attributes include the global attributes. autofocus HTML5 This Boolean attribute specifies that the button should have input focus when the page loads. Only one element in a document can have this attribute. auto
complete This attribute on a <button> is nonstandard and Firefox-specific. Unlike other browsers, Firefox persists the dynamic disabled state of a <button> across page loads. Setting auto
complete="off" on the button disables this feature; see bug 654072. disabled This Boolean attribute prevents the user from interacting with the button: it cannot be pressed or focused. Firefox, unlike other brows...
... form HTML5 The <form> element to associate the button with (its form owner). The value of this attribute must be the id of a <form> in the same document. ...
<input type="date"> - HTML: Hypertext Markup Language
gracefully to <input type="text">. Among browsers with custom interfaces for selecting dates are Chrome and Opera, whose data control 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 auto
complete, 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 ins...
...t input. Let's look at an example of minimum and maximum dates, and also made a field required: <form> <label> Choose your preferred party date (required, April 1st to 20th): <input type="date" name="party" min="2017-04-01" max="2017-04-20" required> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form> If you try to submit the form with an in
complete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: Here's a screenshot for those of you who aren't using a supporting browser: Here's the CSS used in the above example. We make use of the :valid and :invalid pseudo-elements to add an icon next to the input, based on whether or not the current value is valid. We had to put the icon ...
<input type="datetime-local"> - HTML: Hypertext Markup Language
date and the time parts of the value bring up two separate pickers for you, so you can easily set both the date and 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 auto
complete, 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 ...
...Try playing with the example now: Here's a screenshot for those of you who aren't using a supporting browser: Here's the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a <span...
<input type="file"> - HTML: Hypertext Markup Language
".png, .jpg, .jpeg" -- Accept PNG or JPEG files. accept="image/*" -- Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.) accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" -- accept anything that smells like an MS Word document. ...
...he beginning of it. There are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is defined in the spec. Examples In this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the HTMLInputElement.files property, as well as showing off a few clever tricks. Note: You can see the
complete source code for this example on GitHub -- file-example.html (see it live also). We won't explain the CSS; the JavaScript is the main focus. First of all, let's look at the HTML: <form method="post" enctype="multipart/form-data"> <div> <label for="image_uploads">Choose images to upload (PNG, JPG)</label> <input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .
<input type="month"> - HTML: Hypertext Markup Language
upport month, the screenshot below shows what it looks like in Chrome and Opera. Clicking the down 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 auto
complete, 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 lo...
...h" name="bday-month" value="2017-06"> var monthControl = document.querySelector('input[type="month"]'); monthControl.value = '1978-06'; Additional attributes In addition to the attributes common to <input> elements, month inputs offer the following attributes: Attribute Description list The id of the <datalist> element that contains the optional pre-defined auto
complete options max The latest year and month to accept as a valid input min The earliest year and month to accept as a valid input readonly A Boolean which, if present, indicates that the input's value can't be edited step A stepping interval to use when incrementing and decrementing the value of the input field list The values of the list attribut...
<input type="number"> - HTML: Hypertext Markup Language
GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/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 auto
complete, 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 su...
...lue 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 list The id of the <datalist> element that contains the optional pre-defined auto
complete options max The maximum value to accept for this input min The minimum value to accept for this input placeholder An example value to display inside the field when it's empty readonly A Boolean attribute indicating whether the value is read-only step A stepping interval to use when using up and down arrows to adjust the value, as well as...
<video>: The Video Embed element - HTML: Hypertext Markup Language
s The input buffer of a ScriptProcessorNode is ready to be processed. canplay The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. canplaythrough 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. ...
... 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 delayed due to lack of data. progress Fired periodically as the browser loads a resource. ratechange The playback rate has changed. seeked A seek operation
completed. seeking A seek operation began. stalled The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend Media data loading has been suspended. timeupdate The time indicated by the currentTime attribute has been updated. volumechange The volume has changed. waiting Playback has stopped because...
Using the application cache - HTML: Hypertext Markup Language
ified in the manifest file from the application cache (not from the server). In addition, the browser also sends a checking event to the window.applicationCache object, and fetches the manifest file, following the appropriate HTTP caching rules. If the currently-cached copy of the manifest is up-to-date, the browser sends a 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 rul...
...source is inaccessible. Each entry in this section lists two URIs--the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used. The CACHE, NETWORK, and FALLBACK sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest. Example 2: a more
complete cache manifest file The following is a more
complete cache manifest file for the imaginary web site at www.example.com: CACHE MANIFEST # v1 2011-08-14 # This is another comment index.html cache.html style.css image1.png # Use from network if available NETWORK: network.html # Fallback content FALLBACK: . fallback.html This example uses NETWORK and FALLBACK sections to specify that the networ...
Content Security Policy (CSP) - HTTP
n, sites that want to never allow scripts to be executed can opt to globally disallow script execution. Mitigating packet sniffing attacks In addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using HTTPS. A
complete data transmission security strategy includes not only enforcing HTTPS for data transfer, but also marking all cookies with the secure attribute and providing automatic redirects from HTTP pages to their HTTPS counterparts. Sites may also use the Strict-Transport-Security HTTP header to ensure that browsers connect to them only over an encrypted channel. Using CSP Configuring Content Security Po...
...cy is a string containing the policy directives describing your Content Security Policy. Writing a policy A policy is described using a series of policy directives, each of which describes the policy for a certain resource type or policy area. Your policy should include a default-src policy directive, which is a fallback for other resource types when they don't have policies of their own (for a
complete list, see the description of the default-src directive). A policy needs to include a default-src or script-src directive to prevent inline scripts from running, as well as blocking the use of eval(). A policy needs to include a default-src or style-src directive to restrict inline styles from being applied from a <style> element or a style attribute. There are specific directives for a wide varie...
An overview of HTTP - HTTP
Clients and servers communicate by exchanging individual messages (as opposed to a stream of data). ...
...tiated messages). To present a Web page, the browser sends an original request to fetch the HTML document that represents the page. It then parses this file, making additional requests corresponding to execution scripts, layout information (CSS) to display, and sub-resources contained within the page (usually images and videos). The Web browser then mixes these resources to present to the user a
complete document, the Web page. Scripts executed by the browser can fetch more resources in later phases and the browser updates the Web page accordingly. A Web page is a hypertext document. This means some parts of displayed text are links which can be activated (usually by a click of the mouse) to fetch a new Web page, allowing the user to direct their user-agent and navigate through the Web. The brow...
308 Permanent Redirect - HTTP
arch engines update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is sent to the new URL). The request method and the body will not be altered, whereas 301 may incorrectly sometimes be changed to a GET method. ...
...EO-speak', it is said that the 'link-juice' is sent to the new URL). The request method and the body will not be altered, whereas 301 may incorrectly sometimes be changed to a GET method. ...
HTTP response status codes - HTTP
Responses are grouped in five classes: Informational responses (100-199), Successful responses (200-299), Redirects (300-399), Client errors (400-499), and Server errors (500-599). The below status codes are defined by section 10 of RFC 2616. You can find an updated specification in RFC 7231. If you receive a response that is not in this list, it is a non-standard response, possibly custom to the server's software. ...
...riant Also Negotiates The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. 507 Insufficient Storage (WebDAV) The method could not be performed on the resource because the server is unable to store the representation needed to successfully
complete the request. 508 Loop Detected (WebDAV) The server detected an infinite loop while processing the request. 510 Not Extended Further extensions to the request are required for the server to fulfil it. 511 Network Authentication Required The 511 status code indicates that the client needs to authenticate to gain network access. ...
CSS Houdini
s. Advantages of Houdini Houdini enables faster parse times than using JavaScript .style for style changes. Browsers parse the CSSOM -- including layout, paint, and composite processes -- before applying any style updates found in scripts. In addition, layout, paint, and composite processes are repeated for JavaScript style updates. Houdini code doesn't wait for that first rendering cycle to be
complete. Rather, it is included in that first cycle -- creating renderable, understandable styles. Houdini provides an object-based API for working with CSS values in JavaScript. Houdini's CSS Typed OM is a CSS Object Model with types and methods, exposing values as JavaScript objects making for more intuitive CSS manipulation than previous string based HTMLElement.style manipulations. Every element and...
...ssible 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 great power comes great responsibi...
Expressions and operators - JavaScript
Operators JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence. ...
... Expressions An expression is any valid unit of code that resolves to a value. Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluate and...
Keyed collections - JavaScript
indexed by a key; Map and Set objects contain elements which are iterable in the order of insertion. Maps Map object 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. let sayings = new Map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); // false sayings.delete('dog'); sayings.has('dog'); // false for (let [key, value] of sayings)...
...t 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 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.
Inheritance and the prototype chain - JavaScript
var inst = new bar; console.log(inst.foo_prop); console.log(inst.bar_prop) Support in all in-use-today browsers which are all non-microsoft browsers plus IE9 and up. Allows the dynamic manipulation of an objects prototype and can even force a prototype on a prototype-less object created with Object.create(null). Should-be-deprecated and ill-performant. ...
...rop: "foo val", __proto__: Object.prototype } } }; console.log(inst.foo_prop); console.log(inst.bar_prop) Support in all in-use-today browsers which are all non-microsoft browsers plus IE11 and up. Setting __proto__ to something that is not an object only fails silently. It does not throw an exception. Grossly deprecated and non-performant. ...
JSON.stringify() - JavaScript
onversion 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 the value null, are all considered null. All the other Object instances (including Map, Set, WeakMap, and WeakSet) will have only their enumerable properties se...
...eError: cyclic object value" JSON.stringify(circularReference); To serialize circular references you can use a library that supports them (e.g. cycle.js by Douglas Crockford) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. Issue with plain JSON.stringify for use as JavaScript Historically, JSON was not a
completely strict subset of JavaScript. The literal code points U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR could appear literally in string literals and property names in JSON text. But they could not appear literally in similar context in JavaScript text, only using Unicode escapes as \u2028 and \u2029. This recently changed: now both code points may appear literally in strings in JSON and Jav...
Object.assign() - JavaScript
ed, foo3 will not be copied. console.log(target.baz); // undefined, the third source will not be copied either. Copying accessors const obj = { foo: 1, get bar() { return 2; } }; let copy = Object.assign({}, obj); console.log(copy); // { foo: 1, bar: 2 } // The value of copy.bar is obj.bar's getter's return value. ...
... ...
Promise.allSettled() - JavaScript
The Promise.allSettled() method returns a 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...
...e 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 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, ...
Proxy - JavaScript
/* var docCookies = ... get the "docCookies" object here: https://developer.mozilla.org/docs/DOM/d...
...} console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' } console.log(products['Chrome']); // undefined console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }] console.log(products.types); // ['browser', 'mailer'] console.log(products.number); // 3 A
complete traps list example Now in order to create a
complete sample traps list, for didactic purposes, we will try to proxify a non-native object that is particularly suited to this type of operation: the docCookies global object created by the "little framework" published on the document.cookie page. /* var docCookies = ... get the "docCookies" object here: https://developer.mozilla.org/docs/DOM/document.cookie#A_little_framework.3A_a_
complete_cookie...
encodeURI() - JavaScript
he 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 parts that a URI "scheme" can possibly contain. Note how certain characters are used to signify special meaning: http://username:password@www.example.co...
...ode 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 encodeURIComponent encodeURI() differs from encodeURIComponent() as follows...
async function - JavaScript
e.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 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 cha...
...nction concurrentPromise() { console.log('==CONCURRENT START with Promise.all==') return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => { console.log(messages[0]) // slow console.log(messages[1]) // fast }) } async function parallel() { console.log('==PARALLEL with await Promise.all==') // Start 2 "jobs" in parallel and wait for both of them to
complete await Promise.all([ (async()=>console.log(await resolveAfter2Seconds()))(), (async()=>console.log(await resolveAfter1Second()))() ]) } sequentialStart() // after 2 seconds, logs "slow", then after 1 more second, "fast" // wait above to finish setTimeout(concurrentStart, 4000) // after 2 seconds, logs "slow" and then "fast" // wait again setTimeout(concurrentPromise, 7000) // sa...
Image file type and format guide - Web media technologies
ally supports a variety of internal data representations. The simplest, and most commonly used, form of BMP file is an uncompressed raster image, with each pixel occupying 3 bytes representing its red, green, and blue components, and each row padded with 0x00 bytes to a multiple of 4 bytes wide. While other data representations are defined in the specification, they are not widely used and often
completely unimplemented. These features include: support for different bit depths, indexed color, alpha channels, and different pixel orders (by default, BMP is written from bottom-left corner toward the right and top, rather than from the top-left corner toward the right and bottom). Theoretically, several compression algorithms are supported, and the image data can also be stored in JPEG or PNG format...
...a web site's root directory to specify a favicon -- an icon to be displayed in the Favorites menu, and other places where an iconic representation of the site would be useful. An ICO file can contain multiple icons, and begins with a directory listing details about each. Following the directory comes the data for the icons. Each icon's data can be either a BMP image without the file header, or a
complete PNG image (including the file header). If you use ICO files, you should use the BMP format, as support for PNG inside ICO files wasn't added until Windows Vista and may not be well supported. ICO files should not be used in web content. Additionally, their use for favicons has subsided in favor of using a PNG file and the <link> element, as described in Providing icons for different usage conte...
Populating the page: how browsers work - Web Performance
t takes to transmit bytes over-the-air to computers. Web performance is what we have to do to make the page load happen as quickly as possible. For the most part, browsers are considered single threaded. For smooth interactions, the developer's goal is to ensure performant site interactions, from smooth scrolling to being responsive to touch. Render time is key, with ensuring the main thread can
complete all the work we throw at it and still always be available to handle user interactions. Web performance can be improved by understanding the single-threaded nature of the browser and minimizing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate. Navigation Navigation is the first step in loading a web page...
...sible and appropriate, to ensure rendering is smooth and responses to interactions are immediate. Navigation Navigation is the first step in loading a web page. It occurs whenever a user requests a page by entering a URL into the address bar, clicking a link, submitting a form, as well as other actions. One of the goals of web performance is to minimize the amount of time a navigation takes to
complete. In ideal conditions, this usually doesn't take too long, but latency and bandwidth are foes which can cause delays. DNS Lookup The first step of navigating to a web page is finding where the assets for that page are located. If you navigate to https://example.com, the HTML page is located on the server with IP address of 93.184.216.34. If you've never visited this site, a DNS lookup must happe...
Recommended Web Performance Timings: How long is too long? - Web Performance
n or changing frame rate, will appear janky. Responsiveness goal When the user interacts with content, it is important to provide feedback and acknowledge the user's response or interaction and to do so within 100ms, preferably within 50ms. 50ms seconds feels immediate. ...
...feel immediate, such as a hover or button press, but that doesn't mean the
completed response should be instantaneous. While a slower than 100ms reaction may create a disconnect between the user interaction and the response, a 100 to 200ms transition for a response may help the user notice the response their interaction initiated, such as a menu opening. If a response takes longer than 100ms to
complete, provide some form of feedback to inform the user the interaction has occurred. ...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
receive the result whenever it is ready using a Promise-based approach. They can do a lot more than "just" offering offline capabilities, including handling notifications, performing heavy calculations on a separate thread, etc. Service workers are quite powerful as they can take control over network requests, modify them, serve custom responses retrieved from the cache, or synthesize responses
completely. Security Because they are so powerful, Service Workers can only be executed in secure contexts (meaning HTTPS). If you want to experiment first before pushing your code to production, you can always test on a localhost or setup GitHub Pages -- both support HTTPS. Offline First The "offline first" -- or "cache first" -- pattern is the most popular strategy for serving content to the user. I...
..., it is registered against the site using the ServiceWorkerContainer.register() method. 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 finally activated. Installation The API allows us to add event listeners for key events we are interested in -- the first one is the install event: self.addEventListener('install', (e) => { console.log('[Service Worker] Install'); }); In the install listener, we can initialize the cache and add files to it for offline use. O...
Example - SVG: Scalable Vector Graphics
In this example, we use XHTML, SVG, JavaScript, and the DOM to animate a swarm of "motes". These motes are governed by two simple principles. First, each mote tries to move towards the mouse cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural-looking behavior. This is done
completely in W3C Standards-XHTML, SVG, and JavaScript-no Flash or any vendor-specific extensions. This example should work in Firefox 1.5 and above. View the example <?xml version='1.0'?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <title>A swarm of motes</title> <style type='text/css'> <![CDATA[ label, input { width: 150px; display: block; float: left; margin-bottom: 10px; } label { ...
...' width='400' height='300'> <svg:circle id='cursor' cx='200' cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/> </svg:svg> <p>A swarm of motes, governed by two simple principles. 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. </p> <p> This is done
completely in W3C Standards-XHTML, SVG and JavaScript-no flash or any vendor specific extensions. Currently, this will work in Mozilla Firefox version 1.5 and above. </p> <div> (C) 2006 <a id='emailme' href='#'>Nick Johnson</a> <script type='text/javascript'> <![CDATA[ // foil spam bots var email = '@riovia.net'; email ='nick' + email; document.getElementById('emailme').href...
Introduction - SVG: Scalable Vector Graphics
VG is an XML language, similar to XHTML, which can be used to draw vector graphics, such as the ones shown to the right. It can be used to create an image either by specifying all the lines and shapes necessary, by modifying already existing raster images, or by a combination of both. The image and its components can also be transformed, composited together, or filtered to change their appearance
completely. SVG came about in 1999 after several competing formats had been submitted to the W3C and failed to be fully ratified. SVG is supported by all major browsers. A downside is loading SVG can be slow. SVG does offer benefits, some of which include having a DOM interface available for it, and not requiring third-party extensions. Whether or not to use it often depends on your specific use case. ...
...h. Not all SVG viewers are equal and so there is a good chance that something written for one app will not display exactly the same in another, simply because they support different levels of the SVG specification or another specification that you are using along with SVG (that is, JavaScript or CSS). SVG is supported in all modern browsers and even a couple versions back in some cases. A fairly
complete browser support table can be found on Can I use. Firefox has supported some SVG content since version 1.5, and that support level has been growing with each release since. Hopefully, along with the tutorial here, MDN can help developers keep up with the differences between Gecko and some of the other major implementations. Before starting you should have a basic understanding of XML or another m...
Paths - SVG: Scalable Vector Graphics
them instead. There is no real performance penalty or bonus for using one or the other. Curve commands There are three different commands that can be used to create smooth curves. Two of those curves are Bezier curves, and the third is an "arc" or part of a circle. You might have already gained practical experience with Bezier curves using path tools in Inkscape, Illustrator or Photoshop. For a
complete description of the math behind Bezier curves, go to a reference like the one on Wikipedia. There are an infinite number of Bezier curves, but only two simple ones are available in <path> elements: a cubic one, called with C, and a quadratic one, called with Q. Bezier Curves The cubic curve, C, is the slightly more complex curve. Cubic Beziers take in two control points for each point. Therefore...
... L 125 230 Z" fill="purple"/> <path d="M 230 230 A 45 45, 0, 1, 1, 275 275 L 275 230 Z" fill="blue"/> </svg> Arcs are an easy way to create pieces of circles or ellipses in drawings. For instance, a pie chart would require a different arc for each piece. If transitioning to SVG from <canvas>, arcs can be the hardest thing to learn, but are also much more powerful.
Complete circles and ellipses are the only shapes that SVG arcs have trouble drawing. Because the start and end points for any path going around a circle are the same point, there are an infinite number of circles that could be chosen, and the actual path is undefined. It's possible to approximate them by making the start and end points of the path slightly askew, and then connecting them with another pat...
Texts - SVG: Scalable Vector Graphics
Basics We have seen in the introducing example, that the text element can be used to put arbitrary text in SVG documents: <text x="10" y="10">Hello World!</text> The x and y attributes determine, where in the viewport the text will appear. ...
... Basics We have seen in the introducing example, that the text element can be used to put arbitrary text in SVG documents: <text x="10" y="10">Hello World!</text> The x and y attributes determine, where in the viewport the text will appear. ...
Tutorials
her you are just starting out, learning the basics, or are an old hand at web development, you can find helpful resources here for best practices. These resources are created by forward-thinking companies and web developers who have embraced open standards and best practices for web development and that provide or allow translations, through an open content license such as Creative Commons. For
complete beginners to the Web Getting started with the Web Getting started with the Web is a concise series introducing you to the practicalities of web development. You'll set up the tools you need to construct a simple webpage and publish your own simple code. HTML Tutorials Introductory level Introduction to HTML This module sets the stage, getting you used to important concepts and synta...
...late the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and new fangled layout tools like flexbox. CSS reference
Complete reference to CSS, with details on support by Firefox and other browsers. Fluid Grids Design layouts that fluidly resize with the browser window, while still using a typographic grid. CSS Challenges Flex your CSS skills, and see where you need more practice. Advanced level Using CSS transforms Apply rotation, skewing, scaling, and translation using CSS. CSS transitions CSS tr...
Using the WebAssembly JavaScript API - WebAssembly
as values instead of JavaScript functions. Memory imports are useful for two reasons: They allow JavaScript to fetch and create the initial contents of memory before or concurrently with module compilation. They allow a single Memory object to be imported by multiple module instances, which is a critical building block for implementing dynamic linking in WebAssembly. Note: You can find our
complete demo at memory.html (see it live also) . Tables A WebAssembly Table is a resizable typed array of references that can be accessed by both JavaScript and WebAssembly code. While Memory provides a resizable typed array of raw bytes, it is unsafe for references to be stored in a Memory since a reference is an engine-trusted value whose bytes must not be read or written directly by content for sa...
...ole.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 This code accesses each function reference stored in the table in turn, and instantiates them to print the values they hold to the console -- note how each function reference is retrieved with a Table.prototype.get() call, then we add an extra set of parentheses on the end to actually invoke the function. Note: You can find our
complete demo at table.html (see it live also). Globals WebAssembly has the ability to create global variable instances, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module instances. This is very useful, as it allows dynamic linking of multiple modules. To create a WebAssembly global instance from inside your JavaScript, you use the WebAssembly.Global() con...
Reddit Example - Archive of obsolete content
ddit. When the user clicks on the title of a story in the panel, the add-on opens the linked story in a new tab in the main browser window. To accomplish this the add-on needs to run a content script in the context 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. ...
self - Archive of obsolete content
This article documents the self object that is available as a global in content scripts. self provides: 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"...
Communicating using "port" - Archive of obsolete content
rker.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 of the global self object. Thus, to emit a message from a content script: self.port.emit("myContentScriptMessage", myContentScriptMessagePayload); To receive a message from the add-on code: self.port.on("myAddonMessage", funct...
Modules - Archive of obsolete content
avaScript does not provide any means to load scripts from other locations: we have to rely on the host application to provide us with this functionality. Applications such as Firefox and Thunderbird are based on Xulrunner. Xulrunner adds a built-in object, known as Components, to the global scope. This object forms the central access point for all functionality provided by the host application. A
complete explanation of how to use Components is out of scope for this document. However, the following example shows how it can be used to load scripts from other locations: const { classes: Cc interfaces: Ci } = Components; var instance = Cc["@mozilla.org/moz/jssubscript-loader;1"]; var loader = instance.getService(Ci.mozIJSSubScriptLoader); function loadScript(url) { loader.loadSubScript...
Module structure of the SDK - Archive of obsolete content
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 with the modul...
SDK API Lifecycle - Archive of obsolete content
ion will inform users that the module is deprecated. Attempts to use a deprecated module at runtime will log an error to the error console. The AMO validator will throw errors when deprecated modules are used, and these add-ons will therefore fail AMO review. All warnings should include links to further information about what to use instead of the deprecated module and when the module will be
completely removed. Removal The target removal date is 18 weeks after deprecation. In preparation for this date the SDK team will decide whether to go ahead with removal: this will depend on how many developers have successfully migrated from the deprecated module, and on how urgently the module needs to be removed. If it's OK to remove the module, it will be removed. The SDK team will remove the corre...
hotkeys - Archive of obsolete content
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, accel-V or accel-Q If you choose to use a key combination that's already defined, choose one which makes sense for the operation it will perform. For example, accel-S is typically used to save a file, but if you use it for something
completely different, then it would be extremely confusing for users. No matter what you choose, it's likely to annoy some people, and to clash with some other add-on, so consider making the combination you choose user-configurable. Globals Constructors Hotkey(options) Creates a hotkey whose onPress listener method is invoked when key combination defined by hotkey is pressed. If more than one hotkey...
page-worker - Archive of obsolete content
ng, as in the examples above. With contentScriptFile you pass a URL which points to a script saved under your add-on's data directory. You construct the URL using the data.url() method of the self module. While content scripts can access DOM content, they can't access any of the SDK APIs, so in many cases you'll need to exchange messages between the content script and your main add-on code for a
complete solution. For example, the content script might read some content and send it back to the main add-on, which could store it using the simple-storage API. You can communicate with the script using either the postMessage() API or (preferably, usually) the port API. For example, this add-on loads a page from Wikipedia, and runs a content script in it to send all the headers back to the main add-on...
self - Archive of obsolete content
Globals Properties uri This property represents an add-on associated unique URI string. This URI can be used for APIs which require a valid URI string, such as the passwords module. id This property is a printable string that is unique for each add-on. It comes from the id property set in the package.json file in the main package (i.e. the package in which you run jpm xpi). ...
tabs - Archive of obsolete content
lling you the load state of the document hosted by this tab. This corresponds directly to Document.readyState. It has one of four possible values: "uninitialized": the tab's document is not yet loading "loading": the tab's document is still in the process of loading "interactive": the tab's document has loaded and is parsed, but resources such as images and stylesheets may still be loading "
complete": the tab's document and all resources are fully loaded Once a tab's readyState has entered "interactive", you can retrieve properties such as the document's URL. Events close This event is emitted when the tab is closed. It's also emitted when the tab's window is closed. Arguments Tab : Listeners are passed the tab object. ready This event is emitted when the DOM for the tab's content i...
widget - Archive of obsolete content
perty to grow it in order to show all the text. Scripting widget content To interact with the widget's content you need to load a separate script into the panel. In the SDK these scripts are called "content scripts" because they're explicitly used for 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 ...
/loader - Archive of obsolete content
log: dump.bind(dump, 'log: '), info: dump.bind(dump, 'info: '), warn: dump.bind(dump, 'warn: '), error: dump.bind(dump, 'error: ') } } }); Be careful not to misuse this feature! In general it is not recommended to provide features via globals, it's almost always better to use pseudo-modules or, even better, modules. resolve The optional resolve option enables you to
completely customize module resolution logic. resolve is assigned a function that takes: the ID of the module passed into require() the ID of the module that called require() On each require() call, the supplied function is then called with the ID of the required module and that of the requiring module. The function returns a string representing the resolved module ID, which is then resolved to it...
core/namespace - Archive of obsolete content
.. } 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 } = 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.p...
io/text-streams - Archive of obsolete content
ing stream's buffer and closes both the stream and the backing stream. If the stream is already closed, an exception is thrown. flush() Flushes the backing stream's buffer. write(str) Writes a string to the stream. If the stream is closed, an exception is thrown. Parameters str : string The string to write. writeAsync(str, callback) Writes a string on a background thread. After the write
completes, the backing stream's buffer is flushed, and both the stream and the backing stream are closed, also on the background thread. If the stream is already closed, an exception is thrown immediately. Parameters str : string The string to write. callback : callback callback, if given, must be a function. It's called as callback(error) when the write
completes. error is an Error object or undefin...
system/child_process - Archive of obsolete content
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. The SDK versions don't: so when you specify a command you must pass in a
complete path to the command or use the env option to set up the child process environment. child.stdin has no write() method (see example below for writing to child process stdin) Examples Adaption of node's documentation for spawn(): var child_process = require("sdk/system/child_process"); var ls = child_process.spawn('/bin/ls', ['-lh', '/usr']); ls.stdout.on('data', function (data) { console.l...
system/runtime - Archive of obsolete content
Access to information about Firefox's runtime environment. All properties exposed are read-only. For more information, see nsIXULRuntime. Globals Properties inSafeMode This value is true if Firefox was started in safe mode, otherwise false. OS A string identifying the current operating system. For example, . "WINNT", "Darwin", or "Linux". See OS_TARGET for a more
complete list of possible values. processType The type of the caller's process, which will be one of these 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 An IPDL unit testing subprocess. ...
window/utils - Archive of obsolete content
. options : object Options object containing the following property: Name Type includePrivate boolean Whether to include private windows. Defaults to false. The add-on must also have opted into private windows for this to have an effect. Returns Array: array of nsIDOMWindow instances. isDocumentLoaded(window) Check if the given window's document is
completely loaded. This means that its "load" event has been fired and all content is loaded, including the whole DOM document, images, and any other sub-resources. Parameters window : nsIDOMWindow Returns boolean: true if the document is
completely loaded. isBrowser(window) Returns true if the given window is a Firefox browser window: that is, its document has a "windowtype" of "chrome://browser/co...
console - Archive of obsolete content
log(), warn(), and error() will all result in output being written. But if the logging level is "warn" then only calls to warn() and error() have any effect, and calls to info() and log() are simply discarded. This means that the same code can be more verbose in a development environment than in a production environment - you just need to arrange for the appropriate logging level to be set. ...
jpm - Archive of obsolete content
the add-on's install manifest. version description entry point (which maps to "main" in package.json) author engines (supported applications) license Most of these fields have a default, which is shown in brackets after the question. If you just press Enter, your add-on gets the default value. Once you've supplied a value or accepted the default for these properties, you'll be shown the
complete contents of "package.json" and asked to accept it. Then jpm creates a skeleton add-on, as a starting point for your add-on development, with the following file structure: my-addon index.js package.json test test-index.js jpm run This command runs a new instance of Firefox with the add-on installed: jpm run jpm run accepts the following options: ...
Adding a Button to the Toolbar - Archive of obsolete content
on button API except it adds a boolean checked property which is toggled whenever the button is checked. To attach the panel, pass the button to the panel's show() method. For more details on this, see the toggle button's documentation. Displaying richer content To create more complex user interface content than is possible with just a button, use the toolbar API. With the toolbar API you get a
complete horizontal strip of user interface real estate. You can add buttons to the toolbar and also frames, that can host HTML, CSS, and JavaScript. Learning more action button reference toggle button reference toolbar reference ...
Annotator - Archive of obsolete content
enter notes (annotations) associated with them. The annotator stores the notes. Whenever the user loads a page containing annotated elements these elements are highlighted, and if the user moves the mouse over an annotated element its annotation is displayed. Next we'll give a quick overview of the annotator's design, then go through the implementation, step by step. If you want to refer to the
complete add-on you can find it under the examples directory in the SDK. Design Overview Implementing the Widget Creating Annotations Storing Annotations Displaying Annotations ...
Getting Started (jpm) - Archive of obsolete content
ter: mkdir my-addon cd my-addon jpm init You'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file. For now, just press Enter to accept the default for each property. For more information on jpm init, see the jpm command reference. Once you've supplied a value or accepted the default for these properties, you'll be shown the
complete contents of "package.json" and asked to accept it. Implementing the add-on Now you can write the add-on's code. Unless you've changed the value of "entry point" ("main" in package.json), this goes in "index.js" file in the root of your add-on. This file was created for you in the previous step. Open it and add the following code: var buttons = require('sdk/ui/button/action'); var tabs = requir...
Logging - Archive of obsolete content
the messages appear in Firefox's Browser Console. But note that by default, calls to console.log() will not result in any output in the Error Console for any installed add-ons: this includes add-ons installed using the Add-on Builder or using tools like the Extension Auto-installer. See "Logging Levels" in the console reference documentation for more information on this. Learning More For the
complete console API, see its API reference. ...
Canvas code snippets - Archive of obsolete content
le(); Code usable only from privileged code These snippets are only useful from privileged code, such as extensions or privileged apps. 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
completely saved. function saveCanvas(canvas, path, type, options) { return Task.spawn(function *() { var reader = new FileReader; var blob = yield new Promise(accept => canvas.toBlob(accept, type, options)); reader.readAsArrayBuffer(blob); yield new Promise(accept => { reader.onloadend = accept }); return yield OS.File.writeAtomic(path, new Uint8Array(reader...
JS XPCOM - Archive of obsolete content
r access well-known objects in XPCOM. Interfaces Every XPCOM object implements one or more interfaces. An interface is simply a list of constants and methods that can be called on the object, an example is nsIFile. Every XPCOM object must implement the nsISupports interface. Accessing XPCOM components from JavaScript XPCOM objects are either created as new instances (each creation gives you a
completely new COM object) or as services (each access gives you the same COM object, often called a singleton). Whether you must create a new instance or access as a service depends on the contract. In order to get an XPCOM object you need to know the contract ID of the object and the interface that you wish to use on it. Creating an instance of a component The preferred method of creating XPCOM instan...
Preferences - Archive of obsolete content
nderbird, and possibly other Mozilla-based applications. For more details on preferences in Mozilla, see Preferences System. If you haven't yet, read other documents about Mozilla preferences on MDN (links below in Resources section). Note: This article doesn't cover all available methods for manipulating preferences; please refer to the XPCOM reference pages listed in Resources section for the
complete list of methods. The interfaces dealing with preferences are fairly well documented, so using the methods not mentioned here should be straightforward. XPCOM 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 ...
StringView - Archive of obsolete content
If you want to build a custom cycle through a variable-length-encoded stringView (UTF-8, UTF-16), you can use a code like the following, which does not make use of stringView.forEachChar(). If the encoding is a fixed-length one (ASCII, UTF-32, etc.), you can do a normal cycle upon the st...
JavaScript timers - Archive of obsolete content
imation 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(). clearInterval() Cancels repeated action which was set up using setInterval(). clearImmediate() Cancels the immediate actions, just like clearTimeout() for setTimeout(). Using JavaScript timers within animations (Javascript Daemons Management) In Computer science a daemon is a task t...
Code snippets - Archive of obsolete content
HTML and XUL Using SVG to enhance HTML or XUL based markup XUL Widgets HTML in XUL for Rich Tooltips Dynamically embed HTML into a XUL element to attain markup in a tooltip Label and description Special uses and line breaking examples Tree Setup and manipulation of trees using XUL and JS Scrollbar Changing style of scrollbars. Applies to scrollbars in browser and iframe as well. Auto
complete Code used to enable form auto
complete in a browser Boxes Tips and tricks when using boxes as containers Tabbox Removing and manipulating tabs in a tabbox Windows-specific Finding Window Handles (HWND) (Firefox) How to use Windows API calls to find various kinds of Mozilla window handles. Window handles can be used for IPC and Accessibility purposes. Using the Windows Registry with XPC...
Developing add-ons - Archive of obsolete content
tting an add-on to AMO Provides helpful information for add-on developers to help them properly package and deliver their add-ons. This includes information about addons.mozilla.org, Mozilla's add-on distribution web site. Extensions Extensions add new functionality to Mozilla applications such as Firefox, SeaMonkey and Thunderbird. They can add anything from a toolbar button to a
completely new feature. Plugins Information about how to create plugins, which are binary components that let Mozilla based software display content they can't handle natively. Jetpack Browser extension development for everyone. Jetpack developers only need to know the tools of the modern web: HTML, CSS, and JavaScript. Themes Themes let users customize the ...
Listening to events in Firefox extensions - Archive of obsolete content
rowser, any of the browsers within it. Some of the more interesting DOM events you may wish to monitor are listed here: Event Description DOMLinkAdded Dispatched when a new HTML <link> element is detected in the document. DOMTitleChanged Dispatched when the title of the page changes. DOMContentLoaded Dispatched when the initial DOM for the page is
completely loaded. load Dispatched after the page--including images--has first finished loading. unload Dispatched when the user has navigated away from the page. pageshow Dispatched when a page is newly displayed. pagehide Dispatched when a page is hidden. Standard behavior for Web pages is: User navigates to a page. As the page loads, inline scr...
Multiple item extension packaging - Archive of obsolete content
same user interface is used for installing a multiple item package (i.e. the individual packages contained in the multiple item package will not be listed). This also allows displaying of signing information for the multiple item package. If a manager (e.g. extension / theme manager) is used, the manager will display the individual items contained by the multiple item package after the download
completes in the same manner that it would if the user had chosen to install multiple individual items simultaneously. The manager will not display the multiple item package in the list of items after the download has
completed. Signing All extensions now require signing by Mozilla. For multiple item packages, all internal add-ons need to be signed, but the container doesn't need to be signed. This mean...
Appendix: What you should know about open-source software licenses - Archive of obsolete content
This document was authored by Yutaka Kachi and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Any discussion of open-source software deserves an explanation of licensing-related issues. In this chapter, I'll explain some of the basics: what open-source software (OSS) licenses are, what types of licenses exist, and when they're appropriate. ...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
<< PreviousNext >> This document was authored by Hiroshi Shimoda of Clear Code Inc. and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Shimoda-san is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008). Before we dive into a thorough explanation, we'll quickly introduce the technologies used to develop Firefox extensions. We will also look at the minimum knowledge you'll need to have in order to develop for Firefox. Technologies used to develop Firefox extensions Firefox and its extensions are both based on and developed with technologies widely used on the web. Its structure is similar to that of the dynamic HTML used on some web pages, or the HTML applications used on Windows. ...
Adding Events and Commands - Archive of obsolete content
several elements at the same time, and this can be difficult to manage through JavaScript. The broadcaster element can help you out in these cases. First you need to add a broadcaster element to your XUL code, as a child of a broadcasterset element. <broadcasterset id="xulschoolhello-broadcasterset"> <broadcaster id="xulschoolhello-online-broadcaster" /> </broadcasterset> These elements are
completely invisible, so you can put them anywhere. It is recommended that you have them at the top of the XUL code, along with script declarations and other invisible elements with as popupset and commandset. Then you need to identify which of your XUL elements will be linked to this broadcaster, using the observes attribute: <menuitem id="xulschoolhello-hello-menu-item" label="&xulschoolhello.hello.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
me reason you want to override these styles (not recommended), you'll need the following rule: -moz-appearance: none; -moz-appearance can be used in many cases where you want to strip the native look out of an element. This will save you a lot of time trying to remove all the CSS rules that give the buttons a native look. You'll probably still need to override a couple other CSS rules to get a
completely plain look. The Customize Toolbars Dialog Firefox has the option to customize its toolbars. We've already mentioned this before, and if you follow our recommendations, then you shouldn't have many problems making your toolbar compatible with the Customize Toolbars dialog. The dialog can be opened from View > Toolbars > Customize..., or by right-clicking on the main toolbar (or any toolbar wit...
Adding windows and dialogs - Archive of obsolete content
" ondialogaccept="return XULSchoolChrome.HelloDialog.accept();" ondialogcancel="return XULSchoolChrome.HelloDialog.cancel();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> Carefully read the specification of the dialog element. You'll see that you can choose from a wide variety of buttons, associate any action you need to them, override their labels, and even add
completely customized extra buttons. All of this without having to worry about your dialog looking odd in some operating systems. The only constant rule is that clicking on OK and Cancel will close the dialog unless your associated function returns false. You should avoid returning false, though, specially with the Cancel button. Dialogs in general should be easy to dismiss. Your dialogs shouldn't have...
Appendix A: Add-on Performance - Archive of obsolete content
re are a few simple guidelines that should be followed to achieve that. Startup This is the area where add-ons have the most noticeable impact. Most add-ons use the load event handler in the main overlay to initialize their objects and sometimes read files or even fetch remote data. The problem with the onload event is that it runs before the main window becomes visible, so all handlers need to
complete before the user can see the window. An add-on can normally add a few hundred milliseconds to startup time because of the load handler, and it's not hard to figure out what having several add-ons will do. Luckily, minimizing your startup time is easy, if you follow these guidelines: Do not load or run code before it's needed. Add-ons can have extra features that are only available depending on...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
d-on happens in 2 stages: first the add-on is flagged to be uninstalled, and then the add-on is actually removed. In the case of Bootstrapped Extensions, both steps happen at the same time. In the case of "traditional" extensions, like those explained in the tutorial, both steps happen at different times. In this case the user is told that Firefox needs to restart in order for the extension to be
completely removed. Then the user has the option to restart right away, wait to restart whenever is convenient, or even cancel the uninstall operation. The add-on will not be
completely removed until the browser is restarted. So, in order to detect the first stage, you'll need to add an event listener using the addAddonListener method. The data parameter explains the action being performed. If you detec...
Connecting to Remote Content - Archive of obsolete content
to quickly access specific nodes in an XML or HTML document with a simple query mechanism. XPath can also be used to extract information from web pages once they load, along with the page load interception techniques discussed previously. XPath is very useful for cases when you're receiving large and complex XML files, and you only need some of the data contained in them. Using XPath to parse a
complete XML document is probably not a good idea performance-wise. Using XSLT XSLT (eXtensible Stylesheet Language Transformations) is another tool used to manipulate XML documents and transform them into other forms of text output, such as HTML, XUL, and so on. We can not cover all transformations to various output formats, so we'll just look into converting an XML document to XUL. First you need to...
JavaScript Object Management - Archive of obsolete content
normally not that much. If you have complex behavior that requires too much code, look for ways to divide it into multiple objects and files. You can include as many scripts in a XUL window as you need. To initialize your chrome objects, it's usually better to run the initialization code from the "load" event handler for the window. The load event is fired after the DOM on the window has loaded
completely, but before it's displayed to the user. This allows you to manipulate and possibly change elements in the window without the user 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-strin...
Mozilla Documentation Roadmap - Archive of obsolete content
using a search engine like Google, with queries such as "MDC Javascript Code Modules" or "Javascript code modules site:developer.mozilla.org". Secondly, there are several important articles that are very lacking in information, like the Preferences System page. And finally, what we mentioned in our XPCOM section: almost no documentation on XPCOM components. The documentation on interfaces is very
complete, but it isn't nearly as useful as the documentation that existed at XULPlanet and was later taken down. XULPlanet allowed you to navigate between interfaces and their related components, which makes locating components very easy. Hopefully this will be corrected in the future. In the meantime, you can still navigate XULPlanet using the Wayback Machine. MDC should be your first stop when looking ...
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. ...
Setting Up a Development Environment - Archive of obsolete content
Inspector is a good guide on how to get started using it. The DOM inspector is particularly useful in finding out how to overlay a window, and how to replace default CSS style rules. You can see the names of the files involved, which gives you a good starting point when looking into the Mozilla source. You can even change styles, attributes and execute Javascript code in it, although that's not
completely reliable. JavaScript Debugger The name says it all. The Venkman JavaScript Debugger is a great way to trace execution of your JavaScript code. To debug extension and browser code, right-click on the Loaded Scripts panel and uncheck Exclude Browser Files. The list of loaded scripts will grow long to include all of the scripts in Firefox. Having our file naming conventions prove very useful in...
The Box Model - Archive of obsolete content
ments and inside of elements. The margin determines the space between an element and the elements surrounding it, while the padding determines the space between the borders of a container element and its child nodes, kind of like an inner margin. Sometimes you also need to define flexible spaces between elements. In this case you should use a spacer element with a flex value. A spacer element is
completely invisible and doesn't do more than take space. You should only use it when you need flexible space. If you need fix-sized space it's best to use margins and paddings and avoid adding unnecessary nodes to your XUL document. Alignment XUL, unlike HTML, provides an easy way to align elements both horizontally and vertically. You can either use the align and pack attributes, or the -moz-box-align...
The Essentials of an Extension - Archive of obsolete content
y.properties" /> </stringbundleset> The stringbundleset element is just a container for stringbundle elements. There should only be one per document, which is the reason why we overlay the stringbundleset that is in browser.xul, hence the very generic id. We don't include the insertbefore or insertafter attributes because the ordering of string bundles doesn't make a difference. The element is
completely invisible. If you don't include any of those ordering attributes in an overlay element, Firefox will just append your element as the last child of the parent element. All you need for the string bundle is an id (to be able to fetch the element later) and the chrome path to the properties file. And, of course, you need the properties file: xulschoolhello.greeting.label = Hi! How are you? ...
XPCOM Objects - Archive of obsolete content
t, you'll see in what interface this member is defined. Clicking on the link for the getBranch method takes you to the nsIPrefService documentation page, where you can see more details on the interface and the method. You can also see a list of what components implement this interface. All of this documentation is generated from the one present in the Firefox source files, so it's in general very
complete and well written. It's a shame XUL Planet is no longer with us. Interfaces can be awkward to handle. If you want to call a method or use an attribute of interface X in a component, you first need to "cast" the component to interface X. This is done via the QueryInterface method that is included in all XPCOM components. this._prefService = Cc["@mozilla.org/preferences-service;1"].getService(...
Supporting search suggestions in search plugins - Archive of obsolete content
string and completion array are specified, leaving out the optional elements. Your completion list can include as many suggestions as you like, although it should be kept manageable, given that the display will be updating live while the user is typing their search string. In addition, the method you use to select suggestions is entirely up to you. Note: Firefox requires that suggest requests
complete within 500ms for suggestions to be displayed. If the request for the suggest URL does not return data before 500ms have elapsed, no search suggestions will be shown. ...
Promises - Archive of obsolete content
_1, PATH_1); // Fetch a file visible in the download manager. let download_2 = yield Downloads.createDownload({ source: URL_2, target: PATH_2, }); // Add it to the downloads list used by the download manager UI. let list = yield Downloads.getList(Downloads.ALL); list.add(download_2); // Start the second download, and wait for both // downloads to
complete. // This will raise an error if either download fails. yield Promise.all([download_1, download_2.start()]); // Do something with the saved files. doStuffWith(PATH_1, PATH_2); }); SQLite First, it's important to note that SQLite should be avoided in favor of simpler solutions, such as flat JSON files, under most circumstances. The IO, memory, and CPU over...
Creating a dynamic status bar extension - Archive of obsolete content
l1d1t1c1ohgv&e=.csv&s=GOOG'; // ... httpRequest = new XMLHttpRequest(); httpRequest.open('GET', fullUrl, true); httpRequest.onload = infoReceived; httpRequest.send(null); } The httpRequest variable will contain an XMLHttpRequest object. This object is used to configure and run an HTTP request on a web server, which we'll use to fetch the stock quote data. The fullUrl variable is the
complete URL to use when requesting a stock quote. In this case, we're using Yahoo's comma-separated values return to fetch easily-parsed stock quote data for Google (ticker symbol GOOG). refreshInformation() embeds another function, infoReceived(), which we'll look at separately shortly. The first thing we do is create a new XMLHttpRequest object to use for processing our request. We open the request, sp...
Creating a status bar extension - Archive of obsolete content
pers into one place to make it easy to jump in and get started. Note: The extension created by this tutorial won't work in Firefox that don't have a static status bar (that is, Firefox 4 and up). You can find a more up-to-date tutorial in the XUL School tutorial The Essentials of an Extension. Many of the concepts introduced here apply to any XUL-based application; however, to keep from getting
completely overwhelmed, we're going to focus specifically on Firefox. This sample will add a static text string to the status bar at the bottom of Firefox browser windows. If this sounds a lot like the existing Building an Extension article, you're right. However, this sample will be expanded upon in later articles in the series. Download the sample You can download a copy of this sample to look over -- o...
dischargingtimechange - Archive of obsolete content
o Cancelable No Target BatteryManager Default Action None Properties The event callback doesn't receive any event objects, but properties can be read from the BatteryManager object received from the navigator.getBattery method. Property Type Description 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. Example navigator.getBattery().then(function(battery) { console.log("Battery discharging time: " + battery.dischargingTime + " seconds"); batt...
Index of archived content - Archive of obsolete content
Modifying the Page Hosted by a Tab Open a Web Page Troubleshooting Unit Testing Using XPCOM without chrome Using third-party modules (jpm) Bootstrapped extensions Code snippets Alerts and Notifications Auto
complete Bookmarks Boxes Canvas code snippets Cookies Customizing the download progress bar Delayed Execution Dialogs and Prompts Downloading Files Drag & Drop Embedding SVG Examples and demos from articles File I/O Finding window handles F...
Environment variables affecting crash reporting - Archive of obsolete content
dump file after submitting it to the server. Minidumps will still be moved to the "Crash Reports/pending" directory. MOZ_CRASHREPORTER_NO_REPORT Save the minidump file but don't launch the crash reporting UI or send the report to the server. Minidumps will be stored in the user's profile directory, in a subdirectory named "minidumps". MOZ_CRASHREPORTER_DISABLE Disable Breakpad crash reporting
completely. You can use this if you would rather use the JIT debugger on Windows with the symbol server, for example. MOZ_CRASHREPORTER_SHUTDOWN Save the minidump and then force the application to close. This is useful for content crashes that don't normally close the chrome (main application) processes. This variable would cause the application to close as well. MOZ_CRASHREPORTER The opposite of MOZ_...
Source Navigator - Archive of obsolete content
nerate a long list of occurances. (as I understand. Let me know if this is wrong..) It can generate a class hierarchy quite easily (unfortunately, not for classnames which are defined by macro.) Installing Source Navigator In Ubuntu Execute the following line in a terminal window: sudo apt-get install sourcenav This should install source-navigator. One can check whether the installation is
complete by executing: $ which snavigator /usr/bin/snavigator Importing the source Execute the following: snavigator. This triggers a splash screen, followed by a "Source-Navigator Projects" dialog as the following: I've already created a new project bin.proj before documenting this. If this is your first time to open source navigator, the big white box on the left of the dialog should contain no line...
Source code directories overview - Archive of obsolete content
like history, bookmarks, preferences, migration, sidebar.. configcontains build scripts for Firefox. extensions contains code for making certain extensions work. installer contains the Firefox installer code. locales contains the files that are translated for Firefox. themes contains Firefox themes. Toolkit Toolkit is used by the standalone products. components contains the alerts, auto
complete, command line interface, console, cookies, download manager, filepicker, history, password manager, typeaheadfind, view source, etc. content contains XUL specific to the toolkit. library contains libXUL work. localescontains files that are translated. mozappscontains shared application stuff. obsoletecontains obsolete stuff. profilecontains the profile manager themescontains themes as they...
Using XML Data Islands in Mozilla - Archive of obsolete content
nt.getElementById("purchase-order").textContent; 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. ...
Automated testing tips and tricks - Archive of obsolete content
In test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run How to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js How to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://peop...
Creating a Firefox sidebar extension - Archive of obsolete content
ptySidebar.commandkey and openEmptySidebar.modifierskey keys from the dtd, remove the <keyset> from the firefoxOverlay.xul file. One must then set the key attribute of the menuitem to "". The extension needs to provide some special manifest files that control how it is installed and where its chrome resources are stored. The first is install.rdf, the install manifest. See Install Manifests for a
complete listing of the required and optional properties. The install manifest is listed in Example 5. Example 5. install.rdf <?xml version="1.0" encoding="UTF-8"?> <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <Description about="urn:mozilla:install-manifest"> <em:id>emptysidebar@yourdomain.com</em:id> <em:name>EmptySidebar Extensi...
Finding the file to modify - Archive of obsolete content
he structure layer identifies the widgets (menus, buttons, etc.) and their position in the UI relative to each other, the style layer defines how the widgets look (size, color, style, etc.) and their overall position (alignment), and the behavior layer specifies how the widgets behave and how users can use them to accomplish their goals. mention the localization layer (Note: These layers are not
completely mutually exclusive. In particular, positioning information can be specified in both the structure layer and the style layer, and some behavior can be partly defined in the style layer.) We're going to add code to all three UI layers, starting with the structure layer. The structure layer consists of XUL files. XUL, which is short for XML-based User Interface Language (and is pronounced like "Z...
Prerequisites - Archive of obsolete content
You should also understand tag-based languages like HTML as well as basic JavaScript, CSS, and the DOM. You might install Mozilla multiple times in the course of this tutorial, so you will find it handy to keep around a Mozilla installer. If you currently use Mozilla, you should install a new copy of the software in a different location from the existing installation for the purposes of this demo. ...
Creating a Microsummary - Archive of obsolete content
ect attribute contains an XPath expression that points to the node containing the count. XPath is a language for identifying nodes in HTML/XML documents. It also contains basic functions for manipulating those nodes and their content. The easiest way to get an XPath expression that points to the node in question is to use the XPath Checker extension. Install the extension (restarting Firefox to
complete installation) then go to the Spread Firefox home page, find the Firefox download count (a large number at the bottom of the right-hand column), context click on the number, and select View XPath from the context menu. XPath Checker will open a new window. The new window will include an XPath field that contains this XPath expression pointing to the download count node: id('download-count'). Add...
In-Depth - Archive of obsolete content
moz. This is only a list of properties which may be useful to you; it is in no way all of the Mozilla specific properties available. Other sites which list Mozilla specific CSS properties XulPlanet.com [dead link, 26.03.13] Mozilla-prefixed properties on the standard track 26.03.13 -moz-appearance Makes a widget look like it's from your operating system. Possible are (This is probably an in
complete list): none - (!important may be needed) Will override the operating system default. Use this when you want one or two controls to look different from the operating systems defaults. button, checkbox-container, checkbox, dialog, dualbutton, dualbutton-dropdown, listbox, menu, menulist-textfield, menulist-button, menulist, menulist-text, progressbar, progresschunk, radio-container, radio, resizer,...
Dehydra Object Reference - Archive of obsolete content
f property allows access to the original type object. .hasDefault boolean flag Applicable to function parameters only. Indicates whether the parameter has a default value, e.g. void foo(int i = 42). Aggregate Types (class/struct/union/enum) This type object represents aggregate types in GCC. Property Type Description .kind string One of "class", "struct", "union", or "enum". .isIn
complete boolean flag the type was forward-declared and the full declaration has not been processed. .bases array of objects Inheritance information about the class. Each member of the array has the following properties: { access: 'public' | 'protected' | 'private', type: type object representing the base class } .members array of variable objects An array containing all the member variables...
Developing New Mozilla Features - Archive of obsolete content
more members who are already familiar with and to the Mozilla world. Develop relationships with existing developers in the area of your feature If you want to add a big new feature to mail, spend some time helping the existing mail developers. Talk to the developers about fixing some of their bugs. Fix some bugs. Have some of your QA team get involved. Once you're familiar with an area, do the
completely unexpected and write a piece of documentation. Developers will be grateful, and you'll be known as someone seriously interested in contributing. Become familiar with our code review processes. Have someone on your team become Mozilla-savvy enough to obtain CVS access. Help the existing developers to understand that you are "for real" That you have a clue about Mozilla development; that your t...
Embedding FAQ - Archive of obsolete content
splay(); 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
completed(ProgressEvent event) { nsIDOMDocument doc = browser.getDocument(); System.out.println(doc); } }); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } ...
External CVS snapshots in mozilla-central - Archive of obsolete content
Those directories shall be considered read-only, changes shall be delivered to the upstream software projects. Eventually we'd like to have ACLs, but as of today there is no protection for accidental commits to those directories. Such changes will get overwritten without warning on importing the next updated version. ...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
eateInstance on NS_CONTENT_HANDLER_CONTRACTID_PREFIX + aContentType and expecting back an nsIContentHandler). If a handler is found, we call HandleContent on it to give it a chance to take over the load. If it does so, we abort the entire dispatch process right here and cancel the necko request; we will not be getting a stream listener to stream data into, since the content handler has taken over
completely. If at this point we do not have an nsIURIContentListener, we have failed to find a way to handle this content type. If that is the case, DispatchContent tries to convert the data to some other content type by looking for a stream converter (implementing nsIStreamConverter) that takes our content type as input and outputs the magic type "*/*" (which just means we'll take anything it can give ...
Helper Apps (and a bit of Save As) - Archive of obsolete content
er wants if the user has decided (save to disk and open in helper are the current options the user has). Helper App dialog This is our implementation of nsIHelperAppLauncherDialog It calls back to the nsExternalAppHandler to let it know what the user picked Saving to disk If a user decides to "save to disk", we just move/copy the temporary file over to the chosen location once the download
completes. If an error occurs while we do this we delete the temp file and put up an error dialog. Launching a helper application This is delegated to the nsPIExternalAppLauncher (also implemented by the nsExternalHelperAppHandler): Windows: launch either directly via nsIProcess or via the ::ShellExecute() method depending on where the MIMEInfo came from. Last-ditch check for executable files here. ...
generateCRMFRequest() - Archive of obsolete content
ld be used to wrap the private key being escrowed. The user will be prompted for confirmation whenever a key will be escrowed. Only key exchange keys will be escrowed. If a dual use key is being generated, it will not be escrowed. The value of this argument is a base-64 encoded certificate. "CRMF Generation Done Code" This parameter is JavaScript to execute when the CRMF generation is
complete. keySizeN The size in bits of the Nth key to generate "keyParamsN" This string is an optional algorithm dependent parameter value. For Diffie-Hellman it is used to specify p and g parameters. For DSA, it will be used to specify pqg. If the key generation requires parameters and the value passed in is NULL, then the client will generate the parameters on its own. Currently,...
Java in Firefox Extensions - Archive of obsolete content
rd 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 from within an XPCOM component rather than from XUL is to maintain a singleton (some singular Java object) across all Firefox windows. If you call Java from XUL, then each Firefox window will have its own class loader and hence its own "singleton". The following approach is taken from the extension XqUSEme (note you must use the latest vers...
Simple Storage - Archive of obsolete content
-- simply uses that data: myStorage.fribblefrops.forEach(function (elt) console.log(elt));var bar = myStorage.heimelfarbs.bar;jetpack.notifications.show(bar.baz); That's all there is to it! Note that these examples create a myStorage variable to emphasize the fact that jetpack.storage.simple is just a normal JavaScript object. They could have simply used jetpack.storage.simple directly. Here's a
complete real-world example. It's a simple note-taking jetpack. Select some text on the page, right-click, and select Note. The text will be remembered across browser restarts as a note. All notes are shown in the Tools menu. You can install this example from the Jetpack Gallery. jetpack.future.import("menu");jetpack.future.import("selection");jetpack.future.import("storage.simple");// Create the persiste...
Simple Storage - Archive of obsolete content
simply uses that data: myStorage.fribblefrops.forEach(function (elt) console.log(elt)); var bar = myStorage.heimelfarbs.bar; jetpack.notifications.show(bar.baz); That's all there is to it! Note that these examples create a myStorage variable to emphasize the fact that jetpack.storage.simple is just a normal JavaScript object. They could have simply used jetpack.storage.simple directly. Here's a
complete real-world example. It's a simple note-taking jetpack. Select some text on the page, right-click, and select Note. The text will be remembered across browser restarts as a note. All notes are shown in the Tools menu. You can install this example from the Jetpack Gallery. jetpack.future.import("menu"); jetpack.future.import("selection"); jetpack.future.import("storage.simple"); // Create the pers...
statusBar - Archive of obsolete content
Namespace: jetpack.statusBar Methods copyBackground embedIframe append The append Methods adds a new Item to the statusbar. Many of the options are optional. Syntax jetpack.statusBar.append(options); Possible Options are: url width (string/length) The width of the Panel-Item html (string) The html Code which will be used inside the Item onLoad (event) This Event fires when the Item was appended. Its acutally not implemented in the current Version. ...
New Security Model for Web Services - Archive of obsolete content
ll that do not directly hurt the user who reconfigured his browser to try to access some external service but hurts the owners of other services behind the firewall. Signed Scripts A certain degree of additional trust may be lent to a script by having the author digitally sign it. But signed scripts have not really caught on as they require certificates do not change the basic problem that some
completely-unknown party has written a script that might now have access to internal resources. Asking the User Where the sandbox cannot otherwise determine whether the executing script should be permitted access to the resource, a dialog box may be raised to ask the user to grant special privileges. This is currently permitted for locally-saved scripts and signed scripts. This could be combined with th...
Plug-n-Hack Phase1 - Archive of obsolete content
a separate webserver (e.g. for testing); Plug-n-hack requires tool and service manifests to be served from the same origin as the API endpoints but, for testing purposes, Ringleader (the Firefox addon implementation of the browser component) allows you to set a preference to relax or disable origin checks. The preference is ringleader.check.origin This can be set to 'off' to disble origin checks
completely, or 'noport' to disable only port checks. Security tool commands manifest An example commands manifest (for OWASP ZAP) is: https://code.google.com/p/zap-extensions/source/browse/branches/beta/src/org/zaproxy/zap/extension/plugnhack/resource/service.json Firefox UI In Firefox the tool commands will be made available via the Developer Toolbar (GCLI) https://developer.mozilla.org/docs/Tools/GCLI A...
Plug-n-Hack - Archive of obsolete content
) request. PnH allows security tools to declare the functionality that they support which is suitable for invoking directly from the browser. A browser that supports PnH can then allow the user to invoke such functionality without having to switch to and from the tool. While some of the PnH capabilities do have a fixed meaning, particularly around proxy configuration, most of the capabilities are
completely generic, allowing tools to expose whatever functionality they want. Implementing the above features in Firefox and the tools that we work on and support gives our team an advantage, however we believe that opening up such capabilities to all browsers and all security tools is much more useful for security researchers and application developers and testers. As a result we have designed and devel...
HostWindow - Archive of obsolete content
er itself cannot be hidden as it is the only UI to show a collapsed sidebar. When not displayed the entire sidebar area, including the splitter are hidden. Note: The sidebar is currently not supported. We are considering whether to support a sidebar in future versions of Prism and welcome input on this subject. Status - Area of the statusbar that displays the loading status message and a "percent
complete" progress bar, as well as the "gear" menu that provides access to Prism commands such as displaying the error console. To display the status bar, the statusbar option in webapp.ini must be set to true. Command Menu - A popup menu showing several Prism-specific commands. ...
Prism - Archive of obsolete content
pecific features like shortcut creation and dock/tray icons. We intend to propose these extensions for inclusion in future versions of XULRunner. Firefox extension: A Firefox extension, code-named "Refractor", can be used to spin out new Prism apps from inside the web browser. Refractor adds a new menu item to call up the shortcut creation dialog for inside Firefox. Web apps can also point to a
complete web app bundle or some elements of a web app (like higher resolution icons). Refractor automatically takes this information into account. Documentation Frequently Asked Questions Bundles A web application bundle is a zip archive that holds a configuration file, icons and...
RDF Datasource How-To - Archive of obsolete content
model. The tree tag will be treated as if it has the ID attribute with a value http://foo.bar.com/. <template>...</template>. The XUL template that is used to build content from the graph. Starting with the resource that corresponds to the tree element, http://foo.bar.com/, the graph will be traversed and content will be constructed using the pattern specified within the template tags. For a
complete description of how content is built from RDF, see the XUL:Template Guide. 1 As of this writing, it is not currently possible to implement JavaScript XPCOM components; however, it may soon be possible to do so via XPConnect. Update: JavaScript XPCOM should now be possible. Contact: Chris Waterson (waterson@netscape.com) Original Document Information Author(s): Chris Waterson Last Updated Date...
Frequently Asked Questions - Archive of obsolete content
led. This is done by toggling a hidden user configuration preference (pref). To access the pref type about:config into the URL bar, then type svg.enabled into the Filter field. When you double click on the pref you will see its value change to and from true/false, turning the native support on/off. How does Mozilla's SVG implementation compare to Adobe's? Mozilla's native implementation is less
complete than Adobe SVG Viewer's in general. There are major features such as filters and SMIL based animation that have still to be implemented in Mozilla. However, Mozilla's implementation already supports some things that Adobe's lacks, particularly parts of the XML and SVG DOMs. For example we support SVG exceptions and SVGTransform objects. How do you install Adobe's SVG Viewer in Mozilla? The SVG ...
Safely loading URIs - Archive of obsolete content
ther in how the source of the URI is identified and in what is known about the URI to be loaded. In general, the following guidelines apply for Gecko 1.8: If you plan pass a URI string to nsIWebNavigation.loadURI (which can happen indirectly, e.g. by passing the string to something that loads it in a <browser> or <iframe>), you must call checkLoadURIStr to be secure. There's no way to do this
completely securely in Gecko versions prior to 1.8.0.4. If you're doing anything else (passing a URI string to some other API like window.open or <img src="">, passing a URI object to an API that loads URI objects, etc.) use whichever method best fits the data you can get your hands on. If you have a choice as to what data you have, prefer checkLoadURIWithPrincipal to checkLoadURI and prefer checkLoadURI...
Space Manager High Level Design - Archive of obsolete content
a BandData collection, which is largely made up of nsTrapezoid data. Use Case Use Case 1: Space Manager is Created / Destroyed Space Manager instances are created in the nsBlockFrame's Reflow method. An instance is created The BlockReflowState's previous Space Manager is saved off. The new Space Manager instance is associated with the BlockReflowState. After the block frame's Reflow has
completed, the old Space Manager instance is re-associated with the BlockReflowState The new Space Manager is destroyed. If the BlockReflowState already had a Space Manager instance associated with it, it is stored off before being replaced, and the returned to the BlockReflowState instance after the new one has been destroyed. Thus, Space Managers are effectively 'nested' during reflow, with each new b...
Supporting private browsing mode - Archive of obsolete content
Firefox 3.5 introduced private browsing mode, in which potentially private information is not recorded. This includes cookies, history information, download information, and so forth. When private browsing mode is enabled, temporary, databases are created to be used for cookies and local storage; these databases are thrown away when private browsing mode is turned off, and the regular databases are re-activated. The temporary cookie and local storage databases start out empty. ...
Table Cellmap - Archive of obsolete content
gment to come from the table level down to the rowgroup level nsCellMap* map = mFirstMap; while (map) { if (map->GetRowCount() > rowIndex) { // Add your action here } rowIndex -= map->GetRowCount(); map = map->GetNextSibling(); } Data entry The usual way to populate the cellmap is via nsTableFrame::InsertRows. Enabling the debug code at the function entrance and exit gives a quite
complete picture of the cellmap structure. Below follows the dump for the 2x2 table. insertRowsBefore firstRow=0 ***START TABLE DUMP*** mColWidths= row(0)=02763344 cell(0)=02763528 cell(0)=0276381C row(0)=02763940 cell(0)=02763990 cell(0)=02763AB4 ***** START TABLE CELL MAP DUMP ***** 023566B0 cols array orig/span-> 023566B0 ***** START GROUP CELL MAP DUMP ***** 023565B0 mapRowCount=0 tableRowCount=0...
Running Tamarin acceptance tests - Archive of obsolete content
as skipping... reason: 2531 running abcasm/adhoc.abs skipping... reason: inconsistencies in different debug output, need to implement regex matching of diffs 2527 running abcasm/branchToCommon.abs 2530 running abcasm/arithmetic.abs 2529 running abcasm/bkpt.abs 2528 running abcasm/bkptline.abs 2526 running abcasm/bug_476556.abs 2524 running abcasm/bug_491056.abs ... test run PASSED! Tests
complete at 2010-09-28 10:39:26.751797 Start Date: 2010-09-28 10:38:07.221457 End Date : 2010-09-28 10:39:26.751797 Test Time : 0:01:19.530340 passes : 59291 failures : 0 expected failures : 75 tests skipped : 76 The -f flag tells runtests.py to force recompilation of all the scripts. For help on runtests.py options, see below or use python runtests.py -h. Notes on u...
Tamarin Acceptance Testing - Archive of obsolete content
In order to ensure that changes to the Tamarin code base are high quality before submitting, all developers are required to
complete the following steps. Successfully build release and debug versions of the shell with the debugger enabled [info] Successfully run the following test suites: acceptance test suite [info] self tests [info] Submit a sandbox build request to test against platforms that you may not have locally [info] Available Tamarin Acceptance Test Suites Actionscript Acceptance Tests: Actionscript Acceptance Tests Running Tamarin acceptance tests Abc Assembler Tests Cmdline tests Performance Tests Actionscript Performance Tests Running Tamarin performance tests Built-in self tests ...
The Download Manager schema - Archive of obsolete content
currBytes INTEGER The current number of bytes that have been downloaded. Defaults to 0, may not be null. maxBytes INTEGER The total number of bytes that need to be downloaded. Defaults to -1, may not be null. mimeType TEXT The MIME type of the file. preferredApplication TEXT The preferred application to use to open the file after the download is
complete. preferredAction INTEGER The action constant from nsIMIMEInfo representing the action to take upon completing the download. Default 0 (save to disk); may not be null. autoResume INTEGER 0 if the file should not automatically resume downloading, 1 if it should. Defaults to 0, and may not be null. See also nsIDownloadManager nsIDownloadManagerUI nsIDownload...
[Deprecated] The Mozilla build VM - Archive of obsolete content
th Building Firefox instead. Other links of interest may include: Developer guide (documentation about developing on and for Mozilla projects). Mentored bugs have a mentor who commits to helping you every step of the way. Generally, there should be enough information in the bug to get started. Whenever you need help, contact the mentor via Matrix, in the bug itself, or by email. When you've
completed the bug, they will help you get your code into the tree. "Good" first bugs may be a little stale, but at some point in their lives we considered that they would be a good first step for newcomers to Mozilla. We are in the process of migrating these bugs to mentored bugs, but more recent "good first bugs" may be good starting points if there are no appropriate mentored bugs. You can also ask y...
Menus - Archive of obsolete content
to be shared between each window without having to duplicate code. This technique may be used for individual menus or for an entire menu bar. For example, to have a Tools menu that is shared between all windows, just create a menu in the overlay, and include it in each window with a single line: <menu id="menu-tools"/> The overlay should have a menu with the same id 'menu-tools' containing the
complete definition of the menu. If you wish to have slight differences between each window, one possibility is to show or hide menu items in a load event listener. For example, to have an item initially hidden in a window: function initMenus() { var item = document.getElementById("menu-file-open"); item.hidden = true; } The hidden property is set to true to hide the menu with the id 'menu-fileOpe...
Panels - Archive of obsolete content
ng code: <label value="Search" popup="search-panel"/> The result is a search button which opens a panel for entering the search term. When using the popup attribute, the panel will appear with the top left corner at the mouse position. In this case, you may wish to have the popup appear below the label instead. The position attribute may be used to control the placement of the popup. Here is a
complete example: <panel id="search-panel" position="after_start"> <label control="search" value="Terms:"/> <textbox id="search"/> </panel> <label value="Search" popup="search-panel"/> The position attribute has been added to the panel element with the value 'after_start'. This causes the panel to be displayed not where the mouse was clicked but aligned along the bottom edge of the label. For more...
Special per-platform menu considerations - Archive of obsolete content
ecting this item will hide all other applications except this one. menu_mac_show_all Selecting this item will show the windows for all applications. checkForUpdates The item that opens the Update dialog for the application, for applications that have one (such as SeaMonkey; Firefox does not have this item). The last five items aren't normally used but are listed for
completeness. Here is an example: <menubar> <menu label="Tools"> <menupopup> <menuitem label="Spell Check"/> <menuitem id="menu_preferences" label="Preferences" oncommand="window.openDialog('options.xul', '_new', 'chrome');"/> </menupopup> </menu> </menubar> This menu item will be placed on the application menu on the Macintosh but left in the Tools menu on ot...
editable - Archive of obsolete content
<< XUL Reference editable Type: boolean Returns true if the element is editable. Auto
complete fields are editable so this property always returns true for those. ...
textbox.label - Archive of obsolete content
erence label Type: string Sets the label attribute. Gets the label attribute if it is present and not empty. Otherwise it returns the value of the associated label element, if applicable. Otherwise it returns the placeholder or emptyText property. The getter is mostly useful for screen readers. Note: Prior to Firefox 3, and always in Thunderbird and SeaMonkey, the label property of an auto
complete textbox returns its value, for compatibility with the menulist element. ...
Actions - Archive of obsolete content
item variable, the id will be set to this value. Then, the remaining attributes on the element are examined and any variables are replaced in place. That is, the text ?relateditem in the label attribute will be replaced with the string 'http://www.xulplanet.com/rdf/B' for the first result. In the image, you can see that the label for the first button does indeed have this value. Processing is now
complete for the first result, so the builder moves on to the next result. For result B, the builder would have generated the following content: <button id="http://www.xulplanet.com/rdf/B" label="http://www.xulplanet.com/rdf/B"/> Naturally, you wouldn't use an id attribute inside a template action since the id would be replaced anyway. In fact, any ids you put inside a template action will be ignored. Ho...
Introduction - Archive of obsolete content
g gets generated again. An interesting thing to note is that due to the nature of the RDF parsing process, the builder generates results and builds content incrementally while the data arrives. Of course, since the data arrives so quickly from the network, you really don't notice this. If the datasource is already loaded, the builder can construct content all in one step, although even this isn't
completely true as we'll see later. For XML datasources, use a querytype of xml. The datasources attribute should be the URL of an XML file, which can be either the location of a web site or a file on the local file system, using its file or chrome URL. This file will be loaded and the resulting XML document will be used as the datasource when the template builder generates results and creates content. Fo...
RDF Modifications - Archive of obsolete content
The RDF observer also has two methods onBeginUpdateBatch and onEndUpdateBatch. These are called when performing a lot of operations on a datasource. When changing the datasource, the changes are surrounded by begin and end batch calls. Then, rather than notify on every change, the datasource will send one notification when the changes are finished. The template builder then rebuilds the template
completely when done. This is useful when making a large amount of changes to avoid having to keep recalculating parts of the template that might change again quickly. Adding RDF Triples Let's say we've just added the triple below to the datasource. subject: http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg predicate: http://purl.org/dc/elements/1.1/description object: One of the thirty or so Egyp...
Sorting Results - Archive of obsolete content
nly one column should have the sortActive attribute set to true at a time. The tree will change both attributes as necessary automatically when the column headers are clicked or the tree is sorted by other means. If you don't want to allow sorting by a certain column, you can leave out the sort attribute. Only specify this attribute on columns that you wish to allow the user to sort by. Here is a
complete example of sorting a tree. The sort attribute should be set to the variable that holds the values to sort by. Usually, this would be the same variable that is used to generate the label for the cells in that column, however this is not actually necessary. For instance, in the example the second column sorts by date, but if you were to use a different variable such as ?description, the tree would ...
Template Logging - Archive of obsolete content
ta didn't exist for a particular result. In the above example, some people may not have names. These people will not match the query but it will not cause an error. Thus, if no error is logged, it generally indicates an issue with the data or that the data does not match the query being used. We could debug this by removing parts of the query bottom up, for instance, removing the <triple> element
completely and seeing whether any results or content is generated. Remember to use the logging flag as described above to see whether any results are being generated. Unfortunately, detecting network or parsing errors with the data itself can be difficult. Naturally, semantic errors in the data in the datasource can't be easily detected automatically. However, for XML datasources, you can at least check t...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
this setting. If your text editor does not support UTF-8, search the Internet for a better one that you can download. Optional tools You can optionally use any image editor to customize the images. You can optionally use a jar tool or zip tool to package your button as a cross-platform installable (XPI) for other people to install and use. Making a button There are nine easy steps. When you have
completed all the steps, you will have a structure like this in the directory where you installed SeaMonkey: 1. Go to the directory where you installed SeaMonkey, then go to the chrome directory there. Note: For information about how to find the directory where you installed SeaMonkey, see: Installation directory If you cannot easily find the directory, you can use the following m...
Custom toolbar button - Archive of obsolete content
setting. If your text editor does not support UTF-8, search the Internet for a better one that you can download. Optional tools You can optionally use any image editor to customize the images. You can optionally use a jar tool or zip tool to package your button as a cross-platform installable (XPI) for other people to install and use. Making a button There are ten easy steps. When you have
completed all the steps, you will have a structure like this in your profile directory: The profile directory and the extensions directory already exist. You will add the other directories and files that are shown in the diagram. (Other directories and files also exist, but the diagram does not show them.) 1. Go to the profile directory that you use for the application, then go to the extensions d...
Toolbars - Archive of obsolete content
and toolbar buttons. Toolbar customization events A look at the events that are sent during toolbar customization; you can use these to be kept aware of changes to toolbars. Creating toolbar buttons How to use overlays to add toolbar buttons to Mozilla applications. Custom toolbar button Another example of how to create a toolbar button,
complete with a sample extension you can download and try. Code snippets: Toolbar Code snippets that are helpful when working with toolbars. Community View Mozilla extension development forums... Mailing list Newsgroup RSS feed #extdev IRC channel MozillaZine forum about:addons newslett...
Adding Event Handlers - Archive of obsolete content
e window again. You can respond to an event during either the capturing or bubbling phase. Once the event has finished propagating, any default action will occur, which is the built in behaviour of the element. For example, when the mouse is moved over a button that is inside a box, a 'mousemove' event is generated, and sent first to the window, followed by the document, and then the box. That
completes the capturing phase. Next, the 'mousemove' event is sent to the button. Finally, the bubbling phase causes the event to be sent to the box, document and window. The bubbling phase is essentially the reverse of the capturing phase. Note that some events don't do the bubbling phase. You can attach listeners to each element to listen to the events during each step of event propagation. Due to the ...
Adding Labels and Images - Archive of obsolete content
fferent than HTML (image instead of img). You can use the src attribute to specify the URL of the image file. The example below shows this: <image src="images/banner.jpg"/> Although you can use this syntax, it would be better in order to support different themes to use a style sheet to set the image URL. A later section will describe how to use style sheets, but an example will be shown here for
completeness. You can use the list-style-image CSS property to set the URL for the image. Here are some examples: XUL: <image id="image1"/> <image id="search"/> Style Sheet: #image1 { list-style-image: url("chrome://findfile/skin/banner.jpg"); } #search { list-style-image: url("http://example.com/images/search.png"); } These images come from within the chrome directory, in the skin for the ...
Advanced Rules - Archive of obsolete content
es also, but they hold resources, not text, so they won't likely have meaningful values to users. In the simple rule syntax, you use the syntax uri='rdf:*' to indicate where content should be generated. In the full syntax, you set the value of the uri attribute to a variable which you used in the conditions. Usually, this will be the variable assigned in the child attribute of the member element.
Complete Tree Example The following example shows a
complete tree with conditions and an action. You can view the RDF file separately: wheater.rdf Example 1 : Source <tree id="weatherTree" flex="1" datasources="weather.rdf" ref="http://www.xulplanet.com/rdf/weather/cities"> <treecols> <treecol id="city" label="City" primary="true" flex="1"/> <treecol id="pred" label="Prediction" flex="1"...
Box Objects - Archive of obsolete content
the box is the base of all displayed XUL elements. However, there are a number of subtypes, about 25 or so, for specific XUL elements. Some of these subtypes, such as the stack or listbox are needed for more complex layouts than the basic box, while others such as the button are used only to add extra mouse and key event handling. The layout object associated with an element can be removed and a
completely different type of object created just by changing the CSS display property, among others. For example changing the display property of a button element to block will cause the button layout object to be deleted and a block object to be created instead. Naturally, this will change the appearance and function of the element. It isn't necessary to know the details of how the layout objects are con...
Commands - Archive of obsolete content
is case, you just need to attach a controller to a listbox which will perform the action in its doCommand method. Try opening the example below (Source View) in a browser window and selecting 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. <window id="controller-example" title="Controller Example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init() { var list = document.getElementById("theList"); var listController = { supportsCommand : function...
Content Panels - Archive of obsolete content
a very simple interface for a web browser. A box has been created containing two elements: a toolbox and an iframe. A Back button, a Forward button and a field for typing is URLs has been added to the only toolbar (We'll learn about toolbar in a later section). The web pages would appear inside the iframe. In this case, the file index.html would appear by default. This example isn't functionally
complete. Next, we would want to add script which changes the src attribute at the desired time, for example when the user presses the Enter key. Browsers There is a second type of content panel, using the browser tag. You would use this when you want to create a frame that displays content like a browser. Actually, the iframe can do this too, but the browser has a variety of additional features. For...
Install Scripts - Archive of obsolete content
e(Install.LOCALE | Install.DELAYED_CHROME, getFolder(findDir, "locale")); The DELAYED_CHROME flag is used to indicate that the chrome should be installed the next time Mozilla is run. Installation Completion The addDirectory() and addFile() functions don't copy any files. They only state which files should be installed. Similarly, registerChrome() only states that chrome should be registered. To
complete the process and begin copying files, call the performInstall() function. It takes no arguments. The final script for installing the find files component is shown below: Source initInstall("Find Files","/Xulplanet/Find Files","0.5.0.0"); findDir = getFolder("Chrome","findfile"); setPackageFolder(findDir); addDirectory("findfile"); registerChrome(Install.CONTENT | Install.DELAYED_CHROME, ge...
Introduction - Archive of obsolete content
he Mozilla platform which allows you to create standalone XUL applications. A browser isn't required to run these applications, as they have their own executable file. XUL package In between the other two are applications which are created in the same way as an extension, but they act like a separate application in a separate window. This is used when you don't want to have the larger size of a
complete XULRunner application, but don't mind requiring a Mozilla browser to be installed to be able to run the application. Remote XUL application You could also just place XUL code on a web server and open it in Firefox, as you would any other web page, however this is discouraged and was disabled in Firefox 8. It is still possible to enable this for selected sites to let legacy apps to continue wor...
RDF Datasources - Archive of obsolete content
el="rdf:http://www.some-fictitious-zoo.com/rdf#name"/> <treecell label="rdf:http://www.some-fictitious-zoo.com/rdf#species"/> </treerow> </treeitem> </treechildren> </rule> </template> </tree> Here, the data has been generated from the file. The ref attribute has been set to the root element in the RDF file, which is the top-level Seq. This will give us a
complete list of animals. If we wanted to, we could set the ref attribute to any of the other about attribute values to limit the set of data that is returned. For example, to display only the reptiles, use a value of http://www.some-fictitious-zoo.com/reptiles. Setting the ref Attribute Example The example below shows how to display a particular piece of an RDF datasource by setting the ref attribute. Ex...
Stacks and Decks - Archive of obsolete content
elements create text with a size of 15 points. The first, however is offset one pixel to the right and down by adding a padding to its left and top sides. This has the result of drawing the same text 'Shadowed' again but slightly offset from the other. The second description element is drawn in red so the effect is more visible. This method has advantages over using text-shadow because you could
completely style the shadow apart from the main text. It could have its own font, underline or size. (You could even make the shadow blink). It is also useful as Mozilla doesn't currently support CSS text shadowing. A disadvantage is that the area taken up by the shadow makes the size of the stack larger. Shadowing is very useful for creating the disabled appearance of buttons: Example 2 : Source View <...
Tree View Details - Archive of obsolete content
e removed. Finally, we use the splice function to remove the rows from the visibleData array and call the rowCountChanged function to redraw the tree. When deleting rows, you will need to supply a negative count of the number of rows to delete. Whether opening or closing a row, we need to tell the tree to repaint the twisty in the new state. The easiest way to do this is to invalidate the row.
Complete Example There are several other view functions we can implement but they don't need to do anything in this example, so we can create functions that do nothing for those. They are added near the end of the
complete example, shown here: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window onload="init();" xmlns="http://www.mozilla.org/keymaster/ga...
Using nsIXULAppInfo - Archive of obsolete content
o use this code: var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo); (For explanation see this Creating XPCOM article.) Getting application information After you obtained the app info component, you can read its properties to get the application's ID, human-readable name, version, platform version, etc. For
complete list of nsIXULAppInfo's properties, please see nsIXULAppInfo interface description. ID You can tell which application you're running under using the nsIXULAppInfo.ID property. const FIREFOX_ID = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"; const THUNDERBIRD_ID = "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; const SEAMONKEY_ID = "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}"; var appInfo = Components.classe...
Using the Editor from XUL - Archive of obsolete content
The <iframe> contents are then editable. Note that the <editor> element is really just an <iframe> which takes over some of the task of creating the editor from JavaScript. Editor creation So let's trace through the process of editor creation when bringing up the composer window. ...
Using the standard theme - Archive of obsolete content
At the beginning, there is no style When creating a new XUL <tt>window</tt> (or a new <tt>dialog</tt>, for that matter) in your extension, and you do not associate a style sheet with it, your widgets will be unstyled. ...
Writing Skinnable XUL and CSS - Archive of obsolete content
overlays should never import the global skin (or any other skin for that matter). They are already derived skins and therefore should not inherit from global. They should instead rely on the context in which they will appear for color, font, and border information. For example, the sidebar should not import the global skin, since it could appear in Messenger and in Navigator (which could have two
completely different color schemes). If it imported the global skin, then when it was overlayed into Navigator, it would potentially clash (if the user's current chosen Navigator skin were NOT inheriting from global). Derived skin files should not contain any font, color, or border information. This information should only be found in base skin files. The skin file should instead inherit from a base skin...
XUL controls - Archive of obsolete content
ered. <textbox value="firefox"/> More information about the textbox element. Textbox Reference <textbox multiline="true"> A textbox which allows multiple lines of text to be entered. <textbox multiline="true"/> More information about the multiple line textbox element. Textbox Reference <textbox type="auto
complete"> A textbox that provides a dropdown showing matches that would
complete what the user types. The user can select one to have it filled into the textbox. <textbox type="auto
complete" auto
completesearch="history"/> Textbox Reference <textbox type="number"> A textbox for entering numbers. Two arrow buttons are displayed for cycling through values. ...
menulist - Archive of obsolete content
e value of the crop attribute. description Type: string Set to the description of the currently selected menuitem. disableautoselect Type: boolean Gets and sets the value of the disableautoselect attribute. disabled Type: boolean Gets and sets the value of the disabled attribute. editable Type: boolean Returns true if the element is editable. Auto
complete fields are editable so this property always returns true for those. editor Type: nsIEditor A reference to the nsIEditor for editable text. This property is read only. image Type: image URL The image associated with the currently selected item. inputField Type: textbox element A reference to the textbox element used for editable menu lists. This property is read only and applies...
panel - Archive of obsolete content
lease see popup positioning titlebar Type: string Set the panel's titlebar attribute to the value normal to display a panel with a titlebar. The noautohide attribute must be set to true. top Type: integer Overrides the vertical position of the popup specified by the showPopup method. type Type: string The panel type. Should be one of the following: auto
complete Specify this for a panel that provides a tree for an auto
complete element. auto
complete-richlistbox Specify this for a panel that provides a richlistbox for an auto
complete element. arrow Specify this for a panel that provides an arrow pointing at its anchor. drag Specify this for a panel that's being used as a drag image for a drag and dr...
preference - Archive of obsolete content
System article. Attributes disabled, instantApply, inverted, name, onchange, readonly, tabindex, type Properties defaultValue, disabled, hasUserValue, inverted, locked, name, preferences, readOnly, tabIndex, type, value, valueFromPreferences Methods reset Examples <preferences> <preference id="pref_id" name="preference.name" type="int"/> </preferences> See Preferences System for a
complete example. Attributes disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. Do not ...
resizer - Archive of obsolete content
Note: Starting in Gecko 2.0, you can also specify a target element using the element attribute, to use the resizer to resize the specified element instead of the window. ...
titlebar - Archive of obsolete content
. If the titlebar is in a panel element, dragging it will move the panel. Elements inside the titlebar usually don't receive any mouse events, so e.g. buttons inside it can't be clicked and textboxes can't be focused with the mouse. If you don't want this behavior, you can override it by setting allowevents="true" on the titlebar element. The titlebar will send a command event after the move is
complete. Examples 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. <?xml version="1.0"?> <window title="Movable HUD Window" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" width="300" height="200" style="background: transparent; -moz-appearance: none;"> <titlebar flex="1" oncomm...
tree - Archive of obsolete content
nsITreeView The view for the tree, which is the object which generates the data to be displayed. You can 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. Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassNam...
Application Update - Archive of obsolete content
This article will hopefully explain how to update your XulRunner application using the same method that Firefox, Thunderbird, Songbird, and ChatZilla use. Getting Started You will need the following utility scripts from http://lxr.mozilla.org/mozilla/sourc...ate-packaging/ (or local source of XulRunner) common.sh make_full_update.sh You will need mar / mar.exe to build a
complete update patch. You will need to compile a unix/linux executable mar from mozilla/modules/libmar. As far as I can tell enabling the options --enable-updater and --enable-update-packaging on your configure will build you mar. Compiled versions of mar are available in the Gecko SDK under the folder /host/bin for your OS. In order to generate SHA1 hashes I installed shash. Application Se...
Building XULRunner with Python - Archive of obsolete content
71.bat is used to launch the build console (MSys from the MinGw project ). If you plan to checkout often into empty folders you could modify it to set the CVSROOT environment variable. set CVSROOT=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot Having created amozilla project directory (e.g.C:\projects\mozilla or/c/projects/mozilla in msys) create the following .mozconfig file. Note this is
complete and does not require the checkout of any other project specific .mozconfig files as sometimes shown. It effectively specifies a release build that is not particularly suitable for debugging XULRunner itself. It uses the trunk (or latest) code in CVS so may be unstable. mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/../obj-xulrunner mk_add_options MOZ_CO_PROJECT=xulrunner ac_add_options --enable-applicati...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
dy do this one? Nope. Mozilla has a separate Makefile.in for each directory that is part of the build. In this case, you'll be a happy, healthier and more well-balanced if you don't try to understand the file at all. Just copy it from McCoy. You don't even have to substitute in your application name for mccoy since it uses the APP_NAME variable. application.ini - used for application packaging. A
complete description can be found in XUL Application Packaging. In this case you can basically copy over the file as is, since once again variables are used for things like the application name and version. But you will have to change the ID to something unique to your app. default-prefs.js - these are the default Mozilla preferences used by XULRunner when running your app. The important ones are describe...
MacFAQ - Archive of obsolete content
Note that in order to copy the framework while keeping the relative soft-links in the framework, do something like: % ( cd dist ; gnutar cf - XUL.framework | ( cd /Library/Frameworks ; gnutar xf - )) Installing Your Application Your application must be installed as a XULRunner app before you can open it. ...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
q.Action = ns + '#' + method; SOAPClient.SendRequest(req, callback); Diff between jqSOAPClient.js and saSOAPClient.js 42c42 < var jsOut = $.xmlToJSON(xData.responseXML); --- > var jsOut = XMLObjectifier.xmlToJSON(xData.responseXML); 46,60c46,62 < $.ajax({ < type: "POST", < url: SOAPClient.Proxy, < dataType: "xml", < processData: false, < data: content, <
complete: getResponse, < contentType: SOAPClient.ContentType + "; charset=\"" + SOAPClient.CharSet + "\"", < beforeSend: function(req) { < req.setRequestHeader("Method", "POST"); < req.setRequestHeader("Content-Length", SOAPClient.ContentLength); < req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer); < req.setRequestHeader("SOAPAction", soapReq.Action); < } <...
XULRunner - Archive of obsolete content
tips for working with XULRunner. Deploying XULRunner An introduction on how to package your application with XULRunner. XULRunner Hall of Fame Tracks all available applications based on XULRunner. Build Documentation Learn how to get the source and build it. Debug Documentation Steps to configure Venkman to debug your App XULRunner Guide A fairly
complete, but outdated, introduction and tutorial for XULRunner which collates much of the documentation found here. View all... Community View Mozilla forums... Mailing list Newsgroup RSS feed #xulrunner on irc.mozilla.org Other community links... Related topics XUL See also A brief introduction to XULRunner ...
mozilla.dev.platform FAQ - Archive of obsolete content
) A: When you <tt>--disable-libxul</tt>, the XPCOM glue doesn't have information about how to load all the dependent libraries like <tt>libgfx.dylib</tt>. In order to use XR successfully in <tt>--disable-libxul</tt> mode, you have to setup DYLD_LIBRARY_PATH to include <tt>/Library/Frameworks/XUL.framework/Versions/1.9a1</tt> - Benjamin Smedberg, Fri, Oct 20 2006 9:12 am Q: When I try to build a
completely standalone XUL app on OS X (10.4.8). took an Foo.app directory created with xulrunner-bin --install-app and tried to copy (using rsync -rl) the XUL.framework directory into a Frameworks directory in the .app bundle and then deleting the XUL.framework directory from /Library/Frameworks, my running my app fails silently. It works fine when the XUL.framework is installed in /Library/Frameworks. An...
Mozilla release FAQ - Archive of obsolete content
between several pages, the user may have images turned off or lack capabilities to use a certain type of media. Dynamically generated pages make this nearly impossible. Devising a system that would handle all of these situations would make web servers more complex, slower, and likely hurt the transfer time that this proposal is attempting to save. Also, progressive display of the webpage would be
completely gone with this idea. For these reasons, this is generally considered a bad idea. I'd like to port Mozilla to XXXOS. Any advice? If you're targeting a relatively recent Unix, you probably will have very few problems. Otherwise, the more Unixlike the target system is, the easier your port will go. I would suggest that before you devote much time and effort to your port, you consider: How many ...
Format - Archive of obsolete content
Summary: mozilla.dev.planning - July 17-23, 2006 Announcements Firefox 2/Gecko 1.8.1 bug approvals Starting on Friday July 21 at 10:00a PDT the release triage team will no longer be accepting bugs unless they meet one of the posted criteria. Criteria are included in the linked post. Firefox 1.5.0.5 planned release - 2006/07/26 Discussions Firefox survey feedback requested Rachel Werner (Mozilla Corp marketing intern) requested feedback on a proposed user survey. The survey questions and feedback are included in the thread. Deadline for feedback has passed. ...
2006-11-03 - Archive of obsolete content
ggests a feature to compare different versions of a webpage to see what has changed. XML in Firefox is a Major Problem A user draws attention to what they think is a bug, but the developers say it's proper browser behaviour. What GUI lib was used for developing Firefox 2.0 ? A user inquires about what GUI library is used for developing Firefox 2.0. Event in Firefox similar to OnDownload
Complete event in IE A user asks what even can be used that is similar to the OnDownload
Complete even in IE. Meetings None this week. Authors Sara Minchella (sara) Dave Manley (seneManley) Back to Summary List ...
2006-11-04 - Archive of obsolete content
ure A user suggests a feature to compare different versions of a webpage to see what has changed. in Firefox is a Major Problem A user draws attention to what they think is a bug, but the developers say it's propwer browser behaviour. GUI lib was used for developing Firefox 2.0 ? A user inquires about what GUI library is used for developing Firefox 2.0. in Firefox similar to OnDownload
Complete event in IE A user asks what even can be used that is similar to the OnDownload
Complete even in IE. Meetings None this week. Authors Sara Minchella (sara) Dave Manley (seneManley) Back to Summary List ...
2006-11-10 - Archive of obsolete content
Summary: mozilla.dev.apps.firefox - November 4, 2006 - November 10, 2006 Announcements None this week. Discussions site-specific search using our search box A discussion surrounding implementing a way to search a current page with the page's embedded search component and how to make this efficient and usable. Event in Firefox similar to OnDownload
Complete event in IE An inquiry about how to change the font of a web page before it is displayed using an extenstion. favicon as microsummary/feed/other stuff indicator Suggestion about making the favicon create a bookmark for the page with a microsummary. Firefox 2.0 - net accessed when bookmark properties viewed Question about whether Firefox 2.0 downlads the web page again when the properties of the bookmark are viewed. F...
2006-12-01 - Archive of obsolete content
e, others say its a bug! The debate continues. Discussion of support for Modal windows within Firefox 2.0 A lengthy post regarding the re-implementation of modal windows into firefox. Basic Feature that I think is a must in any web broswer A discussion revolving around the idea of having firefox automatically convert mistaken non-English characters to English so that web addresses will be
completed. mozStorage documentation up A revisted discussion surround the mozStorage documentation. rich results for searches A proposal to implement "rich results", a set of registered sites that would provide information as it relates to a user's search. Windows DDE Shell Integration removal A call for responses or concerns regarding the removal of the DDE Shell Integration. How do allow ...
2006-10-06 - Archive of obsolete content
the tree part where host_xpidl was located. He then was able to successfully build ThunderBird. Ludwig Hugelschafer response to the posting. Announcements New SVG build dependency coming On October 2nd T Rowley announced that: Soon SVG on the trunk will be switching to use thebes directly (instead of the current choice of direct cairo or punching a hole through thebes to cairo). Once
completed you will need to build cairo gfx in order to build SVG. https://bugzilla.mozilla.org/show_bug.cgi?id=354866 Taking moz180-linux-tbox down temporarily Oct 6th early afternoon (PDT) On October 5th Rob Helmer announced that: He will be taking the 1.8.0 branch (en-US and l10n) Linux tinderbox down tomorrow afternoon (Oct 6th, PDT) in order to clone the disks and create a staging server for th...
2006-10-13 - Archive of obsolete content
40-workarounds and gcc-and-visibility-one-step-forward-hit-a-brick-wall Announcements Please help us test the new Tinderbox and Bonsai server installations Paul Reed announced that they are setting up a new installation of the Tinderbox and Bonsai servers onto new, supported hardware. Some testing and validation has been done, but they would like other people to look at the installations and
complete the setup before they switch over. New Tinderbox Installation New Bonsai Installation If any inconsistencies are found please use Bugzilla to let them know Discussions There were no discussions this week. Meetings There were no meetings this week. ...
2006-10-27 - Archive of obsolete content
was to add "-L/usr/sfw/lib" into MOZ_CAIRO_LIBS of config/autoconf.mk. MOZ_CAIRO_LIBS = -L$(LIBXUL_DIST)/lib -lmozcairo -lmozlibpixman \ -L/usr/sfw/lib -lXrender -lfreetype -lfontconfig October 27: Alex replied to Masaki posting, stating that he was going to use the work around that he provided and would provide feedback if it was successful or not. Later that day Alex able to successful
complete his Firefox 2 build by using Masaki'swork around that he had posted. update-packaging October 27: atachi.hayash wanted to know if you use MSYS would update-packaging work. Click here to view the errorthat he receives when trying to update-packaging. error building firefox-2.0rc3 October 27: Chotu Atwork is trying to build Firefox-2.0rc3 on uclinux running on a MIPS processor. During his b...
2006-10-06 - Archive of obsolete content
Summary: mozilla.dev.l10n - October 6, 2006 Announcements English United States Dictionary English United States Dictionary for firefox 2. Firefox 2 sign-off procedure Localization team should begin intense QA as outlined here. FFx 2 RC2 testing today L10n builds were
completed was
completed and ready for test. test resumt will be found here Another Lightning localization update with some bad news Difference has been located between SUNBIRD_0_3_BRANCH (for Sunbird 0.3) and MOZILLA_1_8_BRANCH. Sunbird/Lightning localization update You need to update your localization if you want your locale to ship with Lightning 0.3 or Sunbird 0.3. MozillaTranslator 5.13 RFEs new version of MozillaTranslator will be relaesed in a few weeks. Calendar localization update RC1 for Sunbir...
2006-11-3 - Archive of obsolete content
MozillaTranslator 5.13 released MozillaTranslator 5.13 is available here. Opening l10n repository on MOZILLA_1_8_BRANCH for approved check-ins MOZILLA_1_8_BRANCH is opened for approved check-ins. ...
2006-10-20 - Archive of obsolete content
Discussions Sparky AND comet going away on Friday Preed wants to get rid of Sparky and comet (both older desktop class linux boxes). Robert Kaiser gave some background on the boxes. ...
2006-11-10 - Archive of obsolete content
form - November 4th - November 10th, 2006 Announcements No announcements this week Traffic beaufour moves the discussion about XulRunner unit-tests like xpcshell from mozilla.dev.platform to mozilla.dev.quality. Benjamin Smedberg crossposted a notice about Unit Testing For the Mozilla Toolkit, letting developers know about the importance of testing for the improvement of Mozilla 2, and asks for
complete coverage. Several community members comment, backing up Benjamin's post. William VanderPol asks, regarding Remote XUL Applications, if is it possible (or does it exist?) to have an extension that will allow chrome access to certain specified URL's? James Leigh points out that resources are available at O'Reily, in the Creating Applications with Mozilla section. Benjamin Smedberg has been "working...
2006-10-20 - Archive of obsolete content
There are a few concerns with the software updates, and a decision is required on this before a "Go" for RC3 release can be given. Announced by Tim on Friday October 13, 2006. Help required designing new Home for Quality.Mozilla.Org - Talented Web Designers and/or Artists interested in helping the design for Quality.Mozilla.Org please read this posting. If your theme is chosen you will be placed on the hall of fame and will receive a gift from Mozilla. Posted by Jay Patel on October 18th, 2006. ...
NPN_DestroyStream - Archive of obsolete content
NPError reason); Parameters The function has the following parameters: instance Pointer to current plug-in instance. stream Pointer to current stream, initiated by either the browser or the plug-in. reason Reason the stream was stopped so the application can give the user appropriate feedback. Values: NPRES_DONE (most common): Stream
completed normally; all data was sent by the plug-in to the browser. NPRES_USER_BREAK: Plug-in is terminating the stream due to a user request. NPRES_NETWORK_ERR: Stream failed due to network problems. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error Codes. Descripti...
NPN_GetURLNotify - Archive of obsolete content
n of the request by calling the plug-in's NPP_URLNotify() function and passing it the notifyData value. NPN_GetURLNotify() typically handles the URL request asynchronously. It returns immediately and only later handles the request and calls NPP_URLNotify(). This notification is the only way the plug-in can tell whether a request with a null target failed, or that a request with a non-null target
completed. For requests that
complete unsuccessfully, the browser calls NPP_URLNotify() as soon as possible. For requests that
complete successfully: If the target is non-null, the browser calls NPP_URLNotify() after it has finished loading the URL. If the target is null, the browser calls NPP_URLNotify() after closing the stream by calling NPN_DestroyStream(). If this function is called with a tar...
NPP_HandleEvent - Archive of obsolete content
drawable area. The plug-in either handles or ignores the event, depending on the value given in the event parameter of this function. For a list of event types the application is responsible for delivering to the plug-in, see the NPEvent structure. MS Windows The browser gives each windowed plug-in its own native window, often a child window of the browser window, to draw into. The plug-in has
complete control over drawing and event handling within that window. Mac OS The browser does not give a windowed plug-in a native window, because the Mac OS platform does not support child windows. Instead, the windowed plug-in draws into the graphics port associated with the the browser window, at the offset that the browser specifies. For this reason, NPP_HandleEvent is only way the plug-in can receiv...
NPP_StreamAsFile - Archive of obsolete content
, NPStream* stream, const char* fname); Parameters The function has the following parameters: instance Pointer to current plug-in instance. stream Pointer to current stream. fname Pointer to full path to a local file. If an error occurs while retrieving the data or writing the file, fname may be null. Description When the stream is
complete, the browser calls NPP_StreamAsFile to provide the instance with a full path name for a local file for the stream. NPP_StreamAsFile is called for streams whose mode is set to NP_ASFILEONLY or NP_ASFILE only in a previous call to NPP_NewStream. If an error occurs while retrieving the data or writing the file, the file name (fname) is null. See Also NPP_NewStream, NPP_Write, NPP_WriteReady, NPSt...
Adobe Flash - Archive of obsolete content
l fix Flash to be scriptable in Mach-O browsers (on OS X) by version 12. This is currently NOT the case, but 12 is a sufficiently high version number (current versions are version 6r.79) to allow for some leeway for fixing this down the road. When information about when this problem on Mac OS X will be addressed becomes available, the constant can be updated to reflect something less arbitrary. A
complete code listing which expands on the above approach can be found in the flashversion.js file used in the samples. Performance and Flash As is the case with any plug-in content, Flash content has the potential to slow down or even
completely stall not just the tab it's running in, but the entire browser and even the entire computer it's being used on. Avoiding poorly-written or unnecessary Flash co...
Plugins - Archive of obsolete content
Reader plugin lets the user open PDF files directly inside the browser, and the QuickTime and RealPlayer plugins are used to play special format videos in a web page. Plugins are written using NPAPI, the cross-browser API for plugins. The main source of documentation for NPAPI is the Gecko Plugin API Reference. To make your plugin scriptable from web pages, use npruntime. Plugins can be written
completely from scratch using C APIs (usually in C or C++) or they may be built on a plugin framework such as Firebreath, JUCE, or QtBrowserPlugin. There are also some code generation tools that may be helpful. More information about these tools can be found on the External Resources page. Plugins are different from extensions, which modify or enhance the functionality of the browser itself. Plugins are ...
Syndicating content with RSS - Archive of obsolete content
y of prioritizing the content type that an HTTP client prefers to receive. This technique takes advantage by having the client prefer RSS (over HTML or other formats). Here's a simple example of it being done: Accept: application/rss+xml, text/html With real production software, though, it would look more like this: Accept: application/rss+xml, application/xhtml+xml, text/html Here's a more
complete example: GET / HTTP/1.1 Host: example.com Accept: application/rss+xml, application/xhtml+xml, text/html When an HTTP server (or server-side script) gets this, it should redirect the HTTP client to the feed. It should do this with an HTTP 302 Found. Something like: HTTP/1.1 302 Found Location: http://example.com/feed ...
SSL and TLS - Archive of obsolete content
The Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols are universally accepted standards for authenticated and encrypted communication between clients and servers. Both client and server authentication occur over SSL/TLS. SSL/TLS uses a combination of public key and symmetric-key encryption. Symmetric-key encryption is much faster than public-key encryption, but public-key encryption provides better authentication techniques. An SSL/TLS session always begins with an exchange of messages called the SSL handshake, initial communication between the server and client. ...
Tamarin Tracing Build Documentation - Archive of obsolete content
that will be compiled. Documentation on how to setup a user repository http://developer.mozilla.org/En/Publishing_Mercurial_Clones. Push any changes that you want to test into this repository. Request a build via the form at http://tamarin-builds.mozilla.org/build_trigger/requestbuild.cfm User Email: Your email address. An email with the build status will be sent to this address when a builder
completes whether it is passes or fails. Mercurial Repository: Give the location of the repository that will be used for the build. NOTE: Only repositories hosted on http://hg.mozilla.org/ are accepted. Revision: Specify the revision number that will be built. Currently this only accepts the change number and not the hash. Branch: Which branch of tamarin the repository is based on, Tamarin-Central or Tama...
Building a Theme - Archive of obsolete content
rsion! In this case, "39.*" indicates that the extension works with Firefox 39 and any subsequent 39.x release. Themes are compatible by default, unless you set strict compatibility mode for your theme. If you get a message that the install.rdf is malformed, it is helpful to load it into firefox using the File->Open File command and it will report XML errors to you. See Install Manifests for a
complete listing of the required and optional properties. Save the file. Styling the Browser's UI with CSS Firefox's user interface is written in XUL and JavaScript. XUL is an XML grammar that provides user interface widgets like buttons, menus, toolbars, trees, etc. User actions are bound to functionality using JavaScript. These XUL elements are styled using CSS. If you don't know CSS, it's going to...
Theme changes in Firefox 2 - Archive of obsolete content
ive #print-button:hover #print-button:hover:active #reload-button:hover #reload-button:hover:active #searchbar[empty="true"] .searchbar-textbox #stop-button:hover #stop-button:hover:active #urlbar-icons-spacer #urlbar-spacer #urlbar[level="high"] #lock-icon:active #urlbar[level="high"] #lock-icon:hover #urlbar[level="low"] #lock-icon:active #urlbar[level="low"] #lock-icon:hover .auto
complete-treebody::-moz-tree-cell(suggesthint) .auto
complete-treebody::-moz-tree-cell-text(suggestfirst, treecolAuto
CompleteComment) .auto
complete-treebody::-moz-tree-cell-text(suggesthint, treecolAuto
CompleteComment) .bookmark-item[livemark] .openintabs-menuitem .toolbarbutton-icon .toolbarbutton-menubutton-dropmarker toolbar[iconsize="small"] #back-button .toolbarbutton-menubutton-dropmarker too...
Theme changes in Firefox 3.5 - Archive of obsolete content
This article covers the changes that need to be made to update a Firefox theme to work properly in Firefox 3.5. Core, browser and toolkit changes requiring theme updates There are a number of changes in the browser that may require you to make changes to your theme. Affected files Details scrollbar.xml, xulscrollbars.css The <gripper> element was removed from the scrollbar thumb button by bug 448704. For the Windows and Linux native default themes, the gripper is now drawn as a part of the background of the scrollbar thumb widget. Third-party themes can still draw a gripper for the scrollbar thumb button by applying a centered background image to the scrollbar's thumb button. ...
Summary of Changes - Archive of obsolete content
This section outlines all of the element and practice updates described in this article. For a
complete discussion of these items, see the sections in which they are described. Proprietary or Deprecated Feature W3C Feature or Recommended Replacement deprecated FONT HTML 4.01 SPAN plus CSS1 color: ; font-family: ; font-size: ; deprecated CENTER or align="center" CSS1 text-align: center; for in-line elements like text or image deprecated CENTER or align="center" CSS1 margin-left: auto; margin-right: auto; for block-level elements deprecated bgcolor CSS1 background-color: ; non-standard EMBED HTML 4.01 OBJECT deprecated APPLET HTML 4.01 OBJECT non-standard MARQUEE HTML 4.01 DIV plus scripting ...
Using workers in extensions - Archive of obsolete content
e user interface. If you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: Creating a status bar extension Creating a dynamic status bar extension Adding preferences to an extension Localizing an extension Updating an extension to support multiple Mozilla applications Download the sample You may download the
complete example: Download the example. How this differs from previous versions This version of the stock ticker extension moves the XMLHttpRequest call that fetches updated stock information into a worker thread, which then passes that information back to the main body of the extension's code to update the display in the status bar. This demonstrates not only how to use workers in an extension, but...
-moz-stack-sizing - Archive of obsolete content
For example, moving a child of the stack far to the right will widen the stack so the child remains visible. /* Keyword values */ -moz-stack-sizing: auto; -moz-stack-sizing: ignore; /* Global values */ -moz-stack-sizing: inherit; -moz-stack-sizing: initial; -moz-stack-sizing: unset; If you wish to prevent the stack from resizing automatically to accommodate its children, you can set -moz-stack-sizing to ignore on the child element. ...
CSS - Archive of obsolete content
applications like Firefox, the -moz-border-right-colors CSS property sets a list of colors for the right border.-moz-border-top-colorsIn Mozilla applications like Firefox, the -moz-border-top-colors CSS property sets a list of colors for the top border.-moz-stack-sizing-moz-stack-sizing is an extended CSS property. Normally, a <xul:stack> will change its size so that all of its child elements are
completely visible. For example, moving a child of the stack far to the right will widen the stack so the child remains visible.-moz-text-blinkThe -moz-text-blink non-standard Mozilla CSS extension specifies the blink mode.-moz-window-shadowThe -moz-window-shadow CSS property specifies whether a window will have a shadow. It only works on Mac OS X.-ms-acceleratorThe -ms-accelerator CSS property is a Micro...
Processing XML with E4X - Archive of obsolete content
Warning: E4X is obselete. It's been disabled by default for chrome in Firefox 17, and
completely removed in Firefox 21. Use DOMParser/DOMSerializer or a non-native JXON algorithm instead. First introduced in JavaScript 1.6, E4X introduces a native XML object to the JavaScript language, and adds syntax for embedding literal XML documents in JavaScript code. A full definition of E4X can be found in the Ecma-357 specification. This chapter provides a practical overview of the language; it is not a
complete reference. Compatibility issues Prior to widespread browser support for the <script> element, it was common for JavaScript embedded in a page to be surrounded by HTML comment tags to prevent <script> unaware browsers from displaying JavaScript code to the user. This practice is no...
Debug - Archive of obsolete content
eration resulted in an error. 3 Properties Debug.debuggerEnabled Determines whether debugging is enabled for the script context. Debugging may be enabled or disabled whether or not a debugger is attached. Debug.setNonUserCodeExceptions Determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled. Functions Debug.msTraceAsyncCallback
Completed Indicates that the callback stack associated with a previously specified asynchronous operation has
completed. Debug.msTraceAsyncCallbackStarting Associates the callback stack with a previously specified asynchronous operation. Debug.msTraceAsyncOperation
Completed Indicates that an asynchronous operation has
completed. Debug.msTraceAsyncOperationStarting Initiates a trace for an asynchro...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
The text of the h3 was basically touching the right side of the floated image... ...or it would have been, except in some browsers the heading was drawn over the floated image, in contradiction to the CSS specification. Getting the image back on top of the heading turned out to be a matter of relatively positioning the floated image, and then giving it a z-index val...
Writing JavaScript for XHTML - Archive of obsolete content
application/xhtml+xml" ) ) { header( "Content-type: application/xhtml+xml" ); echo '<?xml version="1.0" ?>'."\n"; } else { header( "Content-type: text/html" ); } This distinction also sends the XML declaration, which is strongly recommended, when the document is an XML file. If the content is sent as HTML, an XML declaration would break IE's Doctype switch, so we don't want it there. ...
Building Mozilla XForms - Archive of obsolete content
uses a file called .mozconfig in your home directory to store the build configuration. For xforms, you will need to add the following line: ac_add_options --enable-extensions="default,xforms" # if you're using a Mozilla source before 2010-11-06 (e.g. an old Firefox 3.6 release) use this instead (see bug 601570 for details): ac_add_options --enable-extensions="default,xforms,schema-validation" A
complete .mozconfig file for a release build might look like that: . $topsrcdir/browser/config/mozconfig mk_add_options MOZ_CO_PROJECT=browser mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/obj-@CONFIG_GUESS@ #mk_add_options AUTOCONF=autoconf2.13 # possibly needed #mk_add_options MOZ_MAKE_FLAGS=-jn # (optional) replace n with the number of parallel build processes (e.g. 2 on a dual core processor) ac_add_options...
XForms Custom Controls - Archive of obsolete content
dgets interfaces. You are free to choose what type of binding you will extend to provide the foundation for your custom control. This will very likely be one of the implementation bindings or one of the base bindings. Example A collection of custom control examples can be found on XForms:Custom Controls Examples, and you can also see the blog post "Understanding XForms: Customization". Here is a
complete example that defines a new output control that loads its value as an image. It is bound to <xf:output mediatype="image/*"/> mimicking the current XForms 1.1 draft: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:xf="http://www.w3.org/2002/xforms"> <head...
XForms Custom Controls Examples - Archive of obsolete content
Introduction Here is a collection of misc. custom control examples. Please feel free to add your own examples. A full example showing a
complete form can be found on XForms:Custom_Controls. Output Showing Images <binding id="output-image" extends="chrome://xforms/content/xforms.xml#xformswidget-base"> <content> <html:div> <html:img anonid="content"/> </html:div> </content> <implementation implements="nsIXFormsUIWidget"> <method name="refresh"> <body> var img = document.getAnonymousElementByAttribute(this, "anonid", "content"); img.setAttribute("src", this.stringValue); return true; </body> </method> </implementation> </binding> Output Showing XHTML <binding id="output-xhtml" extends="chrome://xforms/content/xforms-xhtml.xml#xformswidget-ou...
Archived open Web documentation - Archive of obsolete content
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. XForms XForms were envisioned as the future of online forms as envisioned by the W3C. Drawing on other W3C standards like XML Schema, XPath, and XML Events, XForms tried to address some of the limitations of the current HTML forms model. However, XForms never gained traction and is now considered obsolete. ...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
onsistent experience across their product offerings. When usability alters too much across products, users complain. Apple and Microsoft have learned this lesson well. When a Macintosh user shifted from Mac OS 8.x to Mac OS 9.x, the interface and desktop metaphor was virtually unchanged. Users could quickly and easily shift from one version to the next. However, when Mac OS X was released, Apple
completely revamped the interface and desktop metaphor. That change caused quite a rumble through the Apple user community. It changed just enough to make it awkward, but not enough to where the user could not adjust. Apple received both good and bad press; and they lost some users and won some others over. An example of how consistent user experience wins user loyalty can be seen in how Microsoft ensure...
Windows Media in Netscape - Archive of obsolete content
ws Media ActiveX control is supported and available for use. JavaScript will dynamically write out what browser you are running, and what kind of Windows Media Player technology you may have. Example 1: Client-side Detection Scripts Browser architecture supports: NetscapePlugin Windows Media Player Installed: true Windows Media Scriptable: false Windows Media Version: PluginVersion A
complete source code listing showing how that detection was done can be found here (devedge-temp). Below, some of the salient points are illustrated in a code snippet: if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1) { // IE for Windows object instantiation -- use of ActiveXObject } else if(window.GeckoActiveXObject) { // Netscape 7.1 object instantiation --use of GeckoActiveX...
Anatomy of a video game - Game development
l be blocked until the browser decides to fire rAF callbacks. Each of these methods have similar tradeoffs: Users can skip rendering frames or interpolate extra ones depending on their performance. You can count on all users updating non-cosmetic variables at the same constant frequency minus hiccups. Much more complicated to program than the basic loops we saw earlier. User input is
completely ignored until the next update (even if the user has a fast device). The mandatory interpolation has a performance penalty. A separate update and draw method could look like the following example. For the sake of demonstration, the example is based on the third bullet point, just without using Web Workers for readability (and, let's be honest, writability). Note: This example, specifically,...
Index - Game development
. 72 Visual JS GE Canvas, JavaScript, Server, game engine Visual-js GameEngine is a small but comprehensive canvas/websocket-based game engine with GUI source editor only for Windows. The server is based on Node.js vs MySql, the client made in four variant on a JavaScript frameworks for 2d canvas JS , three.js , webGL2 vs glmatrix and 2d canvas with matter.js in typescript to
complete the stack. 73 Visual typescript game engine HTML, game engine 74 Visual-js game engine HTML5, JavaScript, Tools, game engine, visual-js creator : Nikola Lukic 2017 ...
Building up a basic demo with A-Frame - Game development
apes. Add this just before the closing </a-scene> element: <a-camera position="0 1 4" cursor-visible="true" cursor-scale="2" cursor-color="#0095DD" cursor-opacity="0.5"> </a-camera> We've also defined a cursor for the given camera, using the cursor-* attributes (by default it is invisible.) -- we've set its scale so it will more easily visible, its color, and some opacity so it won't
completely covering the objects behind it. Adding lights The basic light types in A-Frame are directional and ambient. The first type is a directional light placed somewhere on the scene while the second one reflects the light from the first type, so it looks more natural; this can be set globally. Add the new code below your previous additions -- this uses the standard <a-light> element: <a-light ty...
Building up a basic demo with Babylon.js - Game development
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 definition: var light = new BABYLON.PointLight("light", new BABYLON.Vector3(10, 10, 0), scene); The param...
Building up a basic demo with PlayCanvas editor - Game development
, Math.sin(this.timer*2), 0); The position of the cone will be animated on each frame by being passed the Math.sin() value of the timer at each point in time -- we have doubled the this.timer value to make it move higher. Add the coneAnimation.js script to the cone object, as before. Test the demo out Launch the demo to see the effects -- all the shapes should animate. Congratulations, you've
completed the tutorial! Summary Now you can check the PlayCanvas engine article if you haven't seen it yet, go back to the Building up a basic demo with PlayCanvas page, or go back a level higher to the main 3D Games on the Web page. ...
Building up a basic demo with the PlayCanvas engine - Game development
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 The basic light types in PlayCanvas are directional and ambient. The first type is a directional light placed somewhere on the scene while the scond one reflects the light from the first type, so it looks more natural; this can be set globally. Again, add the new code below your previous additions. var light = new pc.Entity(...
Unconventional controls - Game development
ximity', function(event) { var min = event.min; var max = event.max; var proximity = event.value; }); The min and max values are the minimum and the maximum distances respectively between which the sensor can detect the exact proximity value. All three are calculated in centimetres. Note: See the DeviceProximityEvent reference page for more details. MaKey MaKey If you want to go
completely bananas you can use MaKey MaKey, a board that can turn anything into a controller -- it's all about connecting real-world, conductive objects to a computer and using them as touch interfaces. Check out the banana piano video, and be sure to visit the quick start guide for all the needed info. There's even a Cylon.js-supported Makey Button functionality inspired by the MaKey MaKey board, so ...
asm.js - Game development
w you can make use of it, and further resources and examples. What is asm.js, exactly? It is a very small, strict subset of JavaScript that only allows things like `while`, `if`, numbers, top-level named functions, and other simple constructs. It does not allow objects, strings, closures, and basically anything that requires heap allocation. Asm.js code resembles C in many ways, but it's still
completely valid JavaScript that will run in all current engines. It pushes JS engines to optimize this kind of code, and gives compilers like Emscripten a clear definition of what kind of code to generate. We will show what asm.js code looks like and explain how it helps and how you can use it. This subset of JavaScript is already highly optimized in many JavaScript engines using fancy Just-In-Time (JIT...
Mouse controls - Game development
pointer is within the Canvas boundaries, and the paddleX position (anchored on the left edge of the paddle) is set to the relativeX value minus half the width of the paddle, so that the movement will actually be relative to the middle of the paddle. The paddle will now follow the position of the mouse cursor, but since we're restricting the movement to the size of the Canvas, it won't disappear
completely off either side. Compare your code This is the latest state of the code to compare against: Exercise: adjust the boundaries of the paddle movement, so the whole paddle will be visible on both edges of the Canvas instead of only half of it. Next steps Now we've got a
complete game we'll finish our series of lessons with some more small tweaks -- Finishing up. << PreviousNext >> ...
Build the brick field - Game development
ng, multiplied by the column number, c, plus the brickInfo.offset.left; the logic for the brickY is identical except that it uses the values for row number, r, brickInfo.height, and brickInfo.offset.top. Now every single brick can be placed in its correct place, with padding between each brick, and drawn at an offset from the left and top Canvas edges. ...
Plug-in Development Overview - Gecko Plugin API Reference
post form data to CGI scripts using HTTP, or upload files to a remote server using FTP. Use NPN_GetURL to request the browser to load a URL into a particular browser window or frame for display, or to deliver the data of that URL to the plug-in instance in a new stream. The NPN_GetURLNotify function operates like NPN_GetURL, except that it notifies the plug-in of the result when the operation
completes. Use NPN_PostURL to send data to a URL from a memory buffer or file. The result from the server can also be sent to a particular browser window or frame for display, or delivered 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 me...
502 - MDN Web Docs Glossary: Definitions of Web-related terms
your request to the upstream server. "502" means that the upstream server has returned an invalid response. Normally the upstream server is not down (i.e. furnishes no response to the gateway/proxy), but simply does not understand the same data-exchange protocol as the gateway/proxy. Internet protocols are quite explicit, and so a 502 usually means that one or both machines were incorrectly or in
completely programmed. Learn more list of HTTP response codes ...
Alpha (alpha channel) - MDN Web Docs Glossary: Definitions of Web-related terms
fies how opaque the color is. For example, the color #8921F2 (also described as rgb(137, 33, 242) or hsl(270, 89%, 54)) is a nice shade of purple. Below you see a small box of that color in the top-left corner and a box of the same color but with an alpha channel set at 0.5 (50% opacity). The two boxes are drawn on top of a paragraph of text. As you can see, the color without an alpha channel
completely blocks the background text, while the box with the alpha channel leaves it visible through the purple background color. Learn more General knowledge Alpha compositing on Wikipedia RGBA color model on Wikipedia Channel (digital image) on Wikipedia Technical reference CSS color ...
Block cipher mode of operation - MDN Web Docs Glossary: Definitions of Web-related terms
they encrypt data a block at a time. The size of each block is fixed and determined by the algorithm: for example AES uses 16-byte blocks. Block ciphers are always used with a mode, which specifies how to securely encrypt messages that are longer than the block size. For example, AES is a cipher, while CTR, CBC, and GCM are all modes. Using an inappropriate mode, or using a mode incorrectly, can
completely undermine the security provided by the underlying cipher. ...
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to
complete some kind of routine or action. Here is a quick example: function greeting(name) { alert('Hello ' + name); } function processUserInput(callback) { var name = prompt('Please enter your name.'); callback(name); } processUserInput(greeting); The above example is a synchronous callback, as it is executed immediately. Note, however, that callbacks are often used to continue code execution after an asynchronous operation has
completed -- these are called asynchronous callbacks. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in...
Certified - MDN Web Docs Glossary: Definitions of Web-related terms
Certified means that an application, content or data transmission has successfully undergone evaluation by professionals with expertise in the relevant field, thereby indicating
completeness, security and trustworthiness. For details on certification in Cryptography, please refer to Digital Certificate. Learn more General knowledge Information security tutorial Certification on Wikipedia ...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
that change the control flow, such as conditionals and loops. For example, imagine a script used to validate user data from a webpage form. The script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in. To do this, the script uses a conditional structure or if...else, so that different code executes depending on whether the form is
complete or not: if (field==empty) { promptUser(); } else { submitForm(); } A typical script in JavaScript or PHP (and the like) includes many control structures, including conditionals, loops and functions. Parts of a script may also be set to execute when events occur. For example, the above excerpt might be inside a function that runs when the user clicks the Submit button for the form. The...
First contentful paint - MDN Web Docs Glossary: Definitions of Web-related terms
First Contentful Paint (FCP) is when the browser renders the first bit of content from the DOM, providing the first feedback to the user that the page is actually loading. The question "Is it happening?" is "yes" when the first contentful paint
completes. The First Contentful Paint time stamp is when the browser first rendered any text, image (including background images), non-white canvas or SVG. This excludes any content of iframes, but includes text with pending webfonts. This is the first time users could start consuming page content. ...
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
pt, interacting directly with the CSSOM before JavaScript is enabled provides for faster parse times. Browsers create the CSSOM -- including layout, paint, and composite processes -- before applying any style updates found in scripts: layout, paint, and composite processes are repeated for updated JavaScript styles to be implemented. Houdini code doesn't wait for that first rendering cycle to be
complete. Rather, it is included in that first cycle, creating renderable, understandable styles. See Also Houdini Houdini: an introduction CSSOM CSS Paint API CSS Typed OM ...
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
an represent numbers, booleans, strings, null, arrays (ordered sequences of values), and objects (string-value mappings) made up of these values (or of other arrays and objects). JSON does not natively represent more complex data types like functions, regular expressions, dates, and so on. (Date objects by default serialize to a string containing the date in ISO format, so the information isn't
completely lost.) If you need JSON to represent additional data types, transform values as they are serialized or before they are deserialized. Much like XML, JSON has the ability to store hierarchical data unlike the more traditional CSV format. Many tools provide translation between these formats such as this online JSON to CSV Converter or this alternative JSON to CSV Converter. Learn more General ...
Long task - MDN Web Docs Glossary: Definitions of Web-related terms
It is an uninterrupted period where the main UI thread is busy for 50 ms or longer. Common examples include long running event handlers, expensive reflows and other re-renders, and work the browser does between different turns of the event loop that exceeds 50 ms. ...
Mozilla Firefox - MDN Web Docs Glossary: Definitions of Web-related terms
Mozilla Firefox is a free open-source browser whose development is overseen by the Mozilla Corporation. Firefox runs on Windows, OS X, Linux, and Android. First released in November 2004, Firefox is
completely customizable with themes, plug-ins, and add-ons. Firefox uses Gecko to render webpages, and implements both current and upcoming Web standards. Learn more General knowledge Mozilla Firefox official website Technical reference Firefox developer documentations on MDN ...
Snap positions - MDN Web Docs Glossary: Definitions of Web-related terms
A scroll container may set snap positions -- points that the scrollport will stop moving at after a scrolling operation is
completed. This allows a scrolling experience that gives the effect of paging through content rather than needing to drag content into view. Defining Snap positions on the scroll container was introduced in the CSS Scroll Snap specification. ...
Specification - MDN Web Docs Glossary: Definitions of Web-related terms
A specification is a document that lays out in detail what functionality or attributes a product must include before delivery. In the context of describing the Web, the term "specification" (often shortened to simply "spec") generally means a document describing a language, technology, or API which makes up the
complete set of open Web technologies. Learn more General knowledge Specification on Wikipedia Technical reference Open Web platform specifications ...
Speed index - MDN Web Docs Glossary: Definitions of Web-related terms
Speed Index (SI) is a page load performance metric that shows you how quickly the contents of a page are visibly populated. It is the average time at which visible parts of the page are displayed. Expressed in milliseconds, and dependent on the size of the viewport, the lower the score, the better. The calculation calculates what percent of the page is visually
complete at every 100ms interval until the page is visually
complete. The overall score, the above the fold metric, is a sum of the individual 10 times per second intervals of the percent of the screen that is not-visually
complete. ...
Symmetric-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
hey encrypt data one block at a time. The size of each block is fixed and determined by the algorithm: for example AES uses 16-byte blocks. Block ciphers are always used with a mode, which specifies how to securely encrypt messages that are longer than the block size. For example, AES is a cipher, while CTR, CBC, and GCM are all modes. Using an inappropriate mode, or using a mode incorrectly, can
completely undermine the security provided by the underlying cipher. ...
TLD - MDN Web Docs Glossary: Definitions of Web-related terms
rict an administrating organization might be, TLD often serves as a clue to the purpose, ownership, or nationality of a website. Consider an example Internet address: https://developer.mozilla.org Here org is the TLD; mozilla.org is the second-level domain name; and developer is a subdomain name. All together, these constitute a fully-qualified domain name; the addition of https:// makes this a
complete URL. IANA today distinguishes the following groups of top-level domains: country-code top-level domains (ccTLD) Two-character domains established for countries or territories. Example: .us for United States. internationalized country code top-level domains (IDN ccTLD) ccTLDs in non-Latin character sets (e.g., Arabic or Chinese). generic top-level domains (gTLD) Top-level domains with thr...
UX - MDN Web Docs Glossary: Definitions of Web-related terms
ience. It is the study of the interaction between users and a system. Its goal is to make a system easy to interact with from the user's point of view. The system can be any kind of product or application that an end user is meant to interact with. UX studies undertaken on a web page for example can demonstrate whether it is easy for users to understand the page, navigate to different areas, and
complete common tasks, and where such processes could have less friction. Learn more General knowledge User experience on Wikipedia ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
use with documents passed into it. Code sample The following code aims to let <xi:include> and <xi:fallback> tags (the two elements in the language) with all of the attributes of <xi:include> be included in an XML document so as to be resolvable into a single XML document. (Note that this has not been thoroughly tested for all circumstances and may not necessarily reflect the standard behavior
completely.) Note also that if you wish to allow xml:base, you will need the xml:base function, and the line beginning var href = ... should become: var href = getXmlBaseLink (/* XLink sans xml:base */ xinclude.getAttribute('href'), /* Element to query from */ xinclude); function resolveXIncludes(docu) { // http://www.w3.org/TR/xinclude/#xml-included-items var xincludes = docu.getElementsByTagN...
About Scriptable Interfaces - Interfaces
Most of the information of this document is based on http://www.mozilla.org/scriptable/ and Creating XPCOM Components Scriptable Interfaces Interfaces allow XPCOM components to expose their functionality to the outside world while hiding the inner details of the component implementation. Interfaces are written in an Interface Description Language. When we label an interface as scriptable, we're saying that components exporting this interface can be referenced (through this interface) from scripts (e.g JavaScript), and that we can write new components implementing the interface using script languages. ...
CSS and JavaScript accessibility best practices - Learn web development
t to put all websites in high contrast colors that are easy for them to see. Whatever the need, you should be comfortable with this, and make your designs flexible enough so that such changes will work in your design. As an example, you might want to make sure your main content area can handle bigger text (maybe it will start to scroll to allow it all to be seen), and won't just hide it, or break
completely. JavaScript JavaScript can also break accessibility, depending on how it is used. Modern JavaScript is a powerful language, and we can do so much with it these days, from simple content and UI updates to fully-fledged 2D and 3D games. There is no rule that says all content has to be 100% accessible to all people -- you just need to do what you can, and make your apps as accessible as possibl...
A cool-looking box - Learn web development
how you worked out the value. A base color for the design. Give the box this color as its background color. The same color for the text; make it readable using a black text shadow. A fairly subtle border radius. A 1-pixel solid border with a color similar to the base color, but a slightly darker shade. A linear semi-transparent black gradient that goes toward the bottom right corner. Make it
completely transparent at the start, gradiating to around 0.2 opacity by 30% along, and remaining at the same color until the end. Multiple box shadows. Give it one standard box shadow to make the box look slightly raised off the page. The other two should be inset box shadows -- a semi-transparent white shadow near the top left and a semi-transparent black shadow near the bottom right -- to add to the n...
Backgrounds and borders - Learn web development
background image In the example above, we have a large image that has ended up being cropped as it is larger than the element it is a background of. In this case we could use the background-size property, which can take length or percentage values, to size the image to fit inside the background. You can also use keywords: cover -- the browser will make the image just large enough so that it
completely covers the box area while still retaining its aspect ratio. In this case, part of the image is likely to end up outside the box. contain -- the browser will make the image the right size to fit inside the box. In this case, you may end up with gaps on either side or on the top and bottom of the image, if the aspect ratio of the image is different from that of the box. In the example below I ...
Creating fancy letterheaded paper - Learn web development
e, you need to: The main letter Apply the CSS to the HTML. Add a background declaration to the letter that: Fixes the top image to the top of the letter Fixes the bottom image to the bottom of the letter Adds a semi-transparent gradient over the top of both of the previous backgrounds that gives the letter a bit of texture. Make it slightly dark right near the top and bottom, but
completely transparent for a large part of the center. Add another background declaration that just adds the top image to the top of the letter, as a fallback for browsers that don't support the previous declaration. Add a white background color to the letter. Add a 1mm top and bottom solid border to the letter, in a color that is inkeeping with the rest of the color scheme. The logo To the <...
Debugging CSS - Learn web development
e DevTools. Perhaps you have realised that you don't want your box to inherit the <body> element's font size, and want to set its own specific size? You can try this out in DevTools before adding it to your CSS file. You can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and DevTools will show you an auto
complete list of matching properties. After selecting font-size, enter the value you want to try. You can also click the + button to add an additional rule with the same selector, and add your new rules there. Note: There are other useful features in the Rules view too, for example declarations with invalid values are crossed out. You can find out more at Examine and edit CSS. Understanding the box ...
Images, media, and form elements - Learn web development
he box but not larger. This technique will work with other replaced elements such as <video>s, or <iframe>s. Try adding max-width: 100% to the <img> element in the example above. You will see that the smaller image remains unchanged, but the larger one becomes smaller to fit into the box. You can make other choices about images inside containers. For example, you may want to size an image so it
completely covers a box. The object-fit property can help you here. When using object-fit the replaced element can be sized to fit a box in a variety of ways. Below we have used the value cover, which sizes the image down, maintaining the aspect ratio so that it neatly fills the box. As the aspect ratio is maintained some parts of the image will be cropped by the box. If we use contain as a value the...
Overflowing content - Learn web development
orks in such a messy way, displaying content outside of its intended container. Why not hide overflowing content? Why not scale the size of the container to fit all the content? Wherever possible, CSS does not hide content. This would cause data loss. The problem with data loss is that you might not notice. Website visitors may not notice. If the submit button on a form disappears and no one can
complete the form, this could be a big problem! Instead, CSS overflows in visible ways. You are more likely to see there is a problem. At worst, a site visitor will let you know that content is overlapping. If you restrict a box with a width or a height, CSS trusts you to know what you are doing. CSS assumes that you are managing the potential for overflow. In general, restricting the block dimension is ...
Styling tables - Learn web development
; padding: 20px; font-style: italic; caption-side: bottom; color: #666; text-align: right; letter-spacing: 1px; } There is nothing remarkable here, except for the caption-side property, which has been given a value of bottom. This causes the caption to be positioned on the bottom of the table, which along with the other declarations gives us this final look (see it live at punk-bands-
complete.html): Table styling quick tips Before moving on, we thought we'd provide you with a quick list of the most useful points illustrated above: Make your table markup as simple as possible, and keep things flexible, e.g. by using percentages, so the design is more responsive. Use table-layout: fixed to create a more predictable table layout that allows you to easily set column widths by se...
The box model - Learn web development
ight properties are respected. padding, margin, and border will cause other elements to be pushed away from the box. It does not, however, break onto a new line, and will only become larger than its content if you explicitly add width and height properties. In this next example, we have added display: inline-block to our <span> element. Try changing this to display: block or removing the line
completely to see the difference in display models. Where this can be useful is when you want to give a link to a larger hit area by adding padding. <a> is an inline element like <span>; you can use display: inline-block to allow padding to be set on it, making it easier for a user to click the link. You see this fairly frequently in navigation bars. The navigation below is displayed in a row using f...
Test your skills: values and units - Learn web development
s in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Task One In this task, the first list item has been given a background color using hex color codes. Your task is to
complete the CSS using the same color in different formats, plus a final list item where you should make the background semi-opaque. The second list item should use RGB color. The third should use HSL color. The fourth should use RGB color but with the alpha channel set to .2. You can find conversions for the hex color at this link. You need to figure out how to use the values in CSS. Try updati...
Test your skills: Writing Modes and Logical Properties - Learn web development
Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Task One The box in the example is displayed with a horizontal writing mode. ...
Flexbox - Learn web development
; however if you are considering using flexbox in a real website you need to do testing and make sure that your user experience is still acceptable in as many browsers as possible. Flexbox is a bit trickier than some CSS features. For example, if a browser is missing a CSS drop shadow, then the site will likely still be usable. Not supporting flexbox features however will probably break a layout
completely, making it unusable. We discuss strategies for overcoming cross browser support issues in our Cross browser testing module. Test your skills! We have covered a lot in this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on -- see Test your skills: Flexbox. Summary That concludes ou...
Practical positioning examples - Learn web development
in the same position in the browser window. When the main content scrolls, the info-box will stay in the same position on the screen. Our finished example will look like this: Note: You can see the finished example running live at fixed-info-box.html (source code). Check it out to get an idea of what you will be building in this section of the article. As a starting point, you can use your
completed example from the first section of the article, or make a local copy of info-box.html from our Github repo. HTML additions First of all, we need some additional HTML to represent the web site main content. Add the following <section> just below your opening <body> tag, just before the existing section: <section class="fake-content"> <h1>Fake content</h1> <p>This is fake content. Your main ...
Supporting older browsers - Learn web development
r, you should note that it is the browsers that do not support CSS Grid, which also doesn't support feature queries. This means that an approach as detailed above will work for those browsers. What we are doing is writing our old CSS first, outside of any feature query. Browsers that do not support Grid, and do not support the feature query will use that layout information they can understand and
completely ignore everything else. The browsers that support the feature query also support CSS Grid and so will run the grid code and the code inside the feature query. The specification for feature queries also contains the ability to test if a browser does not support a feature -- this is only helpful if the browser does support feature queries. In the future, an approach of checking for lack of suppo...
Test your skills: Media Queries and Responsive Design - Learn web development
Note: Due to the need to test your design in multiple screen sizes we do not have an interactive editor for this task. Download the code and work locally, or use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Your task Download the starting point. ...
How CSS is structured - Learn web development
values are case-sensitive. The property and value in each pair is separated by a colon. (:) Look up different values of properties listed below. Write CSS rules that apply styling to different HTML elements: font-size width background-color color border Important: If a property is unknown, or if a value is not valid for a given property, the declaration is processed as invalid. It is
completely ignored by the browser'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 ...
Use CSS to solve common problems - Learn web development
Boxes and layouts How to size CSS boxes How to control overflowing content How to control the part of a CSS box that the background is drawn under How do I define inline, block, and inline-block? How to create fancy boxes (also see the Styling boxes module, generally). How to use background-clip to control how much of the box your background image covers. How to change the box model
completely using box-sizing How to control backgrounds How to control borders How to style an HTML table How to add shadows to boxes Uncommon and advanced techniques CSS allows some advanced design techniques. These articles help demystify some of the more complicated use cases. General How to calculate specificity of a CSS selector How to control inheritance in CSS Advanced effects How...
Web fonts - Learn web development
he bottom of the page. In the resulting screen, you first need to copy the line of HTML code shown and paste it into the head of your HTML file. Put it above the existing <link> element, so that the font is imported before you try to use it in your CSS. You then need to copy the CSS declarations listed into your CSS as appropriate, to apply the custom fonts to your HTML. Note: You can find a
completed version at google-font.html and google-font.css, if you need to check your work against ours (see it live). @font-face in more detail Let's explore that @font-face syntax generated for you by fontsquirrel. This is what one of the blocks looks like: @font-face { font-family: 'ciclefina'; src: url('fonts/cicle_fina-webfont.eot'); src: url('fonts/cicle_fina-webfont.eot?#iefix') format('em...
Learn to style HTML using CSS - Learn web development
ing HTML. Before starting this topic, you should also be familiar with using computers and using the web passively (i.e., just looking at it, consuming the content). You should have a basic work environment set up as detailed in Installing basic software and understand how to create and manage files, as detailed in Dealing with files -- both of which are parts of our Getting started with the web
complete beginner's module. It is recommended that you work through Getting started with the web before proceeding with this topic. However, doing so isn't absolutely necessary as much of what is covered in the CSS basics article is also covered in our CSS first steps module, albeit in a lot more detail. Modules This topic contains the following modules, in a suggested order for working through them. Y...
What do common web layouts contain? - Learn web development
A much trickier layout The Opera de Paris. Basically a two-column layout, but you'll notice many tweaks here and there that visually break up the layout. Especially, the header overlaps the image of the main content. The way the curve of the header's menu ties in with the curve at the bottom of the image, the header and main content look like one thing even though they're technically
completely different. The Opera example looks more complex than the MICA example, but it's actually easier to implement (all right, "easy" is a relative concept). As you see, you can craft stunning websites even with just basic layouts. Have a look at your own favorite websites and ask yourself, where's the header, the footer, the main content, and the side content? That will inspire you for your own des...
How much does it cost to do something on the Web? - Learn web development
Getting involved on the Web isn't as cheap as it looks. In this article we discuss how much you may have to spend, and why. Prerequisites: You should already understand what software you need, the difference between a webpage, a website, etc., and what a domain name is. Objective: Review the
complete process for creating a website and find out how much each step can cost. Summary When launching a website, you may spend nothing, or your costs may go through the roof. In this article we discuss how much everything costs, and how you get what you pay (or don't pay). Software Text editors You likely have a text editor: such as, Notepad on Windows, Gedit on Linux, TextEdit on Mac. You'll have an easier time writing code if you choose an editor that color-co...
How do I start to design my website? - Learn web development
, create these designs?) So now that you have a prioritized list of goals, let's move on to the next question. How could a website bring me to my goals? So you have a list of goals and you feel you need a website to reach those goals. Are you sure? Let's look back at our example. We have five goals connected to music, one goal related to personal life (finding your significant other), and the
completely unrelated cat photos. Is it reasonable to build a single website to cover all those goals? Is it even necessary? After all, scores of existing web services might bring you to your goals without building a new website. Finding a girl/boyfriend is a prime case where it makes more sense to use existing resources rather than build a whole new site. Why? Because we'll spend more time building and m...
What are browser developer tools? - Learn web development
p a text box, where you can key in a new value to get a live preview of a style change. Next to each rule is the file name and line number the rule is defined in. Clicking that rule causes the dev tools to jump to show it in its own view, where it can generally be edited and saved. You can also click the closing curly brace of any rule to bring up a text box on a new line, where you can write a
completely new declaration for your page. You'll notice a number of clickable tabs at the top of the CSS Viewer: Computed: This shows the computed styles for the currently selected element (the final, normalized values that the browser applies). Layout: In Firefox, this area includes two sections: Box Model: represents visually the current element's box model, so you can see at a glance what p...
What is a web server? - Learn web development
documents) between two computers. A Protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol. Textual All commands are plain-text and human-readable. Stateless Neither the server nor the client remember previous communications. For example, relying on HTTP alone, a server can't remember a password you typed or remember your progress on an in
complete transaction. You need an application server for tasks like that. (We'll cover that sort of technology in other articles.) HTTP provides clear rules for how a client and server communicate. We'll cover HTTP itself in a technical article later. For now, just be aware of these things: Only clients can make HTTP requests, and then only to servers. Servers can only respond to a client's HTTP requ...
HTML forms in legacy browsers - Learn web development
This tests if your browser supports the HTML5 form validation API test : Modernizr.formvalidation, // If the browser does not support it, the following polyfill is loaded nope : form-validation-API-polyfill.js, // In any case, your core App file that depends on that API is loaded both : app.js, // Once both files are loaded, this function is called in order to initialize the App.
complete : function () { app.init(); } }); The Modernizr team conveniently maintains a list of great polyfills. Just pick what you need. Note: Modernizr has other awesome features to help you in dealing with unobstructive JavaScript and graceful degradation techniques. Please read the Modernizr documentation. Pay attention to performance Even though scripts like Modernizr are very aware of per...
Sending form data - Learn web development
m you employ, but all server-side languages have functions for this. Things to watch out for are character sequences that look like executable code (such as JavaScript or SQL commands). Limit the incoming amount of data to allow only what's necessary. Sandbox uploaded files. Store them on a different server and allow access to the file only through a different subdomain or even better through a
completely different domain. You should avoid many/most problems if you follow these three rules, but it's always a good idea to get a security review performed by a competent third party. Don't assume that you've seen all the possible problems. Summary As we'd alluded to above, sending form data is easy, but securing an application can be tricky. Just remember that a front-end developer is not the on...
Test your skills: Form validation - Learn web development
to put your code in an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Form validation 1 In this task, we are providing you with a simple support query form, and we want you to add some validation features to it: Make all of the input fields mandatory to
complete before the form can be submitted. Change the type of the "Email address" and "Phone number" fields to make the browser apply some more specific validation suitable for the data being asked for. Give the "User name" field a required length of between 5 and 20 characters, the "Phone number" field a maximum length of 15 characters, and the "Comment" field a maximum length of 200 characters. Try ...
Test your skills: Other controls - Learn web development
food choices. However, this time we want to do things differently: Create a basic text input that is semantically associated with the provided label. Put the food choices into a list that can be associated with a form input. Associate the list with your text input, so that when you type characters, any of the list options that match the character sequence are given in a dropdown list as auto
complete suggestions. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable edit...
UI pseudo-classes - Learn web development
hole duration of the focus. In a similar manner to :invalid, it will stop matching :user-invalid if the value does become valid. Test your skills! You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on -- see Test your skills: Advanced styling. Summary This
completes our look at UI pseudo-classes that relate to form inputs. Keep playing with them, and create some fun form styles! Next up, we'll move on to something different -- client-side form validation. Previous Overview: Forms Next In this module Your first form How to structure a web form Basic native form controls The HTML5 input types Other form controls Styling web forms Advanced f...
Your first form - Learn web development
This is done by using the <button> element; add the following just above the closing </ul> tag: <li class="button"> <button type="submit">Send your message</button> </li> The <button> element also accepts a type attribute -- this accepts one of three values: submit, reset, or b...
CSS basics - Learn web development
that you're using an image smaller than the width set on the body. (600 pixels) If your image is larger, it will overflow the body, spilling into the rest of the page. To fix this, you can either: 1) reduce the image width using a graphics editor, or 2) use CSS to size the image by setting the width property on the <img> element with a smaller value. Note: Don't be too concerned if you don't
completely understand display: block; or the differences between a block element and an inline element. It will make more sense as you continue your study of CSS. You can find more information about different display values on MDN's display reference page. Conclusion If you followed all the instructions in this article, you should have a page that looks similar to this one: (You can view our version...
Dealing with files - Learn web development
our website projects. Inside your chosen place, create a new folder called web-projects (or similar). This is where all your website projects will live. Inside this first folder, create another folder to store your first website in. Call it test-site (or something more imaginative). An aside on casing and spacing You'll notice that throughout this article, we ask you to name folders and files
completely in lowercase with no spaces. This is because: Many computers, particularly web servers, are case-sensitive. So for example, if you put an image on your website at, test-site/MyImage.jpg and then in a different file you try to invoke the image as test-site/myimage.jpg, it may not work. Browsers, web servers, and programming languages do not handle spaces consistently. For example, if you use...
How the Web works - Learn web development
using TCP/IP. If the server approves the client's request, the server sends the client a "200 OK" message, which means "Of course you can look at that website! Here it is", and then starts sending the website's files to the browser as a series of small chunks called data packets (the shop gives you your goods, and you bring them back to your house). The browser assembles the small chunks into a
complete web page and displays it to you (the goods arrive at your door -- new shiny stuff, awesome!). DNS explained Real web addresses aren't the nice, memorable strings you type into your address bar to find your favorite websites. They are special numbers that look like this: 63.245.215.20. This is called an IP address, and it represents a unique location on the web. However, it's not very easy to ...
Installing basic software - Learn web development
An automation system, like Webpack, Grunt, or Gulp to automatically perform repetitive tasks, such as minifying code and running tests. Libraries, frameworks, etc., to speed up writing common functionality. A library tends to be an existing JavaScript or CSS file that provides ready-rolled functionality for you to make use of in your code. A framework tend to take this idea further, offering a
complete system with some custom syntaxes for you to write a web app on top of. More tools besides! What tools do I actually need, right now? That looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these. In this article, we'll just set you up with a bare minimum -- a text editor and some modern web browsers. Installing a text edito...
Define terms with HTML - Learn web development
you should define your abbreviations the first time they occur. <p> <dfn><abbr>HTML</abbr> (hypertext markup language)</dfn> is a description language used to structure documents on the web. </p> The HTML spec does indeed set aside the title attribute for expanding the abbreviation. However, this is not an acceptable alternative for providing an inline expansion. The contents of title are
completely hidden from your users, unless they're using a mouse and they happen to hover over the abbreviation. The spec duly acknowledges this as well. Improve accessibility <dfn> marks the keyword defined, and indicates that the current paragraph defines the keyword. In other words, there's an implicit relationship between the <dfn> element and its container. If you want a more formal relationship, o...
Use JavaScript within a webpage - Learn web development
links and form input) in a logical order. If you use pointer events (like mouse events or touch events), duplicate the functionality with keyboard events. Test your site using a keyboard only. Don't set nor even guess time limits. It takes extra time to navigate with the keyboard or hear content read out. You can hardly ever predict just how long it will take for users or browsers to
complete an process (especially asynchronous actions such as loading resources). Keep animations subtle and brief with no flashing. Flashing is annoying and can cause seizures. Additionally, if an animation lasts more than a couple seconds, give the user a way to cancel it. Let users initiate interactions. That means, don't update content, redirect, or refresh automatically. Don't use carousels or displ...
Creating hyperlinks - Learn web development
to create a multi-page website. This is one common way in which a website is created -- the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up. You'll need to make local copies of the following four pages, all in the same directory. For a
complete file list, see the navigation-menu-start directory: index.html projects.html pictures.html social.html You should: Add an unordered list in the indicated place on one page that includes the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok. Change each page name into a link to that page. Copy the navigation menu across to eac...
Getting started with HTML - Learn web development
g, as your HTML's character encoding is set to UTF-8. HTML comments HTML has a mechanism to write comments in the code. Browsers ignore comments, effectively making comments invisible to the user. The purpose of comments is to allow you to include notes in the code to explain your logic or coding. This is very useful if you return to a code base after being away for long enough that you don't
completely remember it. Likewise, comments are invaluable as different people are making changes and updates. To write an HTML comment, wrap it in the special markers <!-- and -->. For example: <p>I'm not inside a comment</p> <!-- <p>I am!</p> --> As you can see below, only the first paragraph displays in the live output. Summary You made it to the end of the article! We hope you enjoyed your tour...
HTML text fundamentals - Learn web development
Nesting lists It is perfectly ok to nest one list inside another one. You might want to have some sub-bullets sitting below a top-level bullet. Let's take the second list from our recipe example: <ol> <li>Remove the skin from the garlic, and chop coarsely.</li> <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li> <li>Add all the ing...
Marking up a letter - Learn web development
L text fundamentals, Creating hyperlinks, and Advanced text formatting. Objective: Test basic and advanced HTML text formatting, use of hyperlinks, and use of HTML <head>. Starting point To begin, get the raw text you need to mark up, and the the CSS to style the HTML. Create a new .html file using your text editor or use an online tool such as CodePen, jsFiddle, or Glitch to
complete the tasks. Note: If you get stuck, then ask us for help. See the Assessment or further help section at the bottom of this page. Project brief For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university. Block/structural semantic...
Introduction to HTML - Learn web development
ny previous HTML knowledge, but you should have at least basic familiarity with using computers and using the web passively (i.e., just looking at it and consuming content). You should have a basic work environment set up (as detailed in Installing basic software), and understand how to create and manage files (as detailed in Dealing with files). Both are parts of our Getting started with the web
complete beginner's module. Note: If you are working on a computer/tablet/other devices that doesn't let you create your own files, you can try out (most of) the code examples in an online coding program such as JSBin or Glitch. Guides This module contains the following articles, which will take you through all the basic theory of HTML and provide ample opportunity for you to test out some skills. ...
Mozilla splash page - Learn web development
ment (right below the opening tag), embed the YouTube video found at https://www.youtube.com/watch?v=ojcNcvb1olg, using the appropriate YouTube tools to generate the code. The video should be 400px wide. Adding responsive images to the further info links Inside the <div> with the class of further-info you will find four <a> elements -- each one linking to an interesting Mozilla-related page. To
complete this section you'll need to insert an <img> element inside each one containing appropriate src, alt, srcset and sizes attributes. In each case (except one -- which one is inherently responsive?) we want the browser to serve the 120px wide version when the viewport width is 500px wide or less, or the 400px wide version otherwise. Make sure you match the correct images with the correct links! N...
From object to iframe — other embedding technologies - Learn web development
or attempt to steal data via clickjacking, which are both really bad things to do. Plus if everybody started to do this, all the additional bandwidth would start to cost Mozilla a lot of money. Only embed when necessary Sometimes it makes sense to embed third-party content -- like youtube videos and maps -- but you can save yourself a lot of headaches if you only embed third-party content when
completely necessary. A good rule of thumb for web security is "You can never be too cautious. If you made it, double-check it anyway. If someone else made it, assume it's dangerous until proven otherwise." Besides security, you should also be aware of intellectual property issues. Most content is copyrighted, offline and online, even content you might not expect (for example, most images on Wikimedia C...
Video and audio content - Learn web development
much of this if implemented correctly. Fortunately, a few years later the HTML5 specification had such features added, with the <video> and <audio> elements, and some shiny new JavaScript APIs for controlling them. We'll not be looking at JavaScript here -- just the basic foundations that can be achieved with HTML. We won't be teaching you how to produce audio and video files -- that requires a
completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own. Note: Before you begin here, you should also know that there are quite a few OVPs (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, e...
HTML table advanced features and accessibility - Learn web development
r> <td>Toothpaste</td> <td>Supermarket</td> <td>13/09</td> <td>Good</td> <td>5</td> </tr> </tbody> </table> </body> </html> Note: You can also find it on Github as spending-record-finished.html (see it live also). Nesting Tables It is possible to nest a table inside another one, as long as you include the
complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screenreader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources. The following markup shows a simple...
Assessment: Structuring planet data - Learn web development
m, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. An HTML data table would be ideal -- you need to take the raw data you have available and turn it into a table, following the steps below. The finished table should look like this: You can also see the example live here (no looking at the source code -- don't cheat!) Steps to
complete The following steps describe what you need to do to
complete the table example. All the data you'll need is contained in the planets-data.txt file. If you have trouble visualising the data, look at the live example above, or try drawing a diagram. Open your copy of blank-template.html, and start the table off by giving it an outer container, a table header, and a table body. You don't need a ...
Structuring the web with HTML - Learn web development
Before starting this topic, you should have at least basic familiarity with using computers and using the web passively (i.e. just looking at it, consuming the content). You should have a basic work environment set up as detailed in Installing basic software, and understand how to create and manage files, as detailed in Dealing with files -- both are parts of our Getting started with the web
complete beginner's module. It is recommended that you work through Getting started with the web before attempting this topic, however, it isn't absolutely necessary; much of what is covered in the HTML basics article is also covered in our Introduction to HTML module, albeit in a lot more detail. After learning HTML, you can then move on to learning about more advanced topics such as: CSS, and how t...
Making asynchronous programming easier with async and await - Learn web development
ifferences. Instead of needing to chain a .then() block on to the end of each promise-based method, you just need to add an await keyword before the method call, and then assign the result to a variable. The await keyword causes the JavaScript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. Once that's
complete, your code continues to execute starting on the next line. For example: let response = await fetch('coffee.jpg'); The response returned by the fulfilled fetch() promise is assigned to the response variable when that response becomes available, and the parser pauses on this line until that occurs. Once the response is available, the parser moves to the next line, which creates a Blob out of it. ...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
tent = time; } const createClock = setInterval(displayTime, 1000); Just like setTimeout(), setInterval() returns an identifying value you can use later when you need to clear the interval. Clearing intervals setInterval() keeps running a task forever, unless you do something about it. You'll probably want a way to stop such tasks, otherwise you may end up getting errors when the browser can't
complete any further versions of the task, or if the animation being handled by the task has finished. You can do this the same way you stop timeouts -- by passing the identifier returned by the setInterval() call to the clearInterval() function: const myInterval = setInterval(myFunction, 2000); clearInterval(myInterval); Active learning: Creating your own stopwatch! With this all said, we've got a ch...
Asynchronous JavaScript - Learn web development
running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), talk about what they are useful for, and look at their inherent issues. Handling async operations gracefully with Promises Promises are a comparatively new feature of the JavaScript language that allow you to defer further actions until after the previous action has
completed, or respond to its failure. This is really useful for setting up a sequence of operations to work correctly. This article shows you how promises work, where you'll see them in use in WebAPIs, and how to write your own. Making asynchronous programming easier with async and await Promises can be somewhat complex to set up and understand, and so modern browsers have implemented async functions an...
Image gallery - Learn web development
> so that when they are clicked, the corresponding image is displayed in the displayed-img <img> element. Attach an onclick handler to the <button> so that when it is clicked, a darken effect is applied to the full-size image. When it is clicked again, the darken effect is removed again. 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. Looping through the images We've already provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbBar, create a new <img> element, set its src attribute to a placeholder value xxx, and append this new <img> element inside thumbBar. You need to: Put the section of code below the "Looping through ...
Test your skills: Events - Learn web development
tion at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). DOM manipulation: considered useful Some of the questions below require you to write some DOM manipulation code to
complete them -- such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements 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 g...
Test your skills: Functions - Learn web development
tion at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). DOM manipulation: considered useful Some of the questions below require you to write some DOM manipulation code to
complete them -- such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements 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 g...
Test your skills: Loops - Learn web development
, then working on the tasks. We didn't provide live editable versions of these tasks because of the risk of creating infinite loops and crashing the assessment page! If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. DOM manipulation: considered useful Some of the questions below require you to write some DOM manipulation code to
complete them -- such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements 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 g...
Manipulating documents - Learn web development
allows you to dynamically add items to the list using a form input and button. When you add an item to the input and press the button: The item should appear in the list. Each item should be given a button that can be pressed to delete that item off the list. The input should be emptied and focused ready for you to enter another item. The finished demo will look something like this: To
complete the exercise, follow the steps below, and make sure that the list behaves as described above. To start with, download a copy of our shopping-list.html starting file and make a copy of it somewhere. You'll see that it has some minimal CSS, a list with a label, input, and button, and an empty list and <script> element. You'll be making all your additions inside the script. Create three variable...
Third-party APIs - Learn web development
The document type to return results for, as specified in an expression passed in via the fq URL parameter. In this case, we want to return articles. Next, we use a couple of if() statements to check whether the startDate and endDate <input>s have had values filled in on them. If they do, we append their values to the URL, specified in begin_date and end_date URL parameters respectively. So, a
complete URL would end up looking something like this: https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=YOUR-API-KEY-HERE&page=0&q=cats &fq=document_type:("article")&begin_date=20170301&end_date=20170312 Note: You can find more details of what URL parameters can be included at the NYTimes developer docs. Note: The example has rudimentary form data validation -- the search term field ...
Video and Audio APIs - Learn web development
as the video elapses. The <span> is also absolutely positioned to sit near the left hand side of the timer bar. We also give our inner <div> and <span> the right amount of z-index so that the timer will be displayed on top, and the inner <div> below that. This way, we make sure we can see all the information -- one box is not obscuring another. Implementing the JavaScript We've got a fairly
complete HTML and CSS interface already; now we just need to wire up all the buttons to get the controls working. Create a new JavaScript file in the same directory level as your index.html file. Call it custom-player.js. At the top of this file, insert the following code: const media = document.querySelector('video'); const controls = document.querySelector('.controls'); const play = docu...
Storing the information you need — Variables - Learn web development
- so myage is a different variable from myAge. One last point: you also need to avoid using JavaScript reserved words as your variable names -- by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words like var, function, let, and for as variable names. Browsers recognize them as different code items, and so you'll get errors. Note: You can find a fairly
complete list of reserved keywords to avoid at Lexical grammar -- keywords. Good name examples: age myAge init initialColor finalOutputValue audio1 audio2 Bad name examples: 1 a _12 myage MYAGE var Document skjfndskjfnbdskjfb thisisareallylongstupidvariablenameman Try creating a few more variables now, with the above guidance in mind. Variable types There are a few different types of data we can s...
JavaScript First Steps - Learn web development
his first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose. A first splash into JavaScript Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a
completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step. What went wrong? Troubleshooting JavaScript When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear -- this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix...
Adding features to our bouncing balls demo - Learn web development
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 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...
JavaScript object basics - Learn web development
Try these in the JS console: person['eyes'] = 'hazel'; person.farewell = function() { alert("Bye everybody!"); } You can now test out your new members: person['eyes'] person.farewell() One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in t...
Object building practice - Learn web development
ter -- we are specifying the ball's x and y properties. The radius of the arc -- in this case, the ball's size property. The last two parameters specify the start and end number of degrees around the circle that the arc is drawn between. Here we specify 0 degrees, and 2 * PI, which is the equivalent of 360 degrees in radians (annoyingly, you have to specify this in radians). That gives us a
complete circle. If you had specified only 1 * PI, you'd get a semi-circle (180 degrees). Last of all, we use the fill() method, which basically states "finish drawing the path we started with beginPath(), and fill the area it takes up with the color we specified earlier in fillStyle." You can start testing your object out already. Save the code so far, and load the HTML file in a browser. Ope...
Object prototypes - Learn web development
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 o...
Multimedia: Images - Learn web development
s a lot wider range of formats to chose from. If you want to play it safe, then you would go for well compressed Progressive JPEGs. Progressive JPEGs, in contrast to normal JPEGs, render progressively (hence the name), meaning the user sees a low-resolution version that gains clarity as the image downloads, rather than the image loading at full resolution top-to-bottom or even only rendering once
completely downloaded. A good compressor for these would be MozJPEG, e.g. available to use in the online image optimization tool Squoosh. A quality setting of 75% should yield decent results. Other formats improve on JPEG's capabilities in regards to compression, but are not available on every browser: WebP -- created by Google and nowadays supported by all major browsers except Safari. Supports tran...
What is web performance? - Learn web development
l about this topic at Understanding Latency. Conclusion That's it for now; we hope our brief overview of the web performance topic helped you to get an idea of what it is all about, and made you excited to learn more. Next up we'll look at perceived performance, and how you can use some clever techniques to make some unavoidable performance hits appear less severe to the user, or disguise them
completely. Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performance Multimedia: images Multimedia: video JavaScript performance best practices. HTML performance features CSS performance features Fonts and performance Mobile performance Focusing on performance ...
The "why" of web performance - Learn web development
To gain basic familiarity of why web performance is important for good user experience. Web performance refers to how quickly site content loads and renders in a web browser, and how well it responds to user interaction. Bad performing sites are slow to display and slow to respond to input. Bad performing sites increase site abandonment. At its worst, bad performance causes content to be
completely inaccessible. A good goal for web performance is for users to not notice performance. While an individual's perception of site performance performance is subjective, loading and rendering can be measured. Good performance may not be obvious to most site visitors, but most will immediately recognize a sluggish site. That is why we care. Why care about performance? Web performance--and its asso...
Server-side web frameworks - Learn web development
ing a mechanism that naturally maintains better security. Deno's features include: Security by default. Deno modules restrict permissions to file, network, or environment access unless explicitly allowed. TypeScript support out-of-the-box. First-class await mechanism. Built-in testing facility and code formatter (deno fmt) (JavaScript) Browser compatibility: Deno programs that are written
completely in JavaScript excluding the Deno namespace (or feature test for it), should work directly in any modern browser. Script bundling into a single JavaScript file. Deno provides an easy yet powerful way to use JavaScript for both client- and server-side programming. Ruby on Rails (Ruby) Rails (usually referred to as "Ruby on Rails") is a web framework written for the Ruby programming language.
Framework main features - Learn web development
rently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering. You can read more about the Virtual DOM in the React docs. The Incremental DOM is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a
complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM. You can read more about the Incremental DOM on the Auth0 blog. The Glimmer VM is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates ...
Getting started with Vue - Learn web development
ve this here for now. We've learnt about some of the ideas behind Vue, created some scaffolding for our example app to live inside, inspected it, and made a few preliminary changes. With a basic introduction out of the way, we'll now go further and build up our sample app, a basic Todo list application that allows us to store a list of items, check them off when done, and filter the list by all,
complete, and in
complete todos. In the next article we'll build our first custom component, and look at some important concepts such as passing props into it and saving its data state. Previous Overview: Client-side JavaScript frameworks Next In this module Introduction to client-side frameworks Framework main features React Getting started with React Beginning our React todo list...
Focus management with Vue refs - Learn web development
for visualizing when these hooks happen. This article from the Digital Ocean Community Blog dives into the lifecycle methods more deeply. Now that we've gone over the lifecycle methods, let's use one to trigger focus when our ToDoItemEditForm component is mounted. In ToDoItemEditForm.vue, attach ref="labelInput" to the <input> element, like so: <input :id="id" ref="labelInput" type="text" auto
complete="off" v-model.lazy.trim="newName" /> Next, add a mounted() property just inside your component object -- note that this should not be put inside the methods property, but rather at the same hierarchy level as props, data(), and methods. Lifecycle methods are special methods that sit on their own, not alongside the user-defined methods. This should take no inputs. Note that you cannot use an arro...
Implementing feature detection - Learn web development
supports blocks, for example: @supports (flex-flow: row) and (flex: 1) { main { display: flex; } main div { padding-right: 4%; flex: 1; } main div:last-child { padding-right: 0; } } This at-rule block applies the CSS rule within only if the current browser supports both the flex-flow: row and flex: 1 declarations. For each condition to work, you need to include a
complete declaration (not just a property name) and NOT include the semi-colon on the end. @supports also has OR and NOT logic available -- the other block applies the float layout if the flexbox properties are not available: @supports not (flex-flow: row) and (flex: 1) { /* rules in here */ } This may look a lot more convenient than the previous example -- we can do all of our feature detection in...
Tools and testing - Learn web development
ul overview of the general area. Modules Understanding client-side web development tools Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a
complete toolchain example showing you how to get productive. Understanding client-side JavaScript frameworks JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now ...
Chrome Worker Modules
try { MyModule.foo(); } catch (ex) { log("Exception raised at " + ex.moduleName) log("Stack: " + ex.moduleStack); } Subtleties You shouldn't mix both styles exports.foo = bar and module.exports = {foo: bar}. If you do, know that any call to module.exports will overwrite all calls to `exports.foo = bar. You should not modify exports or module.exports once your module initialization is
complete. The module loader supports cyclic calls to require(). However, if you have cyclic requirements, some of the modules involved in the cyclic requirements may become visible by the other modules before they are fully evaluated. No attempt is made to fully isolate modules from each other. In particular, globals (String, Math, Object, self) and the worker global scope itself (this) are shared between...
Accessibility API cross-reference
all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. n/a n/a aria-atomic Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be presented if they are made. n/a n/a aria-auto
complete The control cannot accept input at this time. Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are
complete before exposing them to the user. BUSY BUSY BUSY aria-busy Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. CHECKED CHECKED ...
Accessibility Features in Firefox
nternet Explorer for screen reader users. In fact, the same keyboard commands are still available, so users can become comfortable and productive right away. Screen magnifier users can also benefit from Firefox's powerful features today, as caret and focus tracking are fully enabled. Mozilla Corporation is currently reaching out to work with AI Squared, the makers of ZoomText, in order to enable
complete support of advanced ZoomText features such as the Doc Reader and App Reader. We are also optimistic that the the makers of MAGic and Lunar/Supernova will add Firefox support in the coming year. Mozilla has support for Dragon Naturally Speaking. Some users of the professional version are happily playing with Dragon and Firefox. We are optimistic that Nuance will work to improve access to the user...
Information for External Developers Dealing with Accessibility
Checklist A list of what needs to be done for accessibility when building new toolkits, widget by widget. In addition, here is a list of official keyboard UI guidelines for each desktop: Windows keys: Guidelines on keyboard UI design and on implementing keyboard shortcuts: An excellent resource from Microsoft. ...
Frequently Asked Questions for Lightweight themes
d to do is create two graphics files in your favorite graphics editing program (e.g., Photoshop). To get started read more about how to create a theme. Are there any content guidelines? Yes. We are big fans of creativity, but want to ensure that the art displayed in the Themes gallery meets a basic set of guidelines. Please review the Terms of Service and Conditions of Use for authoritative and
complete language. Do I still retain ownership over artwork that I upload? Yes. Your artwork will always be your artwork. After creating a Lightweight theme, can I edit the design? Yes. If at any point you need to edit or delete your theme design after it has been submitted to the gallery, you can access it from the Submissions dashboard. From there, you can view your current designs. By clicking on e...
Android-specific test suites
n android-checkstyle is currently owned by :mcomella and :nalexander. File tickets in the Firefox for Android product in Bugzilla. android-lint Ensure that the code avoids common Android coding errors. Lint is a code scanning tool that identifies problems in the code regarding quality. It is a fast process that can be run on unexecuted code, and test cases are not needed for the process to be
completed. Lint is a simple test that can assure you have a quality code. See https://developer.android.com/studio/write/lint.html and http://tools.android.com/tips/lint for more details. Running android-lint To run android-lint, first build Firefox for Android with your changes; then run ./mach android lint This will lint the code and report the results to stdout, as well as produce an HTML report. ...
A bird's-eye view of the Mozilla framework
e, we're interested in the RDF sub-graph underlying theContents Panel widget within theHelp Viewer window. Suppose the client already has an nsIRDFDataSource object representing a sub-graph of an RDF graph and calls nsIRDFDataSource.GetTarget(resource, NC_LINK, true) to obtain an nsIRDFNode representing a specific node in the graph, in this case a link to aHelp Viewer document page. The client is
completely unaware of which C++ class (or other language) actually implements nsIRDFNode; it only 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 clien...
Testopia
API USERS TAKE NOTE: Positional parameters are now deprecated. All params should now be sent in a hash (struct, dict, hashmap or whatever your language of choice calls key, value pairs). Though all attempts have been made to provide continuing support for positional parameters, please be aware that some API calls may fail until you make this change. Also, future versions may remove this support
completely. As always please backup your installation before attempting to install or upgrade. Testopia 2.3 This version supports Bugzilla 3.4. The main new features are: Support XML export and import of test plans and children Support CSV export of test cases and results. New reports: worst offender and case roll-up Set priorities on indidual case-runs New clone options Uses the latest Extjs 3...
What to do and what not to do in Bugzilla
build. the build the bug is reported against is more than one stable release old and the bug can't be reproduced with a current build. the bug reporter has not responded to questions for one month and the bug can't be reproduced with a current build. the bug reporter reports that they can no longer see the bug and no other people report that they are still seeing the bug. Resolving bugs as IN
COMPLETE The problem is vaguely described with no steps to reproduce, or is a support request. The reporter should be directed to the product's support page for help diagnosing the issue. If there are only a few comments in the bug, it may be reopened only if the original reporter provides more info, or confirms someone else's steps to reproduce. If the bug is long, when enough info is provided a new bug...
Creating a Firefox sidebar
two ways to create a sidebar for Firefox users: the Social API and an extension. You can choose either depending on your needs and resources. An extension An extension is a kind of add-ons that adds new functionalities to Firefox. There is a wide range of extensions available, and some of them provide a sidebar. Such kind of sidebar can be a simple Web panel or a full-featured extension that is
completely integrated with the browser. There are some ways to create an extension: The new sidebar API has been implemented in Firefox 29 as part of the Add-on SDK. It's the easiest way to create an extension with a sidebar.Obsolete since Gecko 57 You can also build a restartless extension yourself without the SDK. A sample extension to add a Web panel is available as a starter.Obsolete since Gecko 5...
Creating a Login Manager storage module
The category registration looks like this: nsCOMPtr<nsICategoryManager> cat = do_GetService(NS_CATEGORYMANAGER_CONTRACTID); NS_ENSURE_STATE(cat); cat->AddCategoryEntry("login-manager-storage", "nsILoginManagerStorage", kYourContractID, PR_TRUE, PR_TRUE, nsnull); Don't forget to unregister the category on unload. ...
Creating Sandboxed HTTP Connections
new ones are passed in as arguments. Since nsIStreamListener does not cover cookies, the current channel being used will need to be stored as a global, since another listener will be used for cookie notifications (covered in the next section). It is usually best to use a JavaScript wrapper that implements all the required methods and calls the specified callback function when the connection has
completed. Below is an example: // global channel var gChannel; // init the channel // the IO service var ioService = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); // create an nsIURI var uri = ioService.newURI(myURLString, null, null); // get a channel for that nsIURI gChannel = ioService.newChannelFromURI(uri); //...
Debugging OpenGL
the OpenGL debug mode by defining the environment variable MOZ_GL_DEBUG. If you start up Firefox with this variable defined, the following behavior changes occur: Each time you issue an OpenGL call, a check is performed to ensure that the GL context is current, using a thread-local static variable to keep track of this. If the context isn't current, the call aborts. Every time an OpenGL call
completes, glFinish() gets run automatically. This flushes out each call, essentially turning OpenGL into a synchronous API. This makes debugging crashes caused by an OpenGL call much easier, since the stack you see will match where the call was issued, rather than some time in the future when it happens to run and crash. If an OpenGL error occurred when executing the call, an error message is output. ...
Building Firefox with Debug Symbols
ld you should include symbols. ac_add_options --enable-debug-symbols This can optionally take an argument for the type of symbols that need to be produced (like "-g3"). By default it uses "-g" on Linux and MacOS. This value takes precedence over the flags set in MOZ_DEBUG_FLAGS Note that this will override the values provided for CFLAGS and CXXFLAGS. Breakpad symbol files After the build is
complete, run the following command to generate an archive of Breakpad symbol files: mach buildsymbols The tinderbox uses an additional uploadsymbols target to upload symbols to a socorro server. See https://dxr.mozilla.org/mozilla/source/toolkit/crashreporter/tools/upload_symbols.sh for more information about the environment variables used by this target. make package If you use make package to pack...
How Mozilla's build system works
dReader to traverse the moz.build files. This is just the default framework we've established for our build system. Legacy Content THE CONTENT BELOW IS CONSIDERED LEGACY. IT IS PRESERVED FOR HISTORICAL REASONS UNTIL THIS ENTIRE PAGE IS REWRITTEN. Makefile basics Makefiles can be quite complicated, but Mozilla provides a number of built-in rules that should enable most makefiles to be simpler.
Complete documentation for make is beyond the scope of this document but is available here. One concept you will need be familiar with is variables in make. Variables are defined by the syntax VARIABLE = VALUE, and the value of a variable is referenced by writing $(VARIABLE). All variables are strings. All Makefile.in files in Mozilla have the same basic format: DEPTH = ../../../.. topsrcdir...
OS TARGET
OS_TARGET is typically the output of the 'uname -s' command on the target platform. The following list is not
complete as any platform could have its own OS_TARGET. WINNT Linux Darwin android SunOS FreeBSD OpenBSD NetBSD OS2 BeOS IRIX64 AIX HP-UX DragonFly skyos riscos NTO OSF1 ...
Simple SeaMonkey build
Build prerequisites Hardware Requirements: The SeaMonkey build process is both I/O- and CPU-intensive, and can take a long time to build even on modern hardware. Minimum and recommended hardware requirements for Mozilla development are: Recommended: 8GB of RAM (having only 4GB RAM and 4GB swap may give memory errors during compile) 35 GB free disk space. This will accomodate Visual Studio 2013 Community Edition, the required SDKs, the MozillaBuild package, the Mercurial source repository and enough free disk space to compile. ...
Callgraph
This can be used for performing static analysis based on the relationship between functions and methods. For instance, given the C++ code: int foo() { return good(); } int good() { return evil() ? 0 : 1; } The callgraph would be foo() -> good() -> evil(). Given the knowledge that evil() does evil things, one could then determine foo() also does evil things. The Callgraph project uses gcc and Treehydra to generate information about function and method calls at compile time, and aggregates it into a sqlite database. ...
Interface Compatibility
PIs which are explicitly shipped with Mozilla prefixes as a technology preview. This includes CSS properties that begin with the -moz- prefix (e.g. -moz-box-shadow), or JavaScript APIs that begin with the moz prefix (e.g. canvasrenderingcontext.mozDrawText). These APIs may be removed or replaced with standard interfaces in future releases of Mozilla. Jetpack The Jetpack SDK and APIs are not yet
complete. The stable version 1.0 of the Jetpack SDK is planned for later in 2010. Documented APIs which are shipped as part of the Jetpack SDK are designed to work in future versions of Firefox. Achieving this compatibility may require rebuilding the extension with a new version of the Jetpack SDK. JavaScript/XUL Interfaces Traditional extensions written using XUL overlays and XPCOM have access to the ful...
Listening to events on all tabs
The browser representing the tab for which updated progress information is being provided. aWebProgress The progress instance responsible for handling the events. aRequest The nsIRequest object representing the associated request. aCurSelfProgress The current progress for the request indicated by the request parameter. aMaxSelfProgress The value representing 100%
complete for the request indicated by the request parameter. aCurTotalProgress The current progress for all requests associated with webProgress. aMaxTotalProgress The total progress for all requests associated with webProgress. onSecurityChange Notification called for security progress. This method will be called on security transitions (eg HTTP -> HTTPS, HTTPS -> HTTP, FOO -> HTTPS) and...
SVG Guidelines
apply directly the transform on the path/shape definition. Tools Tools can help to clean SVG files. Note, however that some of the rules stated above can be hard to detect with automated tools since they require too much context-awareness. To this date, there doesn't seem to be a tool that handles all of the above. ...
Working with Mozilla source code
The articles below will help you get your hands on the Mozilla source code, learn to navigate the code, and how to get the changes you propose checked into the tree. Getting a pre-configured Mozilla build system virtual machine This is the easiest way to get started: use a VirtualBox virtual machine which is already configured with a
complete build environment for you to use. Just boot the VM and build! Viewing and searching Mozilla source code online Learn how to use Searchfox, Mozilla's online search and browsing tool for accessing the source code. This isn't a good way to download the code, but is a great way to search it. Navigating the Mozilla source code Learn about the various folders in the Mozilla source tree, and how to find what you're looking for. Bugs for newcomers...
Experimental features in Firefox
Preference name dom.visualviewport.enabled Constructable stylesheets The addition of a constructor to the CSSStyleSheet interface as well as a variety of related changes makes it possible to directly create new stylesheets without having to add the sheet to the HTML. This makes it much easier to create reusable stylesheets for use with Shadow DOM. Our implementation is not yet
complete; see bug 1520690 for more details. Release channel Version added Enabled by default? Nightly 73 No Developer Edition 73 No Beta 73 No Release 73 No Preference name layout.css.constructable-stylesheets.enabled WebRTC and media The following experimental features include those found in the WebRTC API...
Cross Process Object Wrappers
hrome side is intentional: because the chrome process runs the Firefox UI, any responsiveness problems affect the whole browser. By making the chrome process block on the content process, CPOWs break this principle and allow unresponsive content process to make the whole browser unresponsive. See safe and unsafe CPOWs for more on this. Performance Although the wrapper looks just like an object
completely contained in the chrome script scope, it's really just a reference to an object in the content process. When you access a property of the wrapper, it sends a synchronous message to the content process and returns the result. This means it is many times slower to use than an object. Message ordering CPOWs can violate assumptions you might make about message ordering. Consider this code: mm.ad...
Limitations of chrome scripts
wser.selectedBrowser.docShell; // null With the shim The shim will give you a CPOW for the content object in these situations. In some situations, the content process may not be initialized when an add-on asks for access to its content. In this case, the shim will return a JavaScript object that looks somewhat like a window or a document for about:blank. However, this "dummy" object is
completely static and only exposes a few of the normal properties that windows and documents have. For this reason, add-ons that try to access content objects in fresh <browser> elements may run into trouble. To make the shim unnecessary: factor the code that needs to access content into a separate script, load that script into the content process as a frame script, and communicate between the chrome scr...
Multiprocess Firefox
Some elements of Multiprocess Firefox have been retained for compatibility. This page is an informal index of leftovers, mostly revolving around the Message Manager and the related Cross Process Object Wrappers. Message manager A
complete guide to the objects used to communicate between chrome code and web content. Cross Process Object Wrappers Cross Process Object Wrappers are a migration aid, giving chrome code synchronous access to web content. Limitations of chrome scripts Practices that will no longer work in chrome code, and how to update them. Limitations of...
Performance best practices for Firefox front-end engineers
ow Uninterruptible reflow is what we want to avoid at all costs. Uninterruptible reflow occurs when some DOM node's styles have changed such that the size or position of one or more nodes in the document will need to be updated, and then JavaScript asks for the size or position of anything. Since everything is pending a reflow, the answer isn't available, so everything stalls until the reflow is
complete and the script can be given an answer. Flushing layout also means that styles must be flushed to calculate the most up-to-date state of things, so it's a double-whammy. Here's a simple example, cribbed from this blog post by Paul Rouget: div1.style.margin = "200px"; // Line 1 var height1 = div1.clientHeight; // Line 2 div2.classList.add("foobar"); // Line 3 var height2 = div2.cl...
Storage access policy: Block cookies from trackers
ontains a conversion tracking tag from the third-party network. On the social media website, the network annotates the advertisement landing page URL with a query parameter that signals that the visit was the result of a click on an advertisement. On your website, the display network's tag checks the URL query parameters and saves any ad tracking parameters to first-party storage. If a user later
completes a conversion event, the network's tag checks first-party storage to determine which click (or clicks) was responsible for the visit. We expect that click-through conversion implemented in this way will continue to work. ...
Firefox and the "about" protocol
There is a lot of useful information about Firefox hidden away behind the about: URL protocol. The most useful is the URL about:config, which displays preferences and settings that can be inspected and changed. Available about: URLs depend on your specific Firefox version. ...
mozbrowserloadend
change in the future and it is not supported widely across browsers, it is suitable for use in code dedicated to Firefox OS apps. The mozbrowserloadend event is fired when the browser <iframe> has finished loading all its assets, or has failed to load. This can be used when the embedder wants to stop spinning a loading indicator, or update the UI in some other way to indicate loading is
complete. General info Specification Non standard Interface CustomEvent Bubbles Yes Cancelable Yes Target <iframe> Default Action None Properties Property Type Description target Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubble...
mozbrowseropenwindow
custom object. details The details property 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 mozbrowser...
Overview of Mozilla embedding APIs
... being reviewed Interface definition: nsIWebBrowserFocus.idl nsIWebProgress Interface status... Interface definition: nsIWebProgressListener Interface status... Interface definition: nsIPrompt Interface status... Interface definition: nsIPrefs Interface status... Interface definition: nsIProfile The Profile Manager creates and manages user profiles; each profile is essentially a
complete configuration of the application, including preferences, installed extensions, and so forth. nsIDirectoryServiceProvider Interface status... Interface definition: nsILocalFile Interface status... Interface definition: nsIFile Interface status... Interface definition: nsIClipboardCommands Interface status... Interface definition: nsISelection Interface status... Interface definition...
Roll your own browser: An embedding how-to
la Examples GtkMozEmbed widget: Gtk widget wrapper for the Mozilla Gecko Engine. TestGtkEmbed: Basic browser built with the GtkMozEmbed widget. URL location field, menu bar, html area, supports SSL. Windows External projects K-Meleon browser: the Windows answer to Galeon. Fast IE-look-alike browser, uses IE and NS bookmarking system, fast loading time, privacy features, Java support and
complete control of the menus and "hotkeys". Implemented with Mozilla embedding APIs. (Screenshots) Neoplanet browser: A Gecko add-on for the NeoPlanet browser. ActiveState's Komodo: Development environment, based on Mozilla's XUL. (Screenshot) Macromedia HomeSite HTML Editor: Internal browser for the Homesite Studio application is implemented by embedding Mozilla. (Mozilla blurb) Bradsoft's TopStyle ...
Gecko SDK
ith the +universal flag. Once that's done, you should perform the following command: ln -s /opt/local/lib/libintl.8.dylib /opt/local/lib/libintl.3.dylib This should fix the problem. Building the SDK To build the SDK, you should build XULRunner (the Gecko SDK is built as part of the XULRunner build process, which is why it's sometimes called the XULRunner SDK). See the Build Documentation for
complete details. After the XULRunner build is
complete running make sdk from your object directory will create a package of the sdk in dist. Contents of the SDK The SDK contains the following: 1.9.2 IDL files for frozen interfaces (under idl/) Header files for frozen interfaces, XPCOM functions, and NSPR functions (under include/) Import libraries or shared libraries (under lib/) Static utility ...
Gecko Keypress Event
and Linux. This makes it impossible for users to distinguish between accesskeys using two different characters on the same key (when the Shift modifier is usually used to select one of the characters). The pairs of characters that might be on the same key depend on the keyboard layout. (bug 359638 partially addressed this issue by trying both characters on the key, but bug 303192 would provide a
complete solution.) Solution The following rules apply: Key handlers should be provided with information about all the possible meanings of the event. A handler on the innermost element should handle a key event even when the event does not match exactly and there is an outer element with a handler that does match exactly (bug 433192). When handling web content accesskeys, the handlers should consi...
Script security
/example.org/ can access each other, and they can also access objects served from https://example.org/foo. Objects that are cross-origin get highly restricted access to each other, according to the same-origin policy. For example, code served from https://example.org/ trying to access objects from https://somewhere-else.org/ will have restricted access. Objects in a privileged scope are allowed
complete access to objects in a less privileged scope, but by default they see a restricted view of such objects, designed to prevent them from being tricked by the untrusted code. An example of this scope is chrome-privileged JavaScript accessing web content. Objects in a less privileged scope don't get any access to objects in a more privileged scope, unless the more privileged scope explicitly clones ...
Gecko
name of the layout engine developed by the Mozilla Project. It was originally named NGLayout. Gecko's function is to render web content, such as HTML, CSS, XUL, JavaScript, and render it on the user's screen or print it. In XUL-based applications Gecko also renders the application's user interface. Gecko is used in many applications, including a few browsers such as Firefox and SeaMonkey (for a
complete list, please refer to Wikipedia's article on Gecko). Products using the same version of Gecko have identical support for Web standards. Documentation Chrome This page contains information specific to browser chrome (not Google Chrome) code running in Gecko. Gecko FAQ Frequently asked questions about Gecko. Gecko DOM reference Referenc...
Gecko's "Almost Standards" Mode
In discussions of DOCTYPEs, many people will refer to a DOCTYPE as being "with URI" or "without URI." The URI is the system identifier. For example, consider the following DOCTYPE: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> The parts are as follows: Public Identifier: ...
Getting Started with Chat
e other options available to you: Windows Mac Linux Colloquy ? IRSSI ? ? ?* Xchat ? ? ? Key: ? -- Binary or executable program available ? -- Only available by downloading and compiling source code ?* -- Binary or executable may be available. If not, you'll have to download source code and compile. Note: For a
complete list of IRC clients go here. Web-based clients There are also a few web-based clients which allow connecting to IRC by clicking on irc:// links. One of the simplest web-based clients is Mibbit, another is IRCCloud. These operate very much in the same way as the previously mentioned desktop clients and ChatZilla. Mibbit does NOT require flash or any other plugins. Channels Here is a list of ...
How Mozilla determines MIME Types
re, it becomes interesting. Firstly, the Operating System is asked for a MIME type. (On Unix, this means checking mime.types.) If that fails, a user-supplied helper app is searched for by extension, and the specified MIME type will be used. (i.e. the list in Edit/Preferences/Helper Applications) If that failed, a list of "extra" MIME types is searched for an extension match. See line 507 for the
complete list. If that also failed, the list of loaded plugins is checked for a plugin that can handle this extension, and is asked for the MIME type If no plugin is registered, the ext-to-type-mapping XPCOM category is searched for the extension. This allows extensions to register additional mappings. The key of the category entry is the extension without leading dot, the value is the MIME type. The ex...
How to get a process dump with Windows Task Manager
s of process hangs, it is often helpful to obtain a process dump while the process is experiencing a hang. This article describes how to get a process dump with Task Manager on Windows. (To get a process dump for Thunderbird or some other product, substitute the product name where ever you see Firefox in these instructions.) Caution The memory dump that will be created through this process is a
complete snapshot of the state of Firefox when you create the file, so it contains URLs of active tabs, history information, and possibly even passwords depending on what you are doing when the snapshot is taken. It is advisable to create a new, blank profile to use when reproducing the hang and capturing the memory dump. Please ask for help doing this! Requirements Windows To get a process dump, y...
Implementing QueryInterface
ce(aIID, &foundInterface); else { NS_ADDREF(foundInterface); status = NS_OK; } *aInstancePtr = foundInterface; return status; } Note that if the base implementation's QueryInterface finds an appropriate interface, your QueryInterface must not AddRef it. This is reflected in the code above. This technique works because nsBaseImplementation is already a
complete class that could have been used on its own. This technique is less appropriate when you derive from several
complete classes; but it can still be used if you are sensitive to the order, e.g., // ... nsresult status; if ( !foundInterface ) { // OK, ask |nsBase1Imp| first, because I want _it_ to be the one true |nsISupports|. status = nsBase1Imp::QueryInterface(...
Integrated Authentication
ive in extensions/negotiateauth. Mozilla also supports raw NTLM authentication using an internal implementation (based on the documentation provided by Eric Glass) that supports NTLMv1/LMv1 and NTLM2 Session Key modes. As of Mozilla 1.7, there is no support for NTLMv2/LMv2. This is mainly due to the fact that NTLMSSP does not provide a means to negotiate use of NTLMv2/LMv2. <i>This document is in
complete ...</i> Flow Diagram The diagram below shows how various components interact. Configuration By default, Mozilla rejects all SPNEGO challenges from a web server. This is to protect the user from the possibility of DNS-spoofing being used to stage a man-in-the-middle exploit (see bug 17578 for more info). Moreover, with Windows clients NTLM may be negotiated as the authentication protocol. So...
Addon
randomly and is made consistent across devices during sync. translators Read only AddonAuthor[] An array of strings holding the translators of the add-on. updateDate Read only Date The Date that the add-on was most recently updated. operationsRequiringRestart Read only integer A bitfield holding all of the operations that will require a restart to
complete for this add-on. fullDescription Read only string developerComments Read only string eula Read only string icon64URL Read only string supportURL Read only string contributionURL Read only string contributionAmount Read only string averageRating Read only numbe...
AddonManager
() Asynchronously gets Addons of specific types. Promise? getAddonsByTypes( in string types[], in AddonListCallback? callback ) Parameters types An optional array of types to retrieve. Each type is a string name callback The callback to pass an array of Addons to getAddonsWithOperationsByTypes() Asynchronously gets Addons that have operations waiting for an application restart to
complete. Promise? getAddonsWithOperationsByTypes( in string types[], in AddonListCallback? callback ) Parameters types An optional array of types to retrieve. Each type is a string name. callback The callback to pass the array of Addons to. addAddonListener() Adds a new AddonListener if the listener is not already registered. void addAddonListener( in AddonListener listener ) Paramet...
UpdateCheckListener
UpdateCheckListeners are passed the results of update checks performed by the AddonUpdateChecker. Method Overview void onUpdateCheck
Complete(in UpdateInfo results[]) void onUpdateCheckError(in integer status) Methods onUpdateCheck
Complete() Called when the update check
completed successfully. void onUpdateCheck
Complete( in UpdateInfo results[] ) Parameters results An array of UpdateInfo objects representing the available add-on versions onUpdateCheckError() Called when the update check fails. void onUpdateCheckError( in integer status ) Parameters status A value representing the type of failure; see the range of possible values. ...
Add-on Repository
ovides 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 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: Compon...
Downloads.jsm
ad.html has been downloaded."); }).then(null, Components.utils.reportError); Observing downloads This example logs a message every time a change occurs in one of the global download lists. To demonstrate the logging, a new download is started while a message box is being shown. The download is stopped and removed from the list when the message box is closed, regardless of whether it has been
completed or not. Components.utils.import("resource://gre/modules/Downloads.jsm"); Components.utils.import("resource://gre/modules/osfile.jsm") Components.utils.import("resource://gre/modules/Task.jsm"); Task.spawn(function () { let list = yield Downloads.getList(Downloads.ALL); let view = { onDownloadAdded: download => console.log("Added", download), onDownloadChanged: download => console...
Http.jsm
ters: name meaning headers an array of headers postData this can be: a string: send it as is an array of parameters: encode as form values null/undefined: no POST data. method GET, POST or PUT (this is automatically set if postData exists). onLoad a function handle to call when the load is
complete, it takes two parameters: the responseText and the XHR object. onError a function handle to call when an error occurs, it takes three parameters: the error, the responseText and the XHR object. logger an object that implements the debug and log methods (e.g. log.jsm). Headers or post data are given as an array of arrays, for each inner array the first value is the ...
Promise
Reject); Constructor Creates a new promise, initially in the pending state, and provides references to the resolving functions that can be used to change its state. new Promise(executor); Parameters executor This function is invoked immediately with the resolving functions as its two arguments: executor(resolve, reject); The constructor will not return until the executor has
completed. The resolving functions can be used at any time, before or after the executor has
completed, to control the final state of the promise. If the executor throws an exception, its value will be passed to the reject resolving function. Resolving functions resolve() Fulfills the associated promise with the specified value, or propagates the state of an existing promise. If the associated promi...
Application Translation with Mercurial
he next step, we will unpack the source code: Open an input shell, e.g. by pressing the Windows key and R on the keyboard or by calling the "Run..." command from the Windows "Start" button, and then typing cmd and pressing the Enter key. Launch the installed MozillaBuild toolset by launching it with its path, e.g. C:\Mozilla\Coding\Buildtools\MozillaBuild\start-shell-msvc2010.bat You can auto
complete the file path after typing a few characters and then pressing the Tabulator key. If you launch the start-shell-l10n.bat, compiling features will be disabled. You can create translation patches, but creating language packs for the application, binary repacks of the application (changing the localization of the program), and compiling the application likely won't work. You are now in the Mozilla...
Localization: Frequently asked questions
For more detailed documentation about localization in general, see our Localization page. How do I preserve whitespace in an entity? Do you really want to preserve whitespace or are you looking for a no-break space, you can add that via a &ua0; or \ua0 to DTD and properties files, resp. ...
Localization content best practices
period (in English). Tooltips are never written in imperative mood but infinitive mood instead. Hence the proper absence of periods to indicate this isn't just a matter of consistency for en-US, as it is also vital info for localizers. Menu and control labels The labels on controls and menu titles, menu option strings, and so forth should not end in periods (in English). These are generally not
complete sentences, but instead, phrases that convey the idea of a concept or action. Therefore, for both correctness and consistency within en-US, please leave out the trailing periods for these items. This also helps with localization. Developer tools key shortcuts When translating Firefox strings from /devtools/ folder, you may see some keys like this: inspector.searchHTML.key=CmdOrCtrl+F The first...
Localizing XLIFF files for iOS
(SOME_TEXT_HERE) is a variable format, %1$@ is another variable format. <note> tags contain localizer notes from developers and should not be translated. <trans-unit id="Add to Bookmarks"> <source>Add to Bookmarks</source> <target>Agregar a marcadores</target> <note>No comment provided by engineer.</note> </trans-unit> Save your translations along the way. Once you've
completed translation, it's important to make sure the XML in your XLIFF file is valid (e.g., no broken tag sets). Open the file in Firefox to have it run a validity check and correct any errors it might yell about. Commiting your XLIFF file Using this command, commit your translated XLIFF file into your locale's directory: git commit -m "Commit message here" . Push your commit into the github repo:...
Localizing with Mercurial
the Mercurial version control system (Hg) to manage our source code and localizations. Mercurial allows localizers to work locally (on their machines) and then push (an Hg term) changes to a remote repository, which usually is hosted on the Mozilla servers (hg.mozilla.org). Localizing current versions of Firefox, Thunderbird and SeaMonkey includes working with Mercurial. If the documentation is in
complete or you have questions, please drop by the #l10n or #hg channels on irc.mozilla.org. The Mercurial FAQ are also worth a read, should you run into trouble. For the eager and quick, below you'll find instructions on installing and configuring Mercurial, instructions on receiving an Hg account commit priviledges, as well as a few tasks you can
complete without account priviledges. Installing Mercur...
Localizing with Mozilla Translator
For the last two options, you should be able to adjust your current MT product paths so you can keep using it just like with CVS. Keep in mind that MT doesn't really know if you are using CVS, SVN, or Mercurial. It is just instructed to read directory subtrees and ignore "CVS" and ".svn" directories it finds. If you have opted for the first solution, you will find yourself with some new products
completely untranslated (once you Update each of them). To migrate the existing translation in the old product, you need to export partial glossaries from the old product, selecting the ''link'' origin (see the previous section) and importing them into the ''link'' target. Defining symbolic links for browser This is an example just for browser, without shared components, but it should suffice to get t...
Localization formats
Read more about gettext on Wikipedia and on MDC. Wiki Blogging, documentation, and other types of Mozilla content often surface as wikis. Case study: Download Day In the above Gettext example, notice how the web developer used "certificate_intro" as the value of the msgid. This is not the actual content that was translated. So, if a localizer wan...
Mozilla Development Strategies
likely have conflicts. See mozilla\config\fast-update.pl for a fast way to update your tree. You can update your main mozilla tree (minus nsprpub, etc) in 1-2 minutes. Work on multiple bugs in parallel You should be working on the most important bugs first. But those might be difficult bugs (hard to reproduce crashers, big rewrites for performance, etc.) which can take several days or weeks to
complete, plus the time for reviews. In your other trees, work on smaller, easier bugs. Pick bugs that won't cause conflicts with the work you're doing in your primary tree. Pick bugs that should only take you a few hours or a day to fix. In theory, fixes for these bugs will be quick to review. If you have problems finding smaller, easier bugs to work on, start by looking for crashers. Maybe the problem ...
Mozilla projects on GitHub
he GitHub website. Most Mozilla project code is located in repositories within the Mozilla GitHub organization. This is a great place to start looking for any projects not listed below. Projects This listing covers the larger-scale and more important Mozilla projects on GitHub. It does not include everything since it's hard to keep track of all the smaller projects. Look to GitHub for the most
complete list of Mozilla projects on GitHub. Project name Description PDF.js A Portable Document Format (PDF) reader written entirely in JavaScript. Shumway Shumway is a Flash VM and runtime written in JavaScript. addon-sdk The Mozilla Add-on SDK. asknot The What Can I Do For Mozilla web site, which helps you figure out how you can contribut...
Mozilla Style System Documentation
Style context management A style context (class nsStyleContext, currently also interface nsIStyleContext although the interface should go away when all of the style systems can be moved back into the layout DLL) represents the style data for a CSS formatting object. In the layout system, these formatting objects are described as frames (interface nsIFrame), although a pair of frames represents table formatting objects. The CSS specification describes formatting objects that correspond to elements in the content model and formatting objects that correspond to pseudo-elements. ...
Gecko Profiler FAQ
form specific parts of the browser stack (such as graphics, media, etc.) then profiling on Windows would be certainly a lot more valuable than on other platforms. Should I profile known to be slow sites on slower hardware to get a better signal? [mstange] That's probably a good idea. As long as the slower hardware is still capable enough that the profiler can successfully
complete symbolication. [ehsan] Performance issues are just much easier to spot on slower hardware, so if nothing else, using slower hardware will help you find problems easier. And don't forget that if you're interested in finding IO slowness issues, profiling on a machine with a fast SSD isn't recommended. ...
Memory reporting
s important that no memory is measured twice; this can lead to strange results in about:memory. Avoiding double measurement is easy in tree-like structures. In graph-like structures (where an object might be pointed to by more than one other object) it gets more difficult, and 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 memor...
Power profiling overview
n identify which timers are firing frequently. Power profiling how-to This section aims to put together all the above information and provide a set of strategies for finding, diagnosing and fixing cases of high power consumption. First of all, all measurements are best done on a quiet machine that is running little other than the program of interest. Global measurements in particular can be
completely skewed and unreliable if this is not the case. Find or confirm a test case where Firefox's power consumption is high. "High" can most easily be gauged by comparing against other browsers. Use power measurements or estimates (e.g. via tools/power/rapl, or mach power on Mac, or Intel Power Gadget on Windows) for the comparisons. Avoid lower-quality measurements, especially Activity Monitor's "En...
Refcount tracing and balancing
If you set this environment variable to the name of a file, the log will be output to that file. You can also set it to 1 to log to stdout or 2 to log to stderr, but these logs are large and expensive to capture, so you probably don't want to do that. WARNING: you should never use this without XPCOM_MEM_LOG_CLASSES and/or XPCOM_MEM_LOG_OBJECTS, because without some filtering the logging will be
completely useless due to how slow the browser will run and how large the logs it produces will be. XPCOM_MEM_COMPTR_LOG This environment variable enables logging of additions and releases of objects into nsCOMPtrs. This requires C++ dynamic casts, so it is not supported on all platforms. However, having an nsCOMPtr log and using it in the creation of the balance tree allows AddRef and Release ca...
Reporting a Performance Problem
n a few seconds from reproducing the performance problem as only the last few seconds are recorded. If the timeline has a large red block it's a good sign. The data will open in a new tab. Wait until the "Symbolicating call stacks" notification disappears before sharing the profile. There will be a button in the top right labeled 'Publish' which will allow you to upload this profile and once
completed will write out a link. Before uploading, the publish button asks you what data you'd like to publish to our servers. Note that while it's possible to strip profiles of potentially privacy sensitive information, the less information a profile contains, the harder it is to analyze and turn into actionable data. Once uploaded, copy permalink URL to your clipboard by right clicking and add the pro...
Scroll-linked effects
ition to time and use that as a timeline for the animation. CompositorWorker: Allows JavaScript to be run on the compositor thread in small chunks, provided it doesn't cause the framerate to drop. Scroll Customization: Introduces a new API for content to dictate how a scroll delta is applied and consumed. As of this writing, Mozilla does not plan to support this proposal, but it is included for
completeness. Call to action If you have thoughts or opinions on: Any of the above proposals in the context of scroll-linked effects. Scroll-linked effects you are trying to implement. Any other related issues or ideas. Please get in touch with us! You can join the discussion on the public-houdini mailing list. ...
dtrace
vocation dtrace must be invoked as the super-user. A good starting command for profiling wakeups is the following. sudo dtrace -n 'mach_kernel::wakeup { @[ustack()] = count(); }' -p $FIREFOX_PID > $OUTPUT_FILE Let's break that down further. The -n option combined with the mach_kernel::wakeup selects a probe point. mach_kernel is the module name and wakeup is the probe name. You can see a
complete list of probes by running sudo dtrace -l. The code between the braces is run when the probe point is hit. The above code counts unique stack traces when wakeups occur; ustack is short for "user stack", i.e. the stack of the userspace program executing. Run that command for a few seconds and then hit Ctrl + C to interrupt it. dtrace will then print to the output file a number of stack traces, ...
Preference reference
tes, or cuts something from a web page, and it lets them know which part of the page had been selected. The emitting of the oncopy, oncut and onpaste events are controlled by this preference. javascript.options.showInConsoleThe preference javascript.options.showInConsole controls whether errors or warnings in chrome code are shown in the Error Console.javascript.options.strictTechnical review
completed.mail.tabs.drawInTitlebarStarting in Thunderbird 17.0, the tabs are drawn in the title bar. The old behavior can be restored by setting the preference mail.tabs.drawInTitlebar to false.nglayout.debug.disable xul fastloadThe preference nglayout.debug.disable_xul_fastload controls whether or not XUL fastload is used.nglayout.debug.disable_xul_cacheTo improve performance, Mozilla caches chrome XUL d...
A guide to searching crash reports
pasting the page's URL. To become an expert at searching and grouping requires understanding the full range of the 100+ fields available for searching and grouping. One way to learn about them is to read lots of individual crash reports; note that all fields shown in the Details tab of an individual crash report have a tool-tip that indicates its key for search. Alternatively, you can browse the
complete list. There is also an API through which searches can be performed programmatically. See the API documentation for full details; note that it uses the term "aggregation" for grouping/faceting. ...
L20n Javascript API
It must return an array which is the final fallback chain of locales, or if the negotiation is asynchronous, it must return a falsy value and call the callback argument upon completion. ctx.registerLocaleNegotiator(function(available, requested, defLocale, callback) { YourApp.getAllAvailableLanguages(function(allAvailable) { var fallbackChain = You...
L20n
on implementing L20n in your HTML code. L20n JavaScript API An API for l20n.js. L20n syntax cheatsheet for developers A simple cheatsheet to help developers as they add L20n to their localization infrastructure. For Localizers Documentation for Localizers creating localized content for a project that uses L20n. Learn the L20n syntax How to naturally localize applications using L20n.
Complete with use cases and examples of L20n in action. Localization use-cases How to naturally localize applications using L20n.
Complete with use cases and examples of L20n in action. L20n and Translation Memory eXchange (TMX) How L20n impacts the Translation Memory eXchange standard for translation memory data. L20n syntax cheatsheet for localizers A simple cheatsheet to help localizers as they l...
Midas editor module security preferences
Please do not try to modify this page. To protect users' private information, unprivileged scripts cannot invoke the Cut, Copy, and Paste commands in Midas, which is Mozilla's rich text editor component. ...
About NSPR
the facilities offered by the various platform providers. Where It's Headed NSPR is applicable as a platform on which to write threaded applications that need to be ported to multiple platforms. The current implementation supports Macintosh (PPC), WIN-32 (WinNT, Win9x) and 20 versions of UNIX and is still expanding. The basic API is stable and expected to remain that way. NSPR is functionally
complete and has entered a mode of sustaining engineering. As operating system vendors issue new releases of their operating systems, NSPR will be moved forward to these new releases by interested players. Original Document Information Author: larryh@netscape.com Last Updated Date: 2000 (Portions of the Introduction moved to the history section in 2012) ...
NSPR Contributor Guide
the bug or use an existing report. Be verbose in describing what you are doing and why. Include your changes as diffs in an attachment to the BugZilla report. Use a coding style consistent with the source file you are changing. New Features For purposes of this paper, a "new feature" is defined as some API addition that goes into the core NSPR library, for example: libnspr4.dll NSPR is mostly
complete. New APIs are driven mostly by the OS vendors as they add new features. Should you decide that there's something that NSPR does not cover that should be covered, let's talk. Your proposed API should encapsulate a relatively low level capability as would be found in a system call or libc. Your new feature must be implemented on all platforms supported by NSPR. When you consider a new API for NSPR ...
NSPR's Position On Abrupt Thread Termination
freed as the stack unwinds. In these cases, the presence of the data is recorded only on the stack, known only to the single thread (normally referred to as encapsulated). The problem with abrupt termination is that it can happen at any time, to a thread that is coded correctly to handle both normal and exceptional situations, but will be unable to do so since it will be denied the opportunity to
complete execution. It can happen because it called out of its own scope into some lazily implemented library. NSPR's answer to this is that there is no abrupt thread termination. All threads must unwind and return from their root function. If they cannot, because of some state corruption, then they must assume that the corruption, like the state, is shared, and their only resource is for the process to t...
PRCallOnceType
inProgress If not zero, the initialization process is currently being executed. ...
PR_Available
xpressed as a 32-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket. Syntax #include <prio.h> PRInt32 PR_Available(PRFileDesc *fd); Parameter The function has the following parameter: fd Pointer to a PRFileDesc object representing a file or socket. Returns The function returns one of the following values: If the function
completes successfully, it returns the number of bytes that are available for reading. For a normal file, these are the bytes beyond the current file pointer. If the function fails, it returns the value -1. The error code can then be retrieved via PR_GetError. Description PR_Available works on normal files and sockets. PR_Available does not work with pipes on Win32 platforms. See Also If the number ...
PR_Available64
ressed as a 32-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket. Syntax #include <prio.h> PRInt64 PR_Available64(PRFileDesc *fd); Parameter The function has the following parameter: fd Pointer to a PRFileDesc object representing a file or socket. Returns The function returns one of the following values: If the function
completes successfully, it returns the number of bytes that are available for reading. For a normal file, these are the bytes beyond the current file pointer. If the function fails, it returns the value -1. The error code can then be retrieved via PR_GetError. Description PR_Available64 works on normal files and sockets. PR_Available does not work with pipes on Win32 platforms. See Also If the numbe...
PR EnumerateAddrInfo
AddrInfo *addrInfo, PRUint16 port, PRNetAddr *result); Parameters The function has the following parameters: enumPtr The index pointer of the enumeration. To begin an enumeration, this argument is set to NULL. To continue an enumeration (thereby getting successive addresses from the PRAddrInfo structure), the value should be set to the function's last returned value. The enumeration is
complete when a value of NULL is returned. addrInfo A pointer to a PRAddrInfo structure returned by PR_GetAddrInfoByName. port The port number to be assigned as part of the PRNetAddr structure. This parameter is not checked for validity. result On input, a pointer to a PRNetAddr structure. On output, this structure is filled in by the runtime if the result of the call is not NULL. Returns The fun...
PR_EnumerateHostEnt
onst PRHostEnt *hostEnt, PRUint16 port, PRNetAddr *address); Parameters The function has the following parameters: enumIndex The index of the enumeration. To begin an enumeration, this argument is set to zero. To continue an enumeration (thereby getting successive addresses from the host entry structure), the value should be set to the function's last returned value. The enumeration is
complete when a value of zero is returned. hostEnt A pointer to a PRHostEnt structure obtained from PR_GetHostByName or PR_GetHostByAddr. port The port number to be assigned as part of the PRNetAddr structure. This parameter is not checked for validity. address On input, a pointer to a PRNetAddr structure. On output, this structure is filled in by the runtime if the result of the call is greater tha...
PR_GetConnectStatus
llDesc satructure whose fd field is the socket and whose in_flags field must contain PR_POLL_WRITE and PR_POLL_EXCEPT. Returns The function returns one of these values: If successful, PR_SUCCESS. If unsuccessful, PR_FAILURE. The reason for the failure can be retrieved via PR_GetError. If PR_GetError returns PR_IN_PROGRESS_ERROR, the nonblocking connection is still in progress and has not
completed yet.Other errors indicate that the connection has failed. Description After PR_Connect on a nonblocking socket fails with PR_IN_PROGRESS_ERROR, you may wait for the connection to
complete by calling PR_Poll on the socket with the in_flags PR_POLL_WRITE | PR_POLL_EXCEPT. When PR_Poll returns, call PR_GetConnectStatus on the socket to determine whether the nonblocking connect has succeeded or fa...
PR_JoinJob
Blocks the current thread until a job has
completed. Syntax #include <prtpool.h> NSPR_API(PRStatus) PR_JoinJob(PRJob *job); Parameter The function has the following parameter: job A pointer to a PRJob structure returned by a PR_QueueJob function representing the job to be cancelled. Returns PRStatus ...
PR_JoinThread
that it blocks the calling thread until the target thread is in a joinable state. PR_JoinThread returns to the caller only after the target thread returns from its root function. PR_JoinThread must not be called until after PR_CreateThread has returned. If PR_JoinThread is not called on the same thread as PR_CreateThread, then it is the caller's responsibility to ensure that PR_CreateThread has
completed. Several threads cannot wait for the same thread to
complete. One of the calling threads operates successfully, and the others terminate with the error PR_FAILURE. The calling thread is not blocked if the target thread has already terminated. PR_JoinThread is interruptable. ...
PR_JoinThreadPool
Waits for all threads in a thread pool to
complete, then releases resources allocated to the thread pool. Syntax #include <prtpool.h> NSPR_API(PRStatus) PR_JoinThreadPool( PRThreadPool *tpool ); Parameter The function has the following parameter: tpool A pointer to a PRThreadPool structure previously created by a call to PR_CreateThreadPool. Returns PRStatus ...
PR_STATIC_ASSERT
expression Any valid expression which evaluates at compile-time to TRUE or FALSE. An expression which cannot be evaluated at compile time will cause a compiler error; see PR_ASSERT for a runtime alternative. Returns Nothing Description This macro evaluates the specified expression. When the result is zero (FALSE) program compilation will fail with a compiler error; otherwise compilation
completes successfully. The compiler error will include the number of the line for which the compile-time assertion failed. This macro may only be used in locations where an extern function declaration may be used. ...
PR_Seek
rameter can be one of the following: PR_SEEK_SET. Sets the file pointer to the value of the offset parameter. PR_SEEK_CUR. Sets the file pointer to its current location plus the value of the offset parameter. PR_SEEK_END. Sets the file pointer to the size of the file plus the value of the offset parameter. Returns The function returns one of the following values: If the function
completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file. If the function fails, the file pointer remains unchanged and the function returns -1. The error code can then be retrieved with PR_GetError. Description Here's an idiom for obtaining the current location of the file pointer for the file descriptor fd: PR_Seek(fd, 0, PR_SEEK_CUR) ...
PR_Seek64
rameter can be one of the following: PR_SEEK_SET. Sets the file pointer to the value of the offset parameter. PR_SEEK_CUR. Sets the file pointer to its current location plus the value of the offset parameter. PR_SEEK_END. Sets the file pointer to the size of the file plus the value of the offset parameter. Returns The function returns one of the following values: If the function
completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file. If the function fails, the file pointer remains unchanged and the function returns -1. The error code can then be retrieved with PR_GetError. Description This is the idiom for obtaining the current location (expressed as a 64-bit integer) of the file pointer for the file descriptor...
An overview of NSS Internals
individual data items, and the code might be required to abort a task at many positions in the logic. An arena is requested once processing of a task starts, and all memory allocations that are logically associated to that task are requested from the associated arena. The implementation of arenas makes sure that all individual memory blocks are tracked. Once a task is done, regardless whether it
completed or was aborted, the programmer simply needs to release the arena, and all individually allocated blocks will be released automatically. Often freeing is combined with immediately erasing (zeroing, zfree) the memory associated to the arena, in order to make it more difficult for attackers to extract keys from a memory dump. NSS uses many C data structures. Often NSS has multiple implementation...
Certificate functions
ter CERT_CertTimesValid MXR 3.2 and later CERT_ChangeCertTrust MXR 3.2 and later CERT_CheckCertValidTimes MXR 3.2 and later CERT_CheckNameSpace MXR 3.12 and later CERT_CheckCertUsage MXR 3.3 and later CERT_CompareName MXR 3.2 and later CERT_CompareValidityTimes MXR 3.11 and later CERT_
CompleteCRLDecodeEntries MXR 3.6 and later CERT_ConvertAndDecodeCertificate MXR 3.9.3 and later CERT_CopyName MXR 3.4 and later CERT_CopyRDN MXR 3.5 and later CERT_CreateAVA MXR 3.2.1 and later CERT_CreateCertificate MXR 3.5 and later CERT_CreateCertificateRequest MXR 3.2 and later CERT_CreateName M...
HTTP delegation
ed from the HTTP server, the function will provide the results in its "out parameters". Please read the source code documentation to learn how to use this API synchronously or asynchronously. Now that we have explained the interaction between NSS, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. Make sure you have
completed the NSS initialization before you attempt to register the callbacks. Look at SEC_HttpClientFcn, which is a (versioned) table of function pointers. Create an instance of this type and supply a pointer to your implementation for each entry in the function table. Finally register your HTTP client implementation with a call to SEC_RegisterDefaultHttpClient. ...
HTTP delegation
ed from the HTTP server, the function will provide the results in its "out parameters". Please read the source code documentation to learn how to use this API synchronously or asynchronously. Now that we have explained the interaction between NSS, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. Make sure you have
completed the NSS initialization before you attempt to register the callbacks. Look at SEC_HttpClientFcn, which is a (versioned) table of function pointers. Create an instance of this type and supply a pointer to your implementation for each entry in the function table. Finally register your HTTP client implementation with a call to SEC_RegisterDefaultHttpClient. ...
Introduction to Network Security Services
s that use the shared libraries must use only the APIs that they export. Three shared libraries export public functions: The SSL library supports core SSL operations. The S/MIME library supports core S/MIME operations. The NSS library supports core crypto operations. We guarantee that applications using the exported APIs will remain compatible with future versions of those libraries. For a
complete list of public functions exported by these shared libraries in NSS 3.2, see NSS functions. For information on which static libraries in NSS 3.1.1 are replaced by each of the above shared libraries in NSS 3.2 , see Migration from NSS 3.1.1. Figure 1, below, shows a simplified view of the relationships among the three shared libraries listed above and NSPR, which provides low-level cross platform...
NSS_3.12.2_release_notes.html
consistently return PKIX_ValidateNode tree that truly represent failure reasons Bug 408260: certutil usage doesn't give enough information about trust arguments Bug 412311: Replace PR_INTERVAL_NO_WAIT with PR_INTERVAL_NO_TIMEOUT in client initialization calls Bug 423839: Add multiple PKCS#11 token password command line option to NSS tools. Bug 432260: [[@ pkix_pl_HttpDefaultClient_HdrCheck
Complete - PKIX_PL_Memcpy] crashes when there is no content-length header in the http response Bug 436599: PKIX: AIA extension is not used in some Bridge CA / known certs configuration Bug 437804: certutil -R for cert renewal should derive the subject from the cert if none is specified. Bug 444974: Crash upon reinsertion of E-Identity smartcard Bug 447563: modutil -add prints no error explanation ...
NSS 3.14.1 release notes
New Types in ocspt.h CERTOCSPResponderIDType Notable Changes in NSS 3.14.1 Windows CE support has been removed from the code base. Bug 812399 - In NSS 3.14, a regression caused Bug 641052 / CVE-2011-3640 to be re-introduced under certain situations. This regression only affected applications that initialize NSS via the NSS_NoDB_Init function. NSS 3.14.1 includes the
complete fix for this issue. Bug 357025 - NSS 3.14 added support for tokens that make use of CKA_ALWAYS_AUTHENTICATE. However, when authenticating with such tokens, it was possible for an internal lock to be acquired twice, causing a hang. This hang has been fixed in NSS 3.14.1. Bug 802429 - In previous versions of NSS, the "cipherOrder" slot configuration flag was not respected, causing the most rece...
NSS 3.15.2 release notes
NSS 3.15.2 Bug 734007 - sizeof() used incorrectly Bug 900971 - nssutil_ReadSecmodDB() leaks memory Bug 681839 - Allow SSL_HandshakeNegotiatedExtension to be called before the handshake is finished. Bug 848384 - Deprecate the SSL cipher policy code, as it's no longer relevant. It is no longer necessary to call NSS_SetDomesticPolicy because all cipher suites are now allowed by default. A
complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&target_milestone=3.15.2&product=NSS&list_id=7982238 Compatibility NSS 3.15.2 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work with NSS 3...
NSS 3.15.3.1 release notes
de immediately. Bug 946351 - Misissued Google certificates from DCSSI New in NSS 3.15.3.1 New Functionality No new major functionality is introduced in this release. This is a patch release to revoke trust of a subordinate CA certificate that was mis-used to generate a certificate used by a network appliance. Bugs fixed in NSS 3.15.3.1 Bug 946351 - Misissued Google certificates from DCSSI A
complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&target_milestone=3.15.3.1&product=NSS Compatibility NSS 3.15.3.1 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work with NSS 3.15.3.1 sha...
NSS 3.15.3 release notes
failure, if a verifyLog isn't used New in NSS 3.15.3 New Functionality No new major functionality is introduced in this release. This release is a patch release to address CVE-2013-1741, CVE-2013-5605 and CVE-2013-5606. Bugs fixed in NSS 3.15.3 Bug 850478 - List RC4_128 cipher suites after AES_128 cipher suites Bug 919677 - Don't advertise TLS 1.2-only ciphersuites in a TLS 1.1 ClientHello A
complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&target_milestone=3.15.3&product=NSS Compatibility NSS 3.15.3 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work with NSS 3.15.3 shared lib...
NSS 3.15.4 release notes
actices. Updated the set of root CA certificates (version 1.96). Improved SSL/TLS false start. In addition to enabling the SSL_ENABLE_FALSE_START option, an application must now register a callback using the SSL_SetCanFalseStartCallback function. When building on Windows, OS_TARGET now defaults to WIN95. To use the WINNT build configuration, specify OS_TARGET=WINNT. Bugs fixed in NSS 3.15.4 A
complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&target_milestone=3.15.4&product=NSS Compatibility NSS 3.15.4 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work with NSS 3.15.4 shared lib...
NSS 3.15.5 release notes
fetching policy when verifying OCSP responses Bug 949060: Validate the iov input argument (an array of PRIOVec structures) of ssl_WriteV (called via PR_Writev). Applications should still take care when converting struct iov to PRIOVec because the iov_len members of the two structures have different types (size_t vs. int). size_t is unsigned and may be larger than int. Bugs fixed in NSS 3.15.5 A
complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&target_milestone=3.15.5&product=NSS Compatibility NSS 3.15.5 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared libraries will work with NSS 3.15.5 shared lib...
NSS 3.22 release notes
_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 External Policy 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(). ...
NSS 3.26 release notes
ild flag NSS_DISABLE_LIBPKIX which allows compilation of NSS without the libpkix library Notable Changes in NSS 3.26 The following CA certificate was Added CN = ISRG Root X1 SHA-256 Fingerprint: 96:BC:EC:06:26:49:76:F3:74:60:77:9A:CF:28:C5:A7:CF:E8:A3:C0:AA:E1:1A:8F:FC:EE:05:C0:BD:DF:08:C6 NPN is disabled, and ALPN is enabled by default the NSS test suite now
completes with the experimental TLS 1.3 code enabled several test improvements and additions, including a NIST known answer test Bugs fixed in NSS 3.26 This Bugzilla query returns all the bugs fixed in NSS 3.26: https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&product=NSS&target_milestone=3.26 Compatibility NSS 3.26 shared libraries are backw...
NSS 3.31.1 release notes
Introduction The Network Security Services (NSS) team has released NSS 3.31.1, which is a patch release for NSS 3.31. Distribution information The hg tag is NSS_3_31_1_RTM. NSS 3.31.1 requires Netscape Portable Runtime (NSPR) 4.15, or newer. NSS 3.31.1 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_31_1_RTM/src/ New in NSS 3.31.1 No new functionality is introduced in this release. Bugs fixed in NSS 3.31.1 Bug 1381784 - Potential deadlock when using an external PKCS#11 token. ...
NSS 3.35 release notes
nstall custom handlers for a TLS extension. experimental: SSL_SetupAntiReplay - configure a TLS server for 0-RTT anti-replay (TLS 1.3 server only). experimental: SSL_SendSessionTicket - send a session ticket (TLS 1.3 server only). Removed experimental APIs Note that experimental APIs might get removed from NSS without announcing removals in the release notes. This section might be in
complete. The experimental API SSL_UseAltServerHelloType has been disabled. Bugs fixed in NSS 3.35 This Bugzilla query returns all the bugs fixed in NSS 3.35: https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&product=NSS&target_milestone=3.35 Compatibility NSS 3.35 shared libraries are backward compatible with all older NSS 3.x shared librar...
NSS 3.44 release notes
uild fails with -DNSS_DISABLE_CHACHAPOLY 1532312 - post-handshake auth doesn't interoperate with OpenSSL 1542741 - certutil -F crashes with segmentation fault 1546925 - Allow preceding text in try comment 1534468 - Expose ChaCha20 primitive 1418944 - Quote CC/CXX variables passed to nspr 1543545 - Allow to build NSS as a static library 1487597 - Early data that arrives before the handshake
completes can be read afterwards 1548398 - freebl_gtest not building on Linux/Mac 1548722 - Fix some Coverity warnings 1540652 - softoken/sdb.c: Logically dead code 1549413 - Android log lib is not included in build 1537927 - IPsec usage is too restrictive for existing deployments 1549608 - Signature fails with dbm disabled 1549848 - Allow building NSS for iOS using gyp 1549847 - NSS's SQLite comp...
NSS 3.48 release notes
NSS CI Bug 1591315 - Update NSC_Decrypt length in constant time Bug 1562671 - Increase NSS MP KDF default iteration count, by default for modern key4 storage, optionally for legacy key3.db storage Bug 1590972 - Use -std=c99 rather than -std=gnu99 Bug 1590676 - Fix build if ARM doesn't support NEON Bug 1575411 - Enable TLS extended master secret by default Bug 1590970 - SSL_SetTimeFunc has in
complete coverage Bug 1590678 - Remove -Wmaybe-uninitialized warning in tls13esni.c Bug 1588244 - NSS changes for Delegated Credential key strength checks Bug 1459141 - Add more CBC padding tests that missed NSS 3.47 Bug 1590339 - Fix a memory leak in btoa.c Bug 1589810 - fix uninitialized variable warnings from certdata.perl Bug 1573118 - Enable TLS 1.3 by default in NSS This Bugzilla query retur...
NSS 3.51 release notes
rg/pub/mozilla.org/security/nss/releases/NSS_3_51_RTM/src/ Other releases are available in NSS Releases. Notable Changes in NSS 3.51 Updated DTLS 1.3 implementation to Draft-34. See Bug 1608892 for details. Bugs fixed in NSS 3.51 Bug 1608892 - Update DTLS 1.3 implementation to draft-34. Bug 1611209 - Correct swapped PKCS11 values of CKM_AES_CMAC and CKM_AES_CMAC_GENERAL Bug 1612259 -
Complete integration of Wycheproof ECDH test cases Bug 1614183 - Check if PPC __has_include(<sys/auxv.h>) Bug 1614786 - Fix a compilation error for 'getFIPSEnv' "defined but not used" Bug 1615208 - Send DTLS version numbers in DTLS 1.3 supported_versions extension to avoid an incompatibility. Bug 1538980 - SECU_ReadDERFromFile calls strstr on a string that isn't guaranteed to be null-terminated Bug 1...
NSS 3.53 release notes
SS_SERVER_DISTRUST_AFTER attribute, which NSS consumers can query to further refine trust decisions. (Bug 1618404, Bug 1621159) If a builtin certificate has a CKA_NSS_SERVER_DISTRUST_AFTER timestamp before the SCT or NotBefore date of a certificate that builtin issued, then clients can elect not to trust it. This attribute provides a more graceful phase-out for certificate authorities than
complete removal from the root certificate builtin store. Bugs fixed in NSS 3.53 Bug 1640260 - Initialize PBE params (ASAN fix) Bug 1618404 - Set CKA_NSS_SERVER_DISTRUST_AFTER for Symantec root certs Bug 1621159 - Set CKA_NSS_SERVER_DISTRUST_AFTER for Consorci AOC, GRCA, and SK ID root certs Bug 1629414 - PPC64: Correct compilation error between VMX vs. VSX vector instructions Bug 1639033 - ...
NSS 3.54 release notes
ication Authority - G4 SHA-256 Fingerprint: 363F3C849EAB03B0A2A0F636D7B86D04D3AC7FCFE26A0A9121AB9795F6E176DF Bug 1618402 - VeriSign Class 3 Public Primary Certification Authority - G3 SHA-256 Fingerprint: EB04CF5EB1F39AFA762F2BB120F296CBA520C1B97DB1589565B81CB9A17B7244 A number of certificates had their Email trust bit disabled. See Bug 1618402 for a
complete list. Bugs fixed in NSS 3.54 Bug 1528113 - Use ARM Cryptography Extension for SHA256. Bug 1603042 - Add TLS 1.3 external PSK support. Bug 1642802 - Add uint128 support for HACL* curve25519 on Windows. Bug 1645186 - Add "certSIGN Root CA G2" root certificate. Bug 1645174 - Add Microsec's "e-Szigno Root CA 2017" root certificate. Bug 1641716 - Add Microsoft's non-EV root certificates. Bu...
NSS Developer Tutorial
. Sometimes an int parameter can be changed to unsigned int, or an int * parameter can be changed to unsigned int *. Whether such a change is safe needs to be reviewed on a case-by-case basis. Types Structs Members of an exported struct, cannot be reordered or removed. Under certain circumstances, it is safe to add new members to an exported struct at the end. Opaque structs give us
complete freedom to change them, but require applications to call NSS functions, to allocate and free them. Enums The numeric values of public enumerators cannot be changed. To stress this fact, we often explicitly assign numeric values to enumerators, rather than relying on the values assigned by the compiler. Symbol export lists The manifest.mn file, in a directory in the NSS source tree, specifies ...
NSS Sample Code Sample1
rappedEncKey, 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 Server(const char *serverName); ~Server(); ...
nss tech note1
f these templates is identical for both decoders, except where noted. A "NULL Template" is a template that is all zeros, having a zero kind.+ The term "NULL-terminated array", as used throughout this document, means an array of templates, the last of which is a NULL template. void* dest is a pointer to the target area. This is where the decoder stores its output. The type is undefined as it is
completely dependent on the content of the decoder templates.+ This typically points to a struct that is described (or partially described) by the templates. PRArenaPool* arena is a pointer to an NSPR arena pool. This is the arena pool from which the decoder will allocate memory as needed. Decoder templates : The SEC_ASN1Template structure tells the decoder what to do with the input data. This struct...
PKCS #11 Module Specs
nss_params are themselves name/value pairs, parsed with the same rules described above. Valid names inside nss_params are: flags - comma separated list of flag values, parsed case-insensitive. Valid flag values are: internal - this library is actually the Netscape internal library fips - this library is the Netscape internal fips library. critical - if this library cannot be loaded,
completely fail initialization. moduleDB - this library includes NSS specific functions to supply additional module specs for loading. moduleDBOnly - this library has no PKCS #11 functions and is only used for loading additional modules. trustOrder - integer value specifying the order in which the trust information for certificates specified by tokens on this PKCS #11 library should be rolled up. '0'...
FC_DigestFinal
Syntax CK_RV FC_DigestFinal( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen ); Parameters hSession [in] session handle. pDigest [out] pointer to the buffer which will receive the digest or NULL. pulDigestLen [in, out] pointer to location containing the maximum buffer size. Description FC_DigestFinal finishes a multi-part digest operation by returning the
complete digest and clearing the operation context. If pDigest is NULL the length of the digest is returned and FC_DigestFinal may be called again with pDigest set to retrieve the digest. A user may call FC_DigestFinal without logging into the token (to assume the NSS User role). Return value Examples See also FC_DigestInit, NSC_DigestFinal ...
FC_Initialize
Return value FC_Initialize returns the following return codes. CKR_OK: library initialization succeeded. CKR_ARGUMENTS_BAD pInitArgs is NULL. pInitArgs->LibraryParameters is NULL. only some of the lock functions were provided by the application. CKR_CANT_LOCK: the CKF_OS_LOCKING_OK flag is not set in pInitArgs->flags. The NSS cr...
FC_SignFinal
CK_RV FC_SignFinal( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG_PTR pusSignatureLen ); Parameters hSession [in] session handle. pSignature [out] pointer to the buffer which will receive the digest or NULL. pusSignatureLen [in, out] pointer to location containing the maximum buffer size. Description FC_SignFinal finishes a multi-part signing operation by returning the
complete signature and clearing the operation context. If pSignature is NULL the length of the signature is returned and FC_SignFinal may be called again with pSignature set to retrieve the signature. A user must log into the token (to assume the NSS User role) before calling FC_SignFinal. Return value Examples See also FC_SignUpdate, NSC_SignFinal ...
NSS environment variables
this file. This allows packet sniffers to decrypt TLS connections. See documentation. 3.12.6 SSLTRACE Integer Tracing level Note: The code must be built with TRACE defined to use this functionality. Before 3.0 Build-Time Environment Variables These environment variables affect the build (compilation) of NSS. Note: This section is a work in progress and is not yet
complete. Variable Type Description Introduced in version BUILD_OPT Boolean (1 to enable) Do an optimized (not DEBUG) build. Default is to do a DEBUG build. Before 3.0 MOZ_DEBUG_SYMBOLS Boolean (1 to enable) Needed on Windows to build with versions of MSVC (such as VC8 and VC9) that do not understand /PDB:NONE 3.11 MOZ_DEBUG_FLAGS ...
NSS functions
ter CERT_CertTimesValid MXR 3.2 and later CERT_ChangeCertTrust MXR 3.2 and later CERT_CheckCertValidTimes MXR 3.2 and later CERT_CheckNameSpace MXR 3.12 and later CERT_CheckCertUsage MXR 3.3 and later CERT_CompareName MXR 3.2 and later CERT_CompareValidityTimes MXR 3.11 and later CERT_
CompleteCRLDecodeEntries MXR 3.6 and later CERT_ConvertAndDecodeCertificate MXR 3.9.3 and later CERT_CopyName MXR 3.4 and later CERT_CopyRDN MXR 3.5 and later CERT_CreateAVA MXR 3.2.1 and later CERT_CreateCertificate MXR 3.5 and later CERT_CreateCertificateRequest MXR 3.2 and later CERT_CreateName M...
NSS tools : certutil
upgraded. -@ pwfile Give the name of a password file to use for the database being upgraded. Usage and Examples Most of the command options in the examples listed here have more arguments available. The arguments included in these examples are the most common ones or are used to illustrate a specific scenario. Use the -H option to show the
complete list of arguments for each command option. Creating New Security Databases Certificates, keys, and security modules related to managing certificates are stored in three related databases: * cert8.db or cert9.db * key3.db or key4.db * secmod.db or pkcs11.txt These databases must be created before certificates or keys can be generated. certutil -N -d...
NSS tools : modutil
cessfully parsed installation script Current platform is Linux:5.4.08:x86 Using installation parameters for platform Linux:5.4.08:x86 Installed file crypto.so to /tmp/crypto.so Installed file setup.sh to ./pk11inst.dir/setup.sh Executing "./pk11inst.dir/setup.sh"... "./pk11inst.dir/setup.sh" executed successfully Installed module "Example PKCS #11 Module" into module database Installation
completed successfully Adding Module Spec Each module has information stored in the security database about its configuration and parameters. These can be added or edited using the -rawadd command. For the current settings or to see the format of the module spec in the database, use the -rawlist option. modutil -rawadd modulespec Deleting a Module A specific PKCS #11 module can be deleted from the...
gtstd.html
to regret that decision. For production deployment, the NSS team strongly recommends that you either: Use certificates from a competent third-party CA that is already known to your relying party software (e.g. your SSL clients), or Use professional grade CA software, such as Red Hat's Dogtag Certificate System, to set up and operate your own CA and issue your own certificates. For
complete information about the command-line options used in the examples that follow, see Using the Certificate Database Tool. Setting Up the CA DB and Certificate Set up the CA with its own separate set of databases. Create a new certificate database in the CA_db directory. >mkdir CA_db >certutil -N -d CA_db Create the self-signed Root CA certificate, specifying the subject name for ...
sslintro.html
SSL to use when the server asks for client authentication information. This callback is required if you want to do client authentication. You can set the callback function to a standard one that is provided, NSS_GetClientAuthData. SSL_HandshakeCallback. Specifies a callback function that will be used by SSL to inform either a client application or a server application when the SSL handshake is
completed. Optional. Communication At this point the application has set up the socket to communicate using SSL. For simple encrypted and authenticated communications, no further calls to SSL functions are required. A variety of additional SSL functions are available, however. These can be used, for example, when interrupting and restarting socket communications, when the application needs to change ...
NSS Tools modutil
t" Successfully parsed installation script Current platform is WINNT::x86 Using installation parameters for platform WinNT::x86 Installed file crypto.dll to C:/winnt/system32/crypto.dll Installed file setup.exe to ./pk11inst.dir/setup.exe Executing "./pk11inst.dir/setup.exe"... "./pk11inst.dir/setup.exe" executed successfully Installed module "Cryptorific Module" into module database Installation
completed successfully C:\modutil> Changing the Password on a Token This example changes the password for a token on an existing module. C:\modutil> modutil -dbdir "c:\databases" -changepw "Communicator Certificate DB" The Security Module Database Tool displays a warning: WARNING: Performing this operation while Communicator is running couldcause corruption of your security databases. If Communic...
NSS tools : modutil
essfully parsed installation script Current platform is Linux:5.4.08:x86 Using installation parameters for platform Linux:5.4.08:x86 Installed file crypto.so to /tmp/crypto.so Installed file setup.sh to ./pk11inst.dir/setup.sh Executing "./pk11inst.dir/setup.sh"... "./pk11inst.dir/setup.sh" executed successfully Installed module "Example PKCS #11 Module" into module database Installation
completed successfully Adding Module Spec Each module has information stored in the security database about its configuration and parameters. These can be added or edited using the -rawadd command. For the current settings or to see the format of the module spec in the database, use the -rawlist option. modutil -rawadd modulespec Deleting a Module A specific PKCS #11 module can ...
NSS tools : signtool
rom one of two kinds of sources: * An independent certificate authority (CA) that authenticates your identity and charges you a fee. You typically get a certificate from an independent CA if you want to sign software that will be distributed over the Internet. * CA server software running on your corporate intranet or extranet. Netscape Certificate Management System provides a
complete management solution for creating, deploying, and managing certificates, including CAs that issue object-signing certificates. You must also have a certificate for the CA that issues your signing certificate before you can sign files. If the certificate authority's certificate isn't already installed in your copy of Communicator, you typically install it by clicking the appropri...
Necko Interfaces Overview
t - notifies start of async download nsIStreamListener::OnDataAvailable - notifies presence of downloaded data nsIRequestObserver::OnStopRequest - notifies completion of async download, possibly w/ error nsILoadGroup : nsIRequest attribute of a nsIRequest channel impl adds itself to its load group during invocation of AsyncOpen channel impl removes itself from its load group when download
completes load groups in gecko own all channels used to load a particular page (until the channels
complete) all channels owned by a load group can be canceled at once via the load group's nsIRequest::Cancel method nsITransport represents a physical connection, such as a file descriptor or a socket used directly by protocol handler implementations (as well as by mailnews and chatzilla) synchronous...
Rhino Debugger
n on the toolbar Press the F8 key on the keyboard Execution will resume until the current function returns or a breakpoint is hit. Go To resume execution of a script you may do any of the following: Select the Debug->Go menu item on the menu bar Press the Go button on the toolbar Press the F5 key on the keyboard Execution will resume until a breakpoint is hit or the script
completes. Break To stop all running scripts and give control to the debugger you may do any of the following: Select the Debug->Break menu item on the menu bar Press the Break button on the toolbar Press the Pause/Break key on the keyboard Break on Exceptions To give control to the debugger whenever a JavaScript is exception is thrown select the Debug->Break on Exceptions checkbox fr...
SpiderMonkey Build Documentation
st=x86_64-pc-mingw32 --target=x86_64-pc-mingw32 Note: You must have started your MozillaBuild shell with the proper -x64.bat script in order for the 64-bit compilers to be in your PATH. Whatever compiler and flags you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure. Building your application While "How to build your
complete application" is clearly out of scope for this document, here are some tips that will help get you on your way: The SpiderMonkey developers frequently and deliberately change the JSAPI ABI. You cannot use headers built for one version/configuration of JSAPI to create object files which will be linked against another. Support for JS_THREADSAFE was recently removed, and threadsafe builds are now...
Creating JavaScript tests
ent wrong. Testing your test Run your new test locally before checking it in (or posting it for review). Nobody likes patches that include failing tests! See Running Automated Javascript Tests for instructions on how to run jstests or jit-tests. It's also a good sanity check to run each new test against an unpatched shell or browser. The test should fail if it's working properly. Checking in
completed tests Tests are usually reviewed and pushed just like any other code change. Just include the test in your patch. Security-sensitive tests should not be committed until the corresponding bug has been made public. Instead, ask a SpiderMonkey peer how to proceed. It is OK under certain circumstances to push new tests to certain repositories without a code review. Don't do this unless you know w...
Hacking Tips
Since there isn't debug info for the jitted code, you will need to tell gdb that you are looking at ARM code: (gdb) set arm force-mode arm Or you can wrap the x c...
Index
Reference, Obsolete, SpiderMonkey JS_ConvertValue converts a JavaScript value, v, to the specified type. On success, the converted value is stored in *vp. Typically users of this function set vp to point to v, so that if conversion is successful, v now contains the converted value. 222 JS_DecompileFunction JSAPI Reference, SpiderMonkey JS_DecompileFunction generates the
complete source code of a function declaration from a function's compiled form, fun. 223 JS_DecompileFunctionBody JSAPI Reference, SpiderMonkey JS_DecompileFunctionBody generates the source code of a function's body, minus the function keyword, name, parameters, and braces, from a function's compiled form, fun. 224 JS_DecompileScript JSAPI Reference, Reference, Referenc...
Introduction to the JavaScript shell
Environment options There are some environment variables that can be set to alter js shell behavior. JS_STDOUT=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 in
complete 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 ...
JS::SourceBufferHolder
not only groups the buffer and length values, it also provides a way to optionally pass ownership of the buffer to the JS engine without copying. Rules for use: The data array must be allocated with js_malloc or js_realloc if ownership is being granted to the SourceBufferHolder. If ownership is not given to the SourceBufferHolder, then the memory must be kept alive until the JS compilation is
complete. Any code calling SourceBufferHolder::take() must guarantee to keep the memory alive until JS compilation
completes. Normally only the JS engine should be calling take(). Example size_t length = 512; char16_t* chars = static_cast<char16_t*>(js_malloc(sizeof(char16_t) * length)); JS::SourceBufferHolder srcBuf(chars, length, JS::SourceBufferHolder::GiveOwnership); JS::Compile(cx, obj, options, ...
JSObjectOps.newObjectMap
d be removed at any time. Try to avoid using it. Warning! JSObjectOps is not a supported API. Details of the API may change from one release to the next. This documentation should be considered SpiderMonkey internals documentation, not API documentation. See bug 408416 for details. The JSObjectOps.newObjectMap callback is called whenever a new object is created. It creates a JSObjectMap that
completely controls the new object's behavior. Syntax typedef JSObjectMap * (*JSNewObjectMapOp)(JSContext *cx, jsrefcount nrefs, JSObjectOps *ops, JSClass *clasp, JSObject *obj); Name Type Description cx JSContext * Pointer to the JS context in which the new object is being created. nrefs jsrefcount The initial reference count for the new JSObjectMap. ...
JS_AlreadyHasOwnProperty
d properties are not found. (This is the only API that can directly detect that a lazily resolved property has not yet been resolved.) Shared, permanent, delegated properties are not found. (Such properties are an implementation detail of SpiderMonkey. They are meant to be a transparent optimization; this is the only API that breaks the abstraction.) For non-native objects, this falls back on a
complete search. This calls the JSObjectOps.lookupProperty hook. *foundp is set to true only if lookupProperty reports that the property was found on obj itself and not on some other object (even the corresponding outer object, if any). If the property is found on obj, this sets *foundp to true and returns true. If the property is not found on obj, this sets *foundp to false and returns true (to indicate ...
JS_DecompileFunctionBody
nctionBody returns a string containing the source code of the function body. Otherwise, it returns NULL. The source code generated by this function is accurate but unadorned and is not suitable for recompilation without providing the function's declaration. If you decompile a function that makes a native C call, the body of the function only contains the text "[native code]". Notes To decompile a
complete function, including its body and declaration, call JS_DecompileFunction instead. See Also MXR ID Search for JS_DecompileFunctionBody JS_DecompileScript JS_CallFunction JS_CallFunctionName JS_CallFunctionValue JS_CompileFunction JS_DecompileFunction JS_DefineFunction JS_DefineFunctions JS_GetFunctionObject JS_NewFunction JS_SetBranchCallback JS_ValueToFunction ...
JS_DumpHeap
JSTRACE_TYPE_OBJECT = 0x3F, JSTRACE_LAST = JSTRACE_TYPE_OBJECT }; Description See bug 378261 for detail. When 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_SetGCCallback
back in JSAPI 13. Obsolete since JSAPI 13 JS_SetGCCallback returns a pointer to the previously used callback function upon completion. The application may store this return value in order to restore the original callback when the new callback is no longer needed. To restore the original callback, call JS_SetGCCallback a second time, and pass the old callback in as the cb argument. During each
complete garbage collection cycle, the current GC callback is called four times: JSGC_BEGIN Start of GC. The callback may prevent GC from starting by returning false. But even if the callback returns true, the garbage collector may determine that GC is not necessary, in which case the other three callbacks are skipped. JSGC_MARK_END Obsolete since JSAPI 13 End of marking. The callback may...
JS_ShutDown
Context created with JS_NewContext must have been destroyed with JS_DestroyContext, and so on. Calling this method before all other resources have been destroyed has undefined behavior. Failure to call this method, at present, has no adverse effects other than leaking memory. This may not always be the case; it's recommended that all embedders call this method when all other JSAPI operations have
completed, to be future-proof. It is currently not possible to initialize SpiderMonkey multiple times (that is, calling JS_Init, then other JSAPI methods, then JS_ShutDown in that order, then doing so again). This restriction may eventually be lifted. Implementation note: This method has been used to clean up memory allocated by jsdtoa.cpp, memory allocated to implement Date.now() on Windows, and when the...
JS_THREADSAFE
Note: JS_THREADSAFE is now permanently on. JS_THREADSAFE was a compile-time option that enables support for running multiple threads of JavaScript code concurrently as long as no objects or strings are shared between them. We have recently made major changes to this feature. Until recently, sharing objects among threads would mostly work, although scripts could easily make it crash. We have now
completely 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_BeginRequ...
SpiderMonkey 52
The Mozilla JavaScript team is pleased to announce the release of SpiderMonkey 52. You can download full source code from treeherder, by going to the mozilla-esr52 repository and clicking on the first SM(pkg) link you see. That will open a small window in the bottom left with a line like "artifact uploaded:mozjs-52.x.y.tar.bz2". SpiderMonkey 52 is the JavaScript engine that shipped in Firefox 52. It continues to improve performance over previous SpiderMonkey releases. It also contains new language and API features described in detail below. Please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. ...
SpiderMonkey releases
This page lists SpiderMonkey release notes. Note: Standalone SpiderMonkey is not an official product. Our continuous integration system does produce a tarball that is built into a binary that runs our smoke tests, but we do not maintain it nor actively test its suitability for general embedding. We have periodically created "releases", but they are best-effort and in
complete. We do happily accept patches, and make some effort to keep the tip of the Gecko tree minimally working as an embeddable source package. We are very limited in our ability to support older versions, including those labeled as "releases" on this page. The easiest way to fetch the version corresponding to the current Firefox release is to visit the treeherder page for the release repository and click on the first SM(pkg) ...
Running Automated JavaScript Tests
Thus, you can run one test by giving its filename, or any substring that is a substring of that test filename only. You can run all tests in a directory by giving the directory path. You can run three specific tests by giving the three names. Or you can run all but selected tests with the --exclude option. Now that the full set of test262 tests is included in the tree, jstests take a long time to
complete. For a smoke test or if you are not changing language-level functionality, you may wish to use jstests.py PATH_TO_JS_SHELL --exclude=test262 Other options allow you to show the test command lines being run, command output and return codes, run tests named in a given file, exclude tests named in a given file, hide the progress bar, change the timeout, run skipped tests, print output in Tinderbox...
WebReplayRoadmap
re should allow it to work on any operating system: the OS features needed are not specific to macOS or to POSIX systems. Still, porting it to other POSIX systems (Linux, Android) will be easier than Windows, due to the overlap with macOS. There is, however, a partial Windows port from an older version of the architecture that can replay a simple page but not rewind, which should make writing a
complete Windows port easier. Cloud Integration (partially implemented) Storing recordings in the cloud and interacting with them via the debugger could streamline several features described above: Difficulties when recording and replaying on different machines with incompatible firefox builds or operating systems will be smoothed out. Recordings can be uploaded, and cloud services can locate the co...
Zest
as a domain-specific language) developed by the Mozilla security team and is intended to be used in web oriented security tools. The language is written in JSON, but we do not expect people to write Zest in this format - it is designed to be a visual language. The core language does not define any graphical representation - that is expected to be defined by the tools that integrate Zest. It is
completely free, open source and can be included in any tool whether open or closed, free or commercial. Zest is still at a very early stage of development, but is has been made available so that anyone can play around with it. All constructive feedback is very welcome. Anyone can contribute to the onward development of Zest, and teams or individuals who develop security tools are especially welcome ...
Mozilla Projects
by the Mozilla security team and is intended to be used in web oriented security tools. The language is written in JSON, but we do not expect people to write Zest in this format - it is designed to be a visual language. The core language does not define any graphical representation - that is expected to be defined by the tools that integrate Zest. It is
completely free, open source and can be included in any tool whether open or closed, free or commercial. Zest is still at a very early stage of development, but is has been made available so that anyone can play around with it. All constructive feedback is very welcome. Anyone can contribute to the onward development of Zest, and teams or individuals who develo...
Handling Mozilla Security Bugs
mation is shared only with those who have a need to know, to the extent they need to know, and that such information is labeled and treated as the organization generally treats confidential material. Not to post descriptions of exploits in public forums like newsgroups. To be careful in whom they add to the CC field of a bug (since all those CC'd on a security bug potentially have access to the
complete bug report). When a bug is put into the security bug group, the group members, bug reporter, and others associated with the bug will decide by consensus, either through comments on the bug or the group mailing list, whether an immediate warning to users is appropriate and how it should be worded. The goals of this warning are: To inform Mozilla users and testers of potential security risks i...
Task graph
s created to decide what to do with the push. The decision task creates a lot of additional tasks. These tasks include build and test tasks, along with lots of other kinds of tasks to build docker images, build toolchains, perform analyses, check syntax, and so on. These tasks are arranged in a "task graph", with some tasks (e.g., tests) depending on others (builds). Once its prerequisite tasks
complete, a dependent task begins. The result of each task is sent to TreeHerder where developers and sheriffs can track the status of the push. The outputs from each task, log files, Firefox installers, and so on, appear attached to each task when it
completes. These are viewable in the Task Inspector. All of this is controlled from within the Gecko source code, through a process called task-graph ge...
Gecko object attributes
at the hiding or removal of items is not. Please see the ARIA States and Properties module for more information. Exposed in ARIA: aria-relevant container-atomic Is this change inside a region that should always be presented at once. If yes, member-of relation will point to the root of the region. See the Live Region Support for more information. container-busy The current changes are not yet
complete. A state change event for the A11y API's BUSY state will be fired on the container object currently marked as BUSY, once it is no longer BUSY. This is especially important in atomic regions. The entire atomic region should be presented once when it is finally no longer BUSY. See the Live Region Support for more information. container-live Interruption policy. See the Live Region Support for mor...
AT APIs Support
different from developing a web page, but the elements available to add widgets are more powerful and designed to be similar to desktop widgets. Examples of XUL applications: Firefox - web-browser Thunderbird - email client Seamonkey - web-browser, advanced e-mail and newsgroup client, IRC chat client, and HTML editing made simple Sunbird - cross-platform calendar application KompoZer - a
complete Web Authoring System for Linux Desktop, Microsoft Windows and Macintosh users to rival programs like FrontPage and Dreamweaver. Open Komodo - platform for building developer environments Miro - a free, open source internet tv and video player Any XulRunner application (Songbird media player, etc.) Extensions to other XUL apps (e.g. Firefox extensions) Gecko Version For Firefox and all othe...
DocShell
nsWebBrowser project page (outlines the design of nsWebBrowser and DocShell). ...
Feed content access API
r Parses RSS and Atom feeds. nsIFeedProgressListener Implemented by the program that wants to parse an RSS or Atom feed to receive messages during the parsing process. nsIFeedResult Describes the result of parsing a feed. nsIFeedResultListener Implemented by the program that wants to parse an RSS or Atom feed to receive notification when parsing is
complete. nsIFeedTextConstruct Represents text values in a feed; includes functions that let you fetch the text as plain text or HTML. nsIScriptableUnescapeHTML A utility 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 t...
The Places database
The places schema looks like so: Core URL table moz_places: This is the main table of URIs and is managed by the history service (see also History service design). Any time a Places component wants to reference a URL, whether visited or not, it refers to this table. Each entry has an optional reference to the moz_favicon table to identify the favicon of the page. No two entries may have the same value in the url column. ...
Frecency algorithm
unique URI in Places, encompassing bookmarks, history and tags. This score is determined by the amount of revisitation, the type of those visits, how recent they were, and whether the URI was bookmarked or tagged. The word "frecency" itself is a combination of the words "frequency" and "recency." The default frecency value for all valid entries is -1. Places with this value can show up in auto
complete results. Invalid places have a frecency value of zero, and will not show up in auto
complete results. Examples of invalid places are "place:" queries, and unvisited livemark feed entries. The frecency calculation process For the 10 most recent visits (where 10 is determined by places.frecency.numVisits): .. Determine percentage bonus for type of visit (ie: the "transition typ...
Places Expiration
d performant) value. All of expiration uses the Storage async API, that ensures I/O is in a separate thread, plus it won't block any read thanks to the use of the WAL journaling system. Common expiration runs on a timer, every 3 minutes and uses a simple adaptive algorithm: if the last step was unable to expire enough entries the next one will expire more entries, otherwise if the previous step
completed the cleanup the next step will be delayed. This ensures expiration doesn't lag behind without hitting performances when there is no need for it. Apart this periodic expiration, there are other steps on idle, on shutdown on clear history. On Idle On idle it expires a larger chunk of pages, then timed expiration is stopped. This ensures to not interfere with standby tasks and preserves battery ...
Places utilities for JavaScript
OM node getViewForNode(aNode) Parameters aNode a DOM node Return type Return the closet ancestor places view if exists, null otherwsie. markPageAsTyped() By calling this before we visit a URL, we will use TRANSITION_TYPED as the transition for the visit to that URL (if we don't have a referrer). This is used when visiting pages from the history menu, history sidebar, url bar, url auto
complete results, and history searches from the places organizer. If we don't call this, we'll treat those visits as TRANSITION_LINK. markPageAsTyped(string aURL) markPageAsFollowedBookmark() By calling this before we visit a URL, we will use TRANSITION_BOOKMARK as the transition for the visit to that URL (if we don't have a referrer). This is used when visiting pages from the bookmarks menu, persona...
Retrieving part of the bookmarks tree
rootNode.getChild(i); dump("Child: " + node.title + "\n"); } // close a container after using it! rootNode.containerOpen = false; If you encounter a node with a type of RESULT_TYPE_FOLDER or another type of container, you can open these folders 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. ...
Using the Places keywords API
A keyword can only be associated to a given url, it's not possible to associate the same keyword with multiple urls (doing so will just update the url it's pointing to). Each keyword can be associated with POST data, in such a case a POST action will be executed when the given URL is selected from the Awesomebar. Different keywords can reference the same url, if their POST data differ. ...
XML Extras
ion 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 (Currently, the JavaScript constructor is XMLSerializer()) nsIDOMParser (Currently, the JavaScript constructor is DOMParser()) nsIXMLHttpRequest Please see the XML Linking and Pointing section in XML in Mozilla document for FIXptr and XPointer documentation. How can I help? Help with testing the components containe...
Starting WebLock
replace existing &previous); if (previous) nsMemory::Free(previous); // free the memory the replaced value might have used The unregistration, which should occur in the unregistration callback, looks like this: rv = catman->DeleteCategoryEntry("xpcom-startup", "WebLock", PR_TRUE); // persist A
complete code listing for registering WebLock as a startup observer follows: #define MOZILLA_STRICT_API #include "nsIGenericFactory.h" #include "nsCOMPtr.h" #include "nsXPCOM.h" #include "nsIServiceManager.h" #include "nsICategoryManager.h" #include "nsMemory.h" #include "nsIObserver.h" #include "nsEmbedString.h" #define WebLock_CID \ { 0x777f7150, 0x4a2b, 0x4301, \ { 0xad, 0x10, 0x5e, 0xab, 0x25, ...
Using XPCOM Utilities to Make Things Easier
rv will be set to NS_OK. If QueryInterface fails, localFile will be null, and rv will be set to a specific error code corresponding to the reason for the failure. In this construct, the result code rv is an optional parameter. If you don't care what the error code is, you can simply drop it from the function call. From this point on, we'll be using nsCOMPtrs as much as possible in WebLock. For a
complete listing of smart pointer functionality, see mozilla.org's nsCOMPtr documentationXXX this should be in devmo. Note: other-parts This section discusses the main parameters of this structure. For a
complete listing of all available options you can look at the
complete reference in the XPCOM API Reference. Note: nsISupports-warning Note that NS_DECL_ISUPPORTS doesn't obey the general rule in whic...
Detailed XPCOM hashtable guide
declare an entry class. If you are hashing a simple key type to a simple data type, they are generally a better choice. nsBaseHashtable and friends: nsDataHashtable, nsInterfaceHashtable, and nsClassHashtable These C++ templates provide a high-level interface for using hashtables that hides most of the complexities of PLDHash. They provide the following features: hashtable operations can be
completed without using an entry class, making code easier to read; optional thread-safety: the hashtable can manage a read-write lock around the table; predefined key classes provide automatic cleanup of strings/interfaces nsInterfaceHashtable and nsClassHashtable automatically release/delete objects to avoid leaks. nsBaseHashtable is not used directly; choose one of the three derivative classes bas...
Receiving startup notifications
tartup notifications. The startup process During application startup, the application's manifest is used to get a list of the components it needs to register, and those components are loaded. This gets enough of XPCOM and the application loaded and running that the Extension Manager can then be loaded and handle installing, uninstalling, and updating any installed extensions. Once that process is
completed, extensions can then be loaded by simply reading their manifests, loading their components, and continuing with application startup, all without having to restart the browser. Receiving startup notifications prior to Gecko 2.0 (Firefox 4) To receive startup notifications, one needs to register with the "app-startup" category using nsICategoryManager; having done so, the component will receive th...
Introduction to XPCOM for the DOM
e of a concrete C++ class". The important thing to note is that a pointer to nsIFoo can only call the methods defined on the nsIFoo interface, and on its parents. For instance, if nsFoo implements two different interfaces, nsIFoo and nsIBar, a pointer to nsIFoo cannot call the methods defined on nsIBar and vice-versa. Note: the previous paragraph is extremely important. If you haven't grasped it
completely, there is no need to read further. Reference counting basics XPCOM uses a reference counting mechanism (refcount in short) to make sure that no object is deleted while interface pointers still point at that object. Indeed, dereferencing a pointer that points to a deleted object can have bad consequences. That is why each time a pointer to an interface is assigned the address of an object, we ...
Components.isSuccessCode
) { return (returnCode & 0x80000000) === 0; } Since failure error codes are turned into exceptions when encountered in JavaScript, this function usually is not necessary. However, if you are using asynchronous APIs, it may be essential. For example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is
completed. If the task is sufficiently complex that it can fail, the notification will include a 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 stre...
Components.utils.importGlobalProperties
vices} = Cu.import("resource://gre/modules/Services.jsm", {}); Reference: Stackoverflow :: Use Blob on firefox add-on hiddenDOMWindow The hidden DOMWindow has all of these objects automatically imported. The downside of using hiddenDOMWindow is that on startup of Firefox, the hiddenDOMWindow objects cannot be accessed until it is fully loaded. Therefore readyState must be checked, if it is not
complete, then a load listener must be attached. Once readyState is
complete then the objects can be used. For example this is how to ues the File object. var domfile = Services.appShell.hiddenDOMWindow.File('/path/to/file'); XPCOM Components Some objects have an XPCOM alternative, which typically allows more flexibility then the DOM version Here is an example of how to use the DOM XMLHttpRequest thr...
Components object
Provides access to the value of the relimit property in the JavaScript environment. utils.reportError Reports a JavaScript Error object to the Error Console. utils.schedulePreciseGC Requests that garbage collection occur sometime in the future when no JavaScript code is running; accepts a callback function to receive notification once collection is
complete. utils.setGCZeal() Sets the GC zeal level for the context. utils.strict Provides access to the value of the strict property in the JavaScript environment. utils.werror Provides access to the value of the werror property in the JavaScript environment. utils.Sandbox Creates sandbox objects for use with evalInSandbo...
amIInstallCallback
toolkit/mozapps/extensions/amIInstallTrigger.idlScriptable A callback function that web pages can implement to be notified when triggered installs
complete. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void onInstallEnded(in AString aUrl, in PRInt32 aStatus); Methods onInstallEnded() Called when an install
completes or fails. void onInstallEnded( in AString aUrl, in PRInt32 aStatus ); Parameters aUrl The url of the add-on being installed. aStatus 0 if the install was successful or negative if not. ...
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 1 ...
imgIRequest
e() 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_
COMPLETE 0x4 The data has been fully loaded to memory, but not necessarily fully decoded. STATUS_ERROR 0x8 An error occurred loading the image. STATUS_FRAME_
COMPLETE 0x10 The first frame has been
completely decoded. STATUS_DECODE_
COMPLETE 0x20 The whole image has been decoded. CORS_NONE 1 CORS modes images can be loaded with. By default, all images are loaded with CORS_NONE and cannot be used cr...
mozIAsyncHistory
sURIVisited( 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 mozIPlaceInfo aPlaceInfo, in mozIVisitInfoCallback aCallback Optional ); Parameters ...
mozIRegistry
It's not really about any "registry interface" so much as it's about how Mozilla supports a more dynamic binding between interface clients and the code that actually provides the implementation of those interfaces. It happens that this objective requires storing information about which implementation to use in a place distinct from your source code. ...
mozIRepresentativeColorCallback
toolkit/components/places/mozIColorAnalyzer.idlScriptable Provides callback methods for mozIColorAnalyzer 1.0 66 Introduced Gecko 17.0 Inherits from: nsISupports Last changed in Gecko 17.0 (Firefox 17.0 / Thunderbird 17.0 / SeaMonkey 2.14) Method overview void on
Complete(in boolean success, [optional] in unsigned long color); Methods on
Complete() Will be called when color analysis finishes. void on
Complete( in boolean success, [optional] in unsigned long color ); Parameters success True if analysis was successful, false otherwise. Analysis can fail if the image is transparent, imageURI doesn't resolve to a valid image, or the image is too big. color The representative color as an integer in RGB form. e.g. 0x...
mozIStorageCompletionCallback
This interface should be implemented to handle callbacks from asynchronous Storage API routines. storage/public/mozIStorageCompletionCallback.idlScriptable Please add a summary to this article. Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Inherits from: nsISupports Method overview void
complete(); Methods
complete() Called when an asynchronous storage routine has
completed. void
complete(); Parameters None. ...
mozIStorageConnection
nt Constant Value Description DEFAULT_PAGE_SIZE 32768 The default size for SQLite database pages. This is used by the Storage API when creating new databases, and must match the SQLITE_DEFAULT_PAGE_SIZE configured in db/sqlite3/src/Makefile.in. Methods asyncClose() Asynchronously closes a database connection, allowing all pending asynchronous statements to
complete first. void asyncClose( in mozIStorageCompletionCallback aCallback Optional ); Parameters aCallback Optional An optional callback handler to be executed when the connection is successfully closed. That object's mozIStorageCompletionCallback.
complete() routine will be called once the connection is closed. Exceptions thrown NS_ERROR_UNEXPECTED Thrown if the method was called on a thr...
mozIStorageStatementCallback
hort aReason ); Parameters aReason The reason the statement stopped executing; see the list of possible values in the Constants section. handleError() Called when an error occurs while executing a statement. This function may be called more than once with a different storageIError each time for any given asynchronous statement, and handleCompletion will be called once the statement is
complete. void handleError( in mozIStorageError aError ); Parameters aError A mozIStorageError object describing the error that occurred. handleResult() Called when results from the statement are available. Generally, this method will be called several times, each time providing one or more results. Once there are no more results, handleCompletion will be called. void handleResult( in ...
mozIVisitStatusCallback
Implement this method to determine the results of the request. void isVisited( in nsIURI aURI, in boolean aVisitedStatus ); Parameters aURI The URI that was checked to see if it's been visited. aVisitedStatus true if the specified URI has been visited; otherwise false. See also mozIAsyncHistory ...
nsIAccessibleEvent
0x0025 0x0022 A dialog box has been closed. EVENT_SCROLLING_START 0x0026 0x0023 Scrolling has started on a scroll bar. EVENT_SCROLLING_END 0x0027 0x0024 Scrolling has ended on a scroll bar. EVENT_MINIMIZE_START 0x0028 0x0025 A window object is about to be minimized or maximized. EVENT_MINIMIZE_END 0x0029 0x0026 A window object has been minimized or maximized. EVENT_DOCUMENT_LOAD_
COMPLETE 0x002B 0x0027 The loading of the document has
completed. EVENT_DOCUMENT_RELOAD 0x002C 0x0028 The document contents are being reloaded. EVENT_DOCUMENT_LOAD_STOPPED 0x002D 0x0029 The loading of the document was interrupted. EVENT_DOCUMENT_ATTRIBUTES_CHANGED 0x002E 0x002A The document wide attributes of the document object have changed. EVENT_DOCUMENT_CONTENT_CHANGED 0x002F 0x002B ...
nsIAlertsService
toolkit/components/alerts/nsIAlertsService.idlScriptable This interface can be used to notify the user of something that does not require an immediate reaction. For example, it can be used to notify the user that their downloads are
complete or that they have new mail. 1.0 66 Introduced Gecko 1.7 Inherits from: nsISupports Last changed in Gecko 22 (Firefox 22 / Thunderbird 22 / SeaMonkey 2.19) By default a message is displayed in a small window that slides up from the bottom of the screen, holds there for a few seconds, then slides down. The specific appearance varies from platform to platform. Note: Prior Firefox 22, the alerts service was only supported on Windows in Gecko 1.7, had no effect on Mac OS X in Gecko 1.8, but was fully supported in Mac OS X i...
nsIArray
ype Description length unsigned long The number of elements in the array. Read only. Methods enumerate() Enumerate the array. nsISimpleEnumerator enumerate(); Parameters None. Return value A new enumerator positioned at the start of the array. Exceptions thrown NS_ERROR_FAILURE If the array is empty (to make it easy to detect errors). NS_ERROR_OUT_OF_MEMORY If there is not enough memory to
complete the operation. indexOf() Get the position of a specific element. Note that since null is a valid input, exceptions are used to indicate that an element is not found. unsigned long indexOf( in unsigned long startIndex, in nsISupports element ); Parameters startIndex The initial element to search in the array. To start at the beginning, use 0 as the startIndex. element The element you are lo...
nsIAsyncStreamCopier
asyncCopy(in nsIRequestObserver aObserver, in nsISupports aObserverContext); void init(in nsIInputStream aSource, in nsIOutputStream aSink, in nsIEventTarget aTarget, in boolean aSourceBuffered, in boolean aSinkBuffered, in unsigned long aChunkSize, in boolean aCloseSource, in boolean aCloseSink); Methods asyncCopy() Starts the copy operation. The specified observer is notified when the copy
completes. void asyncCopy( in nsIRequestObserver aObserver, in nsISupports aObserverContext ); Parameters aObserver Receives notifications. aObserverContext The object to receive notifications with information about the progress of the copy operation. init() Initializes the stream copier. Note: At least one of the streams must be buffered. void init( in nsIInputStream aSource, in nsIOutputStrea...
nsICacheListener
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 ...
nsICachingChannel
e same as cacheToken but accessing the offline app cache token if there is any. Exceptions thrown NS_ERROR_NOT_AVAILABLE When there is not offline cache token. Constants Constant Value Description LOAD_NO_NETWORK_IO 1 << 26 This load flag inhibits fetching from the net. An error of NS_ERROR_DOCUMENT_NOT_CACHED will be sent to the listener's onStopRequest if network IO is necessary to
complete the request. This flag can be used to find out whether fetching this URL would cause validation of the cache entry via the network. Combining this flag with LOAD_BYPASS_LOCAL_CACHE will cause all loads to fail. This flag differs from LOAD_ONLY_FROM_CACHE in that this flag fails the load if validation is required while LOAD_ONLY_FROM_CACHE skips validation where possible. LOAD_CHECK_OFFLINE_CAC...
nsIChannel
ast 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. 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 asyncOp...
nsICryptoHMAC
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 that was re...
nsICryptoHash
lla/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 data that ...
nsIDNSListener
netwerk/dns/nsIDNSListener.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onLookup
Complete(in nsICancelable aRequest, in nsIDNSRecord aRecord, in nsresult aStatus); Methods onLookup
Complete() Called when an asynchronous host lookup
completes. void onLookup
Complete( in nsICancelable aRequest, in nsIDNSRecord aRecord, in nsresult aStatus ); Parameters aRequest The value returned from asyncResolve. aRecord The DNS record corresponding to the hostname that was resolved. this parameter is null if there was an error. aStatus If the lookup failed, this parameter gives the reason. ...
nsIDOMEvent
opagation() Prevents other event listeners from being triggered and, unlike stopPropagation() its effect is immediate. void stopImmediatePropagation(); Parameters None. stopPropagation() The stopPropagation method is used prevent further propagation of an event during event flow. If this method is called by any EventListener the event will cease propagating through the tree. The event will
complete dispatch to all listeners on the current EventTarget before event flow stops. This method may be used during any stage of event flow. void stopPropagation(); Parameters None. ...
nsIDOMFile
a Blob. This will likely change in the future, so avoid using any non-standard methods offered by this interface in order to ensure future compatibility. content/base/public/nsIDOMFile.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports This interface implements the DOM File object; for
complete documentation, read up on that. See also nsIDOMFileList nsIDOMFileException DataTransfer Drag and drop ...
nsIDOMGeoPositionError
error that occurred while performing geolocation operations. dom/interfaces/geolocation/nsIDOMGeoPositionError.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports Attributes Attribute Type Description code short Numerical error code; see Error constants for a
complete list. Read only. message DOMString Human readable error message. Read only. Gecko 1.9.2 note The message attribute was removed in Gecko 1.9.2 (Firefox 3.6). Error constants Constant Value Description PERMISSION_DENIED 1 The user denied permission to retrieve location data. POSITION_UNAVAILABLE 2 Unable to access location da...
nsIDOMOfflineResourceList
ss nsIDOMEventListener An event listener to be called periodically throughout the download process. onupdateready nsIDOMEventListener An event listener to be called when a resource update is ready; this event is not currently used since versioned application caches aren't supported yet. oncached nsIDOMEventListener An event listener to be called when caching is
complete. status unsigned short One of the Application cache state constants indicating the status of the application cache. Constants Application cache state constants Constant Value Description UNCACHED 0 The object isn't associated with an application cache. IDLE 1 The application cache is not in the process of being updated. ...
nsIDOMProgressEvent
bject. 1.0 66 Introduced Gecko 1.9.1 Deprecated Gecko 22 Inherits from: nsIDOMEvent Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) The nsIDOMProgressEvent is used in the media elements (<video> and <audio>) to inform interested code of the progress of the media download. This implementation is a placeholder until the specification is
complete, and is compatible with the WebKit ProgressEvent. Method overview void initProgressEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in boolean lengthComputableArg, in unsigned long long loadedArg, in unsigned long long totalArg); Deprecated since Gecko 22.0 Attributes Attribute Type Description lengthComputable boolean ...
nsIDOMWindowInternal
terfaces used to represent a window in the DOM. 66 Introduced Gecko 1.0 Deprecated Gecko 8.0 Inherits from: nsIDOMWindow Last 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. 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).
nsIDirectoryEnumerator
xpcom/io/nsIDirectoryEnumerator.idlScriptable This interface provides a means for enumerating the contents of a directory. It is similar to nsISimpleEnumerator except the retrieved entries are QI'ed to nsIFile, and there is a mechanism for closing the directory when the enumeration is
complete. 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 close(); Attributes Attribute Type Description nextFile nsIFile The next file in the sequence. The nextFile attribute is the first element upon the first call. This attribute is null if there is no next element. Read only. Methods close() Closes the directory being enumerated,...
nsIDocShell
res this parameter. aURL The URL associated with the new history entry. For instance, if the user tries to reload the page, then this is the URL that will be reloaded. aReplace Whether to modify the current history entry instead of creating a new one. beginRestore() Begin firing WebProgressListener notifications for restoring a page presentation. This method will post an event to
complete the simulated load after returning to the event loop. void beginRestore( in nsIContentViewer viewer, in boolean top ); Parameters viewer The content viewer whose document we are starting to load. If null, it defaults to the docshell's current content viewer, creating one if necessary. top Should be true for the toplevel docshell that is being restored; it will be set to fals...
nsIDownloadProgressListener
d ); Parameters aWebProgress The nsIWebProgress instance used by the Download Manager to monitor downloads. aRequest The nsIChannel that changed state. This parameter will not be null. aCurSelfProgress The current amount of progress that's been made on the download specified by aDownload. aMaxSelfProgress The value that the self progress needs to reach to indicate that the download is
complete. aCurTotalProgress The current amount of progress that's been made on all downloads. aMaxTotalProgress The value that the total progress needs to reach to indicate that all downloads are
complete. aDownload The nsIDownload object whose progress is represented by the aCurSelfProgress and aMaxSelfProgress parameters. onSecurityChange() Called when the level of security being used while dow...
nsIDownloader
netwerk/base/public/nsIDownloader.idlScriptable A special implementation of a nsIStreamListener that will make the contents of the stream available as a file. This may utilize the disk cache as an optimization to avoid an extra copy of the data on disk. The resulting file is valid from the time the downloader
completes until the last reference to the downloader is released. Inherits from: nsIStreamListener Last changed in Gecko 1.7 Method overview void init(in nsIDownloadObserver observer, in nsIFile downloadLocation); Methods init() Initialize this downloader. void init( in nsIDownloadObserver observer, in nsIFile downloadLocation ); Parameters observer The nsIDownloadObserver to be notified when the download
completes. downloadLocation The loc...
nsIDragSession
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. Native code only! Methods getData() Gets data from a drag and drop operation. Can be called while the drag is in process or after the drop has
completed. void getData( in nsITransferable aTransferable, in unsigned long aItemIndex ); Parameters aTransferable The transferable for the data to be put into. aItemIndex Which of multiple drag items, zero-based. Must be less than numDropItems. isDataFlavorSupported() Checks to see if any of the native data on the clipboard matches a given data flavor. If numDropItems is greater than one,...
nsIDynamicContainer
state. A service with large numbers 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 contain...
nsIEditorObserver
editor/idl/nsIEditorObserver.idlScriptable Used by applications wishing to be notified when the editor has
completed a user action. 66 Introduced Gecko 1.0 Obsolete Gecko 18 Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void EditAction(); Methods EditAction() Called after the editor
completes a user action. void EditAction(); Parameters None. ...
nsIFaviconService
his cache will also be written to if you use setAndLoadFaviconForPage() method and it encounters an error while fetching an icon. void addFailedFavicon( in nsIURI aFaviconURI ); Parameters aFaviconURI The URI of an icon in the favicon service. Can be null. expireAllFavicons() Expires all known favicons, removing them from the database. Note: This is an asynchronous operation; when it
completes, a "places-favicons-expired" notification is dispatched through the observer's service. void expireAllFavicons(); Parameters None. getFaviconData() Obsolete since Gecko 22.0 (Firefox 22.0 / Thunderbird 22.0 / SeaMonkey 2.19) Note: This method was removed in Gecko 22.0. You should use the new async API mozIAsyncFavicons.getFaviconDataForPage() instead. This method re...
nsIFeedResultListener
This interface should be implemented by programs to receive events from the feed parser as parsing progresses. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void handleResult(in nsIFeedResult result); Methods handleResult() Called when feed processing is
complete. Even if an error occurred during processing, there may be valid data available for feed-level data or entries processed before the error occurred. If you don't care about doing progress display or the like, this is all you need to implement in order to receive the parsed feed. void handleResult( in nsIFeedResult result ); Parameters result An nsIFeedResult describing the parsed feed. ...
nsIFormHistory2
s, and the values correspond to values the user has submitted. So, several values may exist for a single name. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed 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 auto
complete 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 ...
nsIHttpUpgradeListener
0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) This is used, for example, by WebSockets in order to upgrade an HTTP channel to use the WebSocket protocol. Method overview void onTransportAvailable(in nsISocketTransport aTransport, in nsIAsyncInputStream aSocketIn, in nsIAsyncOutputStream aSocketOut); Methods onTransportAvailable() Called when an HTTP protocol upgrade attempt is
completed, passing in the information needed by the protocol handler to take over the channel that is no longer being used by HTTP. Note: To begin a protocol upgrade, call nsIHttpChannelInternal.HTTPUpgrade(). void onTransportAvailable( in nsISocketTransport aTransport, in nsIAsyncInputStream aSocketIn, in nsIAsyncOutputStream aSocketOut ); Parameters aTransport The nsISocketTransport de...
nsIInstallLocation
e item's resources are managed independently of the Extension System, false otherwise. removeFile() Removes a file from the stage. This cleans up the stage if there is nothing else left after the remove operation. void removeFile( in nsIFile file ); Parameters file The file to remove. stageFile() Stages the specified file by copying it to some location from where it can be retrieved later to
complete installation. nsIFile stageFile( in nsIFile file, in AString id ); Parameters file The file to stage. id The GUID of the item the file represents. Return value The staged file. ...
nsILoginManagerStorage
o password should be required in order to remove all logins. void removeAllLogins(); Parameters None. removeLogin() Implement this method to remove the specified login from the login store. Gecko 1.9.1 note The values of any nsILoginMetaInfo properties are ignored. void removeLogin( in nsILoginInfo aLogin ); Parameters aLogin The login to remove from the login store. A login must match
completely (except for its nsILoginMetaInfo data) to be removed. searchLogins() Implement this to search for logins in the login manager's data store, returning an array of matching logins. If there are no matching logins, return an empty array. void searchLogins( out unsigned long count, in nsIPropertyBag matchData, [retval, array, size_is(count)] out nsILoginInfo logins ); Parameters count The ...
nsIMemoryMultiReporter
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 nsIMemoryReporterManager nsIMemoryReporter ...
nsIMicrosummaryService
d the necessary information (the generator and/or page) before refreshing the microsummary. Callers should check the content property of the returned microsummary object to distinguish between sync and async refreshes. If its value is null, then it's an async refresh, and the caller should register itself as an nsIMicrosummaryObserver via nsIMicrosummary.addObserver() to find out when the refresh
completes. nsIMicrosummary refreshMicrosummary( in long long bookmarkID ); Parameters bookmarkID The bookmark whose microsummary is being refreshed. Return value Returns the microsummary being refreshed. removeMicrosummary() Remove the current microsummary for the given bookmark. void removeMicrosummary( in long long bookmarkID ); Parameters bookmarkID The bookmark for which to re...
nsIMimeConverter
ng propertyName); Parameters propertyName The name of the property to retrieve. Return Value The value of the property. B64EncoderInit() Get an integer property. Usually you would use this to store you own properties. unsigned long getUint32Property(in string propertyName); Parameters propertyName The name of the property to retrieve. Thunderbird stored Uint32 properties (not a
complete list): indexed Used for Spotlight integration on OSX. notAPhishMessage Indicates whether phisihing filters have been run on a message yet. Return Value The value of the property. QPEncoderInit() void setUint32Property(in string propertyName, in unsigned long propertyVal); Parameters propertyName The name of the property to set. propertyVal The...
nsIMimeHeaders
n string headerName, in boolean getAllOfThem ); Parameters headerName Missing Description getAllOfThem Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description initialize() void initialize( [const] in string allHeaders, in long allHeadersSize ); Parameters allHeaders Insert the
complete Message Content allHeadersSize Length of the passed in content Exceptions thrown Missing Exception Missing Description Remarks See also ...
nsIMsgDBHdr
ropertyName); Parameters propertyName The name of the property to retrieve. Return Value The value of the property. getUint32Property() Get an integer property. Usually you would use this to store your own properties. unsigned long getUint32Property(in string propertyName); Parameters propertyName The name of the property to retrieve. Thunderbird stored Uint32 properties (not a
complete list): indexed Used for Spotlight integration on OSX. notAPhishMessage Indicates whether phisihing filters have been run on a message yet. Return Value The value of the property. setUint32Property() void setUint32Property(in string propertyName, in unsigned long propertyVal); Parameters propertyName The name of the property to set. propertyVal ...
nsIMsgIdentity
compatability. Use doBcc and doBccList instead. bccOthers boolean bccList AString doBcc boolean doBccList AString draftFolder AString stationeryFolder AString showSaveMsgDlg boolean directoryServer AString overrideGlobalPref boolean auto
completeToMyDomain boolean If this is false, don't append the user's domain to an auto
complete address with no matches. valid boolean Determines if the UI should use this identity and the wizard uses this to determine whether or not to ask the user to
complete all the fields. smtpServerKey AString The preferred SMTP server for this identity. If this is set, this is the ...
nsIMutableArray
s legal to add null elements to the array. Note also that null elements can be created as a side effect of insertElementAt(). Conversely, if insertElementAt() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsIArray.queryElementAt() will never return a null value. Any of these methods may throw NS_ERROR_OUT_OF_MEMORY when the array must grow to
complete the call, but the allocation fails. Method overview void appendElement(in nsISupports element, in boolean weak); void clear(); void insertElementAt(in nsISupports element, in unsigned long index, in boolean weak); void removeElementAt(in unsigned long index); void replaceElementAt(in nsISupports element, in unsigned long index, in boolean weak); ...
nsINavHistoryObserver
( in nsIURI aURI, in PRTime aVisitTime, in ACString aGUID ); Parameters aURI The URI of the page whose visits have been expired. aVisitTime The largest visit time in microseconds that has been expired. We guarantee that we do not have any visit older than this date. aGUID The unique ID associated with the page. onEndUpdateBatch() Called once a batch of updates is
completed. Once this has been called, you can perform processing, user interface updates, and so forth. This is called sometime after onBeginUpdateBatch(). void onEndUpdateBatch(); Parameters None. onPageChanged() Some attribute on the specified page has changed. Note that for TYPED and HIDDEN pages, the page might not actually have been added yet. This needs to be clarified; what are TYPED and HIDDEN? v...
nsINavHistoryResultObserver
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 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...
nsINavHistoryService
owing 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 auto
complete 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 auto
complete. This will cause the transition type of the next visit of the URL to be marked as "typed." void markPageAsTyped( in nsIURI aURI ); Parameters aU...
nsIPrefService
fBranch - 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 preference data is writte...
nsIPrivateBrowsingService
netwerk/base/public/nsIPrivateBrowsingService.idlScriptable Provides access to information about the state of the private browsing service. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This interface is deprecated since Firefox 20, and will probably be
completely removed in Firefox 21. The nsIPrivateBrowsingService interface provides access to information about the state of the private browsing feature offered in Firefox 3.5 and later. When Firefox is in private browsing mode, Firefox shouldn't save any potentially private information. The browser itself stops caching, and also doesn't record history information. In addition, temporary, databases are created to be used ...
nsIProtocolProxyService
onsumer 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 aCallback ); Parameters aURI The URI to test. aFlags A bit-wise combination of the RESOLVE_ flags defined above. Pass 0 to specify the default behavior. Any additional bits that do not c...
nsIRequestObserver
request. This call is always preceded by a call to onStartRequest(). ...
nsISupports proxies
is is the old install.js scripts that were used in XPInstall in older Mozilla versions. They from the majority of JavaScript code, which is small and can be quickly run. XPInstall installation scripts are sometimes very complex and can require long execution time due to unzipping or native file system actions. If XPInstall ran on the UI thread, the product would appear frozen until the script was
complete. This is definitely bad. Because of this, XPInstall was moved to its own thread. Now XPInstall can do its installations while the product renders, but now XPInstall can not access UI elements such as a progress meter or a confirmation dialog. How can a separate non-UI thread act as if it was on the UI thread? Herein lays the utility of nsISupports Proxies. I believe that other people working on ...
nsITaskbarProgress
ISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview void setProgressState(in nsTaskbarProgressState state, in unsigned long long currentValue Optional, in unsigned long long maxValue Optional); Constants Constant Value Description STATE_NO_PROGRESS 0 Stop displaying progress on the taskbar button. This should be used when the operation is
complete or canceled. STATE_INDETERMINATE 1 Display a cycling, indeterminate progress bar. STATE_NORMAL 2 Display a determinate, normal progress bar. STATE_ERROR 3 Display a determinate, error progress bar. STATE_PAUSED 4 Display a determinate progress bar indicating that the operation has paused. Methods setProgressState() Sets the taskbar progress state and value for this window. The currentV...
nsITextInputProcessor
m ASCII character which is inputted with a far simpler modifier state. See "Printable keys in standard position" section of KeyboardEvent.keyCode for the strict rules of Gecko. When you dispatch non-printable key events, preferred keyCode value is computed from key value automatically if you don't initialize this value. But the computation doesn't emulate the mapping of native key event handling
completely because it has some special cases depending on platform or selected keyboard layout. Therefore, if you need to emulate PC keyboard on specific platform, you may need to specify this explicitly. location Optional. It's not recommended to specify this explicitly since this value should be linked with code attribute value. The automatic computation can compute the best value for this. repeat O...
nsITimer
unsigned long Defines the timer type: one shot, repeating slack or repeating precise. Must be one of the constants defined under Constants on this page. Constants Constant Value Description TYPE_ONE_SHOT 0 Type of a timer that fires once only. TYPE_REPEATING_SLACK 1 After firing, the timer is stopped and not restarted until its callback
completes. The timer period will ideally be at least the time between when processing for last firing the callback
completes and when the next firing occurs, but note that this is not guaranteed: the timer can fire at any time. This is the preferable repeating type for most situations. TYPE_REPEATING_PRECISE 2 TYPE_REPEATING_PRECISE is just a synonym for TYPE_REPEATING_PRECISE_CAN_...
nsITreeBoxObject
owIndex. Inform the tree about this change by calling rowCountChanged(rowIndex+1, -1); beginUpdateBatch() Notify the tree that the view is about to perform a batch update, that is, add, remove or invalidate several rows at once. This must be followed by calling endUpdateBatch(), otherwise the tree will get out of sync. void beginUpdateBatch(); endUpdateBatch() Notify the tree that the view has
completed a batch update. void endUpdateBatch(); clearStyleAndImageCaches() Called on a theme switch to flush out the tree's style and image caches. void clearStyleAndImageCaches(); Other references Tree Widget Changes (applies to Gecko 1.8.0 and later) XUL Tutorial:Tree Box Sorting and filtering a custom tree view XUL Tutorial:Tree View Details nsITreeView ...
nsIURIFixup
IText, in unsigned long aFixupFlags); nsIURI keywordToURI(in AUTF8String aKeyword); nsIURIFixupInfo getFixupURIInfo(in AUTF8String aURIText, in unsigned long aFixupFlags); Constants Constant Value Description FIXUP_FLAG_NONE 0 No fixup flags. FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP 1 Allow the fixup to use a keyword lookup service to
complete the URI. The fixup object implementer should honour this flag and only perform any lengthy keyword (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. ...
nsIUpdatePatch
upt. selected boolean true if this patch is currently selected as the patch to be downloaded and installed for this update transaction. false if another update is selected. size unsigned long The size of the patch file in bytes. state AString The state of this patch. type AString The type of patch represented by the object: "partial" A binary difference between two application versions. "
complete" A
complete patch containing all the replacement files to update to the new version. URL AString The URL from which the patch was downloaded. Methods serialize() Serializes the patch object into a DOM element. nsIDOMElement serialize( in nsIDOMDocument updates ); Parameters updates The DOM document into which to serialize the patch. Return value The patch object serialized into an nsI...
nsIWebProgressListener2
SelfProgress, 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-bit values. Note: If any progress value is unknown, then its value is replaced with -1. void onProgressChange64( in nsIWebProgress aWebProgress, in nsIRequest aRequest, ...
nsIWebSocketChannel
le resolving a resource: URI to a file: URI) so that the original pre-redirect URI can still be obtained. This is never null. Read only. protocol ACString Sec-Websocket-Protocol value. securityInfo nsISupports Transport-level security information (if any). Read only. URI nsIURI The URI corresponding to the protocol connection after any redirections are
completed. Read only. Status codes The following values are permitted status codes. Status code Name Description 0-999 Reserved and not used. 1000 CLOSE_NORMAL Normal closure; the connection successfully
completed whatever purpose for which it was created. 1001 CLOSE_GOING_AWAY The endpoint is going away, either because of a server failur...
nsIWebSocketListener
t() Called to signify the establishment of the message stream. Any listener that receives onStart() will also receive OnStop(). void onStart( in nsISupports aContext ); Parameters aContext User defined context. onStop() Called to signify the completion of the message stream. This is the final notification the listener will receive; once it's been received, the WebSocket connection is
complete. This event can be received in error cases even if nsIWebSocketChannel.close() has not been called. void onStop( in nsISupports aContext, in nsresult aStatusCode ); Parameters aContext User defined context. aStatusCode Reason for stopping (NS_OK if
completed successfully). See also WebSockets nsIWebSocketChannel ...
nsIXMLHttpRequestEventTarget
oduced Gecko 1.9.1 Inherits from: nsIDOMEventTarget Last changed in Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2) Attributes Attribute Type Description onabort nsIDOMEventListener A JavaScript function object that gets invoked if the operation is canceled by the user. onerror nsIDOMEventListener A JavaScript function object that gets invoked if the operation fails to
complete due to an error. onload nsIDOMEventListener A JavaScript function object that gets invoked when the operation is successfully
completed. onloadend nsIDOMEventListener A JavaScript function object that gets invoked when the operation is
completed for any reason; it will always follow a an abort, error, or load event. onloadstart nsIDOMEventListener A JavaScript function object that gets inv...
nsIXPConnect
ither JSPROP_ENUMERATE or 0. interfaceCount The number of interfaces the class implements. interfaceArray The interfaces the class implements; interfaceArray and interfaceCount are like what nsIClassInfo.getInterfaces returns. Return value Missing Description Exceptions thrown Missing Exception Missing Description Native code only!evalInSandboxObject Evaluate script in a sandbox,
completely isolated from all other running scripts. jsval evalInSandboxObject( in AString source, in JSContextPtr cx, in nsIXPConnectJSObjectHolder sandbox, in PRBool returnStringOnly ); Parameters source The source of the script to evaluate. cx The context to use when setting up the evaluation of the script. The actual evaluation will happen on a new temporary context. sandbox The sand...
nsIAbCard/Thunderbird3
Documentation for the old nsIAbCard interface is currently at nsIAbCard. The nsIAbCard interface is used to represent and manipulate cards in the address book. In a big change from the original nsIAbCard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible. Properties currently supported on the card: Names: FirstName, LastName PhoneticFirstName, PhoneticLastName DisplayName, NickName SpouseName, FamilyName PrimaryEmail, SecondEmail Home Contact: HomeAddress, HomeAddress2, HomeCity, HomeState, HomeZipCode, HomeCountry HomePhone, HomePhoneType Work contact. ...
nsMsgMessageFlags
ndicates whether or not the thread rooted at this message is open or closed in the UI. Offline 0x00000080 Indicates whether or not we have this message in the offline cache. Watched 0x00000100 Indicates whether or not this thread is being watched. SenderAuthed 0x00000200 Partial 0x00000400 Indicates whether or not the body we have is a
complete message. Queued 0x00000800 Indicates whether or not the message is queued to be delivered. Forwarded 0x00001000 Indicates whether or not the message has been forwarded. Priorities 0x0000E000 The set of bits that indicate the priority. New 0x00010000 Indicates whether or not the message is new since the last time the folder was opened. ...
Storage
tore 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 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. No Results to be Retu...
Getting Started Guide
ed to be owning references. In fact, if two objects somehow end up owning each other (even transitively) it becomes difficult for either of those object to be reclaimed without adding some `out-of-band' mechanism for breaking the ownership cycle. The document Some COM Ownership Guidelines provides some hints on when ownership is needed. The following lists are good starting point, but by no means
complete. You use an owning reference when you created the object; you got the object from a function that might have created it, e.g., any `getter' function, such as QueryInterface, or CreateInstance. All good getters AddRef the interface pointers they produce, thus providing you with an owning reference; you will hold onto the reference longer than the scope of the function in which you acquired i...
Reference Manual
This section will help you if you're already familiar with nsCOMPtr but you need details. If you've never use nsCOMPtrs before, you might want to read the Getting Started Guide first. If you're trying to fix a broken build, the FAQ might lead you to the answer more quickly. The Basics Design An nsCOMPtr is designed to be a
complete replacement for raw XPCOM interface pointers where they are used as owning references. Almost any place you could use a raw XPCOM interface pointer, you should be able to use an nsCOMPtr. An nsCOMPtr is the exact same size and shape as a raw XPCOM interface pointer. It can be used as a member variable without introducing bloat. Most of the work of being an owning reference can be done in the constructor, destructor, and assignment operators of nsCOMPtr. Whenever...
Using the clipboard
Normally, the text would be in a document or textbox. The code is put together below, with additional error checking: var copytext = "Text to copy"; var trans = Transferable(sourceWindow); trans.addDataFlavor("text/unicode"); trans.setTransferData("text/unicode", SupportsString(copytext), copytext.length * 2); Services.clipboard.setData(trans, null, Services.clipboard.kGlobalClipboard); The
complete function shown below copies some text to the clipboard as HTML, as well as making it a clickable Hyperlink. So we've added a text flavor and an HTML flavor of the content. The Transferable object will hold both flavors. function copyLinkToClipboard(copyURL, copyLabel, sourceWindow) { // generate the Unicode and HTML versions of the Link var textUnicode = copyURL; var textHtml = copyL...
XPCOM
assInfoIf 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 referent object is destroyed before the weak reference, the pointer inside the weak referen...
XPIDL
bidden unless the method is notxpcom and it is used as an inparameter. For types that reference heap-allocated data (strings, arrays, interface pointers, etc), you must follow the XPIDL data ownership conventions in order to avoid memory corruption and security vulnerabilities: For in parameters, the caller allocates and deallocates all data. If the callee needs to use the data after the call
completes, it must make a private copy of the data, or, in the case of interface pointers, AddRef it. For out parameters, the callee creates the data, and transfers ownership to the caller. For buffers, the callee allocates the buffer with NS_Alloc, and the caller frees the buffer with NS_Free. For interface pointers, the callee does the AddRef on behalf of the caller, and the caller must call Release. ...
Xray vision
andard properties, stays in the JavaScript reflection and does not affect the C++ representation. The dual representation enables an elegant implementation of Xrays: the Xray just directly accesses the C++ representation of the original object, and doesn't go to the content's JavaScript reflection at all. Instead of filtering out modifications made by content, the Xray short-circuits the content
completely. This also makes the semantics of Xrays for DOM objects clear: they are the same as the DOM specification, since that is defined using the WebIDL, and the WebIDL also defines the C++ representation. Xrays for JavaScript objects Until recently, built-in JavaScript objects that are not part of the DOM, such as Date, Error, and Object, did not get Xray vision when accessed by more-privileged co...
Mozilla technologies
ated PNG graphicsAPNG is an extension of the Portable Network Graphics (PNG) format, adding support for animated images. APNG is a simpler alternative to MNG, providing a spec suitable for the most common usage of animated images on the Internet.DocShellDocshell is the second iteration of what originally started out as WebShell. ...
LDAP Support
address books and LDAP directories. For large companies, there may be a large number of users in the directory with the same name. In such a scenario, it may be hard to tell which person you really want to send the message to. In Thunderbird, the type down window can be customized to show arbitrary LDAP fields. This can be accomplished by setting the following preferences: user_pref("mail.auto
Complete.commentColumn", 2); user_pref("ldap_2.servers.DIRECTORYNAME.auto
Complete.commentFormat", "[ou]"); The first preference tells us to use a comment column in the type down (the default value is 0 for no comment), and that the value for the comment is a custom string unique to each directory. The commentFormat preference is set on EACH directory. It acts as a template, specifying the extra LDAP a...
Mailnews and Mail code review requirements
the in-testsuite+ flag should be set on the bug. Unit tests must be included in patches and reviewed just like any other code. If an automated test framework is needed but is not yet available, the developer is encouraged to write appropriate test code and commit it. A bug should be filed on the needed test framework. The in-testsuite? flag should be set on the bug until the framework has been
completed and the test code is running automatically. Certain build-config or tooling bugs which don't affect the actual product cannot be usefully tested. These bugs should have the in-testsuite- flag set. Rubber-Stamp Approvals for Intermittently Failing ("Orange") Test Fixes/Debugging In order to make it easier to debug and fix tests that fail intermittently ("intermittent orange" tests), we have c...
Adding items to the Folder Pane
add these newly defined folder-tree-items to the Folder Pane's _rowMap at the appropriate time. Thus, our _insert function becomes _insert: function gne__insert() { // Only insert our nodes into the "all" mode if (gFolderTreeView.mode != "all") return; gFolderTreeView._rowMap.push(containerRow); }, Right now, clicking on these additional items has no effect. However, the
complete example file includes code to display the number selected in Thunderbird's main viewing pane, when such a number is selected in the Folder Pane. A note about the initial rebuild When Thunderbird first starts up, the Folder Pane does an initial rebuild to get the first data it should display. Unfortunately, this rebuild will occur before an extension's "load" event fires. Thus, extensions may ne...
Building a Thunderbird extension 1: introduction
ilable that help with developing Thunderbird extensions. At a minimum you will need: Text editor: Any editor that is capable of writing plain text can be used to write extensions. However, most developers use an editing program optimized for writing code (also known as an Integrated Development Environment). These provide features like syntax highlighting and code coloration, indentation, auto-
complete, etc. File archive utility: Any utility that is capable of creating archive files can be used. There are also a number of extension and applications that are useful for testing and debugging Thunderbird extensions, such as JavaScript consoles and XPCOM inspectors. These are described on the page "Setting up an extension development environment". Documentation Thunderbird extensions (docume...
Access Window
Since window is a global variable you can use it directly from your JavaScript file. ...
Using Mozilla code in other projects
refox but are available for use by other applications; an example of this is Rhino, the JavaScript engine written in Java. You can embed Gecko, the layout engine used by Firefox to process web pages, as a browser within your own application. Building XUL applications The Joy of XUL An introduction to XUL; a must read for new developers. XUL Reference The
complete reference to XUL. XULRunner A Mozilla runtime package that can be used to bootstrap XUL and XPCOM applications with ease. Mozilla Toolkit Information about the Mozilla Toolkit API. Signing Mozilla apps for Mac OS X How to code-sign applications based on Mozilla code for Mac OS X's application security model. Using Mozilla components Spider...
Debugging Tips
let { ctypes } = Components.utils.import("resource://gre/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i.constructor.toSource()); let Point = ctypes.StructType("Point", [{ x: ctypes.int32_t }, { y: ctypes.int32_t }]) let p = Point(10, 20); console.log(p.constructor.toSource()); let pp = p.add...
Declaring and Calling Functions
ypes.unsigned_long); console.log("Clocks since startup: " + clock()); The clock() function requires no input parameters; it simply returns an unsigned long. Example: Multiple input parameters This example declares the libc asctime() function, which converts a time structure into a string. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); For a more
complete version of this example (including the implementation of the struct_tm type), see the structures example. Returned values If the return type can fit into a JavaScript number without loss (that is, it's a number 32 bits or smaller, or is a double or float), then the function just return a JavaScript number. For everything else it returns a ctypes object representing the return value (including 6...
Working with data
s and returns a new 64-bit integer. For example: var num = ctypes.Int64.join(-0x12345678, 0x90ABCDEF); Performing arithmetic with 64-bit values The Int64 and UInt64 objects don't provide any methods for performing arithmetic, which means you'll have to do it yourself by pulling out the high and low 32-bit portions and doing math on them, then joining them back together if necessary to get the
complete result. You'll also have to handle carry from the low to high word and back as appropriate. For example, adding two 64-bit integers can be done like this. This example is for unsigned numbers, but a similar approach can be taken for signed values. function add(a, b) { const MAX_INT = Math.pow(2, 32); var alo = ctypes.UInt64.lo(a); var ahi = ctypes.UInt64.hi(a); var blo = ctypes.UInt64.
StructType
t a string, or one or more of the fields does not have a defined size. RangeError The size of the structure, in bytes, cannot be represented both as a size_t and as a JavaScript Number. Describing fields The fields array is comprised of field descriptors, one for each field in the structure. Each field descriptor contains the field's name and its type, such as {'serialNumber': ctypes.int}. A
complete field descriptor list might look like this: [ {'serialNumber': ctypes.int}, {'userName': ctypes.char.ptr} ] Properties Property Type Description fields CType[] A sealed array of field descriptors. Read only. Properties inherited from CType These properties are available on all CType objects. Property Type Description name Strin...
PKCS #11 Netscape Trust Objects - Network Security Services
d as a certificate authority trust root, and confers its trust to other certificates. Certificate Reference Each trust object contains a reference to a certificate. There are two ways to refer to a certificate depending on whether that certificate is self-signed (like a certificate authority) or signed by another trusted certificate. Certificates used as a root of trust are referred to by the
complete hash of the DER value of the certificate. Certificates in a trust chain whose issuer is trusted are referred to by the DER value of the issuer field, and the serial number. PKCS#11 Representation Trust objects are stored as objects on a PKCS#11 token. Although these are specific to a certificate, they do not need to be stored on the same token as the certificate. Trust objects are of the class ...
Constants - Plugins
ARAM 9 Parameter missing or invalid. NPERR_INVALID_URL 10 URL missing or invalid. NPERR_FILE_NOT_FOUND 11 File missing or invalid. NPERR_NO_DATA 12 Stream contains no data. NPERR_STREAM_NOT_SEEKABLE 13 Seekable stream expected. Result Codes Constant Value Description NPRES_DONE 0 (Most common):
Completed normally; all data was sent to the instance. NPRES_NETWORK_ERR 1 Stream failed due to problems with network, disk I/O, lack of memory, or other problems. NPRES_USER_BREAK 2 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. Plug-in Version Const...
Initialization and Destruction - Plugins
ls from the browser to the plug-in. This table is filled out by the plug-in during the initialization call. The function tables also contain version information that the plug-in checks to verify that it is compatible with the API capabilities provided by the application. To check this information, use NPN_Version. No plug-in API calls can take place in either direction until the initialization
completes successfully, with the exception of the functions NP_Initialize and NP_Shutdown, which are not in the function tables. However, because NP_Initialize is called at the end of the initialization process, you can call other methods, such as NPN_MemAlloc and NPN_Status, from NP_Initialize. Instance Creation After initialization, the plug-in instance is created. More than one instance of the same p...
Plug-in Development Overview - Plugins
post form data to CGI scripts using HTTP, or upload files to a remote server using FTP. Use NPN_GetURL to request the browser to load a URL into a particular browser window or frame for display, or to deliver the data of that URL to the plug-in instance in a new stream. The NPN_GetURLNotify function operates like NPN_GetURL, except that it notifies the plug-in of the result when the operation
completes. Use NPN_PostURL to send data to a URL from a memory buffer or file. The result from the server can also be sent to a particular browser window or frame for display, or delivered 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 me...
Version, UI, and Status Information - Plugins
d check on the current version of the Plug-in API and the browser. Displaying a Status Line Message Users are accustomed to checking the UI status line at the bottom of the browser window for updates on the progress of an operation or the URL of a link on the page. You can also use the status line to notify the user of plug-in-related information. The user might appreciate seeing the percentage
completed of the current operation or the URL of a button or other link object when the cursor is over it, all of which the browser shows. In fact, your plug-in interface should be consistent with the rest of the browser in this way. To accomplish this, the plug-in calls the NPN_Status method to display your message on the status line. void NPN_Status(NPP instance, const char *message); The instance p...
Plugin Roadmap for Firefox - Plugins
a will maintain a list of sites which cannot use any plugins. September 2017 Starting with Firefox 56 in September 2017, Firefox for Android will remove all support for plugins (bug 1381916). 2019 In September 2019, Firefox 69 will remove the "Always Activate" Flash option so we always ask for user permission before activating Flash on a website. 2020 In December 2020, Flash support will be
completely removed from consumer versions of Firefox. Adobe will stop shipping security updates for Flash at the end of 2020. See Also Mozilla Firefox October 2015 - NPAPI Plugins in Firefox July 2016 - Reducing Adobe Flash Usage in Firefox July 2017 - Firefox Roadmap for Flash End-of-Life Adobe Flash November 2015 - Flash, HTML5 and Open Web Standards July 2017 - Flash & the Future of Inter...
Color vision simulation - Firefox Developer Tools
Configuration Editor, make sure the gfx.webrender.all option is set to true. In the Simulate menu, you can choose one option at a time from the following list: None -- choose this to return to normal display Protanomaly (low red) Deuteranomaly (low green) Tritanomaly (low blue) Protanopia (no red) Deuteranopia (no green) Tritanopia (no blue) Contrast loss These simulations are not
completely medically accurate. However, they can give you a sense of what your web site looks like to users with vision problems, and therefore help you judge whether you need to make adjustments in your color or contrast choices. The following table shows a colorful image of a cat's face, and what it looks like in the various simulations. Simulation Image displayed None ...
Accessibility Inspector - Firefox Developer Tools
Check for all types of issues Contrast -- Check for issues with visual contrast Keyboard -- Check for issues with navigating via a keyboard Text Labels -- Check for issues with missing text labels When you one of the menu items, Firefox scans your document for the type of issues you selected. Depending on the size and complexity of your document, this may take a few seconds. When the scan is
complete, the left side of the Accessibility Inspector panel displays only the items that have that type of issue. In the right side of the panel, the Checks subpanel lists the specific issue with the selected node. For each type of issue, there is a Learn more link to further information on MDN Web Docs about the issue. The menu items act as toggles. Select the item to view that type of issue; select ...
DOM Inspector internals - Firefox Developer Tools
viewer's popup overlay (resources/content/viewers/dom/popupOverlay.xul). The same is true for the Find menuitems and the "Select Element By Click" menuitem in the Edit menu, since no other viewers besides the DOM Nodes viewer support these features. The other Edit menu items are also used in several viewers' context menus. For that reason, only those menuitems' ids are referenced here, and the
complete definitions are imported from editingOverlay.xul. Viewers which include one or more of these menuitems in their context menus follow the same practice. The tooltip used for the Inspect menus--the one used to show a document's title (if any) and its URI for a given menuitem--is also defined here. commandOverlay.xul The popupOverlay.xul-provided menuitems that delegate to external command ele...
Introduction to DOM Inspector - Firefox Developer Tools
own application development that were missing. The DOM Inspector not only presents all this information about pages in a clear and structured way, it gives you way to find and update those structures, and it's simple to access via shortcuts and menus already available in the Mozilla browser. Used in concert with Mozilla tools like Venkman, the JavaScript debugger, the DOM Inspector can give you a
complete view of any web page or DOM-based application interface. ...
Browser Console - Firefox Developer Tools
Console command line is disabled by default. To enable it set the devtools.chrome.enabled preference to true in about:config, or set the "Enable chrome debugging" option in the developer tool settings. Like the Web Console, the command line interpreter enables you to evaluate JavaScript expressions in real time:Also like the Web Console's command line interpreter, this command line supports auto
complete, history, and various keyboard shortcuts and helper commands. If the result of a command is an object, you can click on the object to see its details. But while the Web Console executes code in the scope of the content window it's attached to, the browser console executes code in the scope of the chrome window of the browser. You can confirm this by evaluating window: This means you can contr...
Set a breakpoint - Firefox Developer Tools
een set, you can unset it again in various ways: Click on the line number highlight. Highlight the line of code the breakpoint is set on and pressing Ctrl + B (Windows/Linux) or Cmd + B (macOS). Bring up the context menu over the line highlight and choose the Remove Breakpoint option. Other context menu options worth mentioning are: Disable Breakpoint: turn it off, but don't remove it
completely. Disable breakpoints on line and Remove breakpoints on line: Remove or disable column breakpoints. If the breakpoint is an unconditional breakpoint, you'll get an option Add condition, which allows you to turn it into a conditional breakpoint. If the breakpoint is a conditional breakpoint, you'll get an option Edit condition, which allows you to change the previously set condition. Inline ...
Index - Firefox Developer Tools
te an audio context. Within that context they then construct a number of audio nodes, including: 146 Web Console Debugging, Guide, Security, Tools, Web Development, Web Development:Tools, l10n:priority, web console The Web Console: 147 Console messages Most of the Web Console is occupied by the message display pane: 148 Invoke getters from auto
complete No summary! 149 Rich output When the Web console prints objects, it includes a richer set of information than just the object's name. In particular, it: 150 Split console You can use the console alongside other tools. While you're in another tool in the Toolbox, just press Esc or select the "Show split console" command in the Toolbar menu. Th...
Network request details - Firefox Developer Tools
t with the request or response: As with headers, you can filter the list of cookies displayed. The full list of cookie attributes is shown--see the following screenshot showing Response cookies with further attributes shown. The samesite attribute has been shown since Firefox 62 (bug 1452715). Params tab This tab displays the GET parameters and POST data of a request: Response tab The
complete content of the response. If the response is HTML, JS, or CSS, it will be shown as text: If the response is JSON, it will be shown as an inspectable object: If the response is an image, the tab displays a preview: For network responses that are initiated by a WebSocket connection, the details pane shows any associated messages. For more information, see Inspecting web sockets. Cache tab ...
Network request list - Firefox Developer Tools
ookie-name:_ga set-cookie-value Shows the resources that have a Set-Cookie header with a value that matches the specified value. set-cookie-value:true regexp Shows the resources having a URL that matches the given regular expression. regexp:\d{5} regexp:mdn|mozilla For example, to find all 404, not found, errors, you can type "404" into the search and auto-
complete suggests "status-code:404" so you'll end up with something like this: Search in requests Use the Search panel to run a full-text search on headers and content. Click the Search icon in the toolbar. This opens the Search sidebar. Enter a string in the search field of the sidebar, and press Enter or Return. The search results area below the search field displays the requests that contain...
Edit fonts - Firefox Developer Tools
and Firefox 63 features support for editing the properties of variable fonts in the Font Editor. What are variable fonts? Variable Fonts, or OpenType Font Variations, define a new font file format that allows the font designer to include multiple variations of a typeface inside a single font file. That means you no longer have to apply several different web fonts to a single page to represent a
complete typeface for which a variable font is available, provided it includes the desired values for the different characteristics you want to vary. Variable fonts make it easy to vary font characteristics in a much more granular fashion because their allowable ranges are defined by axes of variation (see Introducing the 'variation axis' for more information). For example, font-weight can be set to any ...
Page inspector keyboard shortcuts - Firefox Developer Tools
Esc Step forward through properties and values Tab Tab Tab Step backward through properties and values Shift + Tab Shift + Tab Shift + Tab Start editing property or value (Rules view only, when a property or value is selected, but not already being edited) Enter or Space Return or Space Enter or Space Cycle up and down through auto-
complete suggestions (Rules view only, when a property or value is being edited) Up arrow , Down arrow Up arrow , Down arrow Up arrow , Down arrow Choose current auto-
complete suggestion (Rules view only, when a property or value is being edited) Enter or Tab Return or Tab Enter or Tab Increment selected value by 1 Up arrow Up arrow Up arrow Decrement ...
UI Tour - Firefox Developer Tools
ee Examine and edit the box model. Note that before Firefox 50, the box model view did not appear in the "Computed view" tab, but had its own tab. To learn more about the CSS declarations listed in this view, see Examine computed CSS. Changes view When you are editing in the Rules view, you can see the changes you have made in the Changes view. Computed view The Computed view shows you the
complete computed CSS for the selected element (The computed values are the same as what getComputedStyle would return.): Compatibility view Starting with Firefox Developer Edition version 77, the Compatibility view shows CSS compability issues, if any, for properties applied to the selected element, and for the current page as a whole. It shows icons for the browsers that do support the properties, a...
Allocations - Firefox Developer Tools
cation profile of a site and its responsiveness is the cost of garbage collection (GC). With a garbage-collected language, like JavaScript, the runtime periodically needs to walk the heap looking for objects that are no longer reachable, and then freeing the memory they occupy. While GC events like this are executing, the JavaScript engine must be paused, so your program is suspended and will be
completely unresponsive. To reduce the impact on responsiveness, SpiderMonkey (the JavaScript engine in Firefox) can perform GC in small increments, letting the program run in between. Sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish. GC events are shown as red markers in the Waterfall view, and are a big red flag for responsiveness, ...
Flame Chart - Firefox Developer Tools
distinguish. This gives you a way to know exactly which function was executing at any point during the recording, how long it ran for, and where it was called from. Zooming and panning To work effectively with the Flame Chart, you'll need to be able to navigate it. There are two main controls you can use to navigate the Flame Chart: Zoom: increase/decrease the selected portion of the
complete profile that's displayed in the Flame Chart 1) Mouse wheel up/down in the Flame Chart. 2) Trackpad 2 fingers up/down in the Flame Chart. Pan: move the selected portion of the
complete profile left and right 1) Click and drag the selected portion in the recording overview pane. 2) Click and drag anywhere in the Flame Chart. An example To see how...
Frame rate - Firefox Developer Tools
too low, an animation will have a jerky appearance, while a faster frame rate will be smoother. But frame rate is also useful as a general measure of a site's responsiveness as the user interacts with it. For example, if moving the mouse over some page element triggers some JavaScript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be
completed in that frame. If it takes too long for the browser to process the frame, then the browser will appear momentarily unresponsive (janky). Similarly, if scrolling through a page involves a lot of complex page updates and the browser can't keep up an acceptable frame rate, scrolling the page will appear sluggish or will occasionally freeze. In general, a high and consistent frame rate will make t...
Animating CSS properties - Firefox Developer Tools
peration is labeled "layout" but is also sometimes called "reflow". Paint: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition". This sequence needs to fit into a single frame, since the screen isn't updated until it is
complete. It's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. For a rate of 60 frames per second, that gives the browser 16.7 milliseconds to execute the
complete flow. CSS property cost In the context of the rendering waterfall, some properties are more expensive than others: Property type Cost Examples Properties that affect...
Intensive JavaScript - Firefox Developer Tools
SS calculations and possibly reflow: this is the CSS animation that's running throughout the profile. Then there are three solid blocks of orange, representing JavaScript execution, one for each time we pressed the button. The bottom half, which is correlated with the timeline summary in time, shows frame rate. We can see that frame rate is pretty healthy for most of the recording, but collapses
completely whenever we press the button. We can select one of these periods and have a closer look at it in the main Waterfall 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 sho...
Settings - Firefox Developer Tools
ists in Firefox Nightly. Style Editor Show original sources When a CSS preprocessor supporting source maps is used, this enables the Style Editor to display the original, preprocessor, sources rather than the generated CSS. Learn more about Style Editor support for CSS source maps. With this setting checked, the Page Inspector Rules view will also provide links to the original sources. Auto
complete CSS Enable the Style Editor to offer auto
complete suggestions. Screenshot Behavior Screenshot to clipboard When you click the icon for the Screenshot tool, copy the screenshot image to the clipboard (the image will still be saved to your Downloads directory). New in Firefox 53. Play camera shutter sound When you click the icon for the Screenshot tool, play a shutter sound. New in Firefox...
Style Editor - Firefox Developer Tools
n the sheet's entry in the style sheet pane. The editor provides line numbers and syntax highlighting to help make it easier to read your CSS. It also supports a number of keyboard shortcuts. The Style Editor automatically de-minimizes style sheets that it detects, without affecting the original. This makes it much easier to work on pages that have been optimized. The Style Editor supports auto
complete. Just start typing, and it will offer you a list of suggestions. You can switch auto
complete off in the Style Editor settings. The media sidebar The Style Editor displays a sidebar on the right-hand side whenever the current sheet contains any @media rules. The sidebar lists the rules and provides a link to the line of the sheet where the rule is defined. Click an item to jump to that rule in ...
Taking screenshots - Firefox Developer Tools
different device-pixel-ratio, set a delay before taking the screenshot, or specify your own file name, starting in Firefox 62 you can use the :screenshot helper function in the Web Console. Type :screenshot in the Web Console to create a screenshot of the current page. By default, the image file will be named Screen Shot yyy-mm-dd at hh.mm.ss.png. Tip: You could type :s and then hit Tab to auto
complete :screenshot. The command has the following optional parameters: Command Type Description --clipboard boolean When present, this parameter will cause the screenshot to be copied to the clipboard. Prevents saving to a file unless you use the --file option to force file writing. --delay number The number of seconds to delay before taking the screenshot...
Web Audio Editor - Firefox Developer Tools
buffer source nodes performing transformations such as delay and gain nodes representing the destination of the audio stream, such as the speakers Each node has zero or more AudioParam properties that configure its operation. For example, the GainNode has a single gain property, while the OscillatorNode has frequency and detune properties. The developer connects the nodes in a graph, and the
complete graph defines the behavior of the audio stream. The Web Audio Editor examines an audio context constructed in the page and provides a visualization of its graph. This gives you a high-level view of its operation, and enables you to ensure that all the nodes are connected in the way you expect. You can then examine and edit the AudioParam properties for each node in the graph. Some non-AudioParam...
Web Console UI Tour - Firefox Developer Tools
sn't clear on page reload, or new page load. Show Timestamps: When enabled, timestamps are shown on the left-hand side of each message row to say when the messages were logged. Group Similar Messages: When enabled, similar types of messages are grouped together, with an indicator of the number of occurrences. Enable Autocompletion: When enabled, the JavaScript interpreter attempts to auto
complete while you type. Instant Evaluation: When enabled, the interpreter displays the evaluated results of an expression, when possible, before you press Enter to submit it. Message display pane This is where the messages appear, both those generated by the code in the page, and those generated by the commands entered on the command line. See Console messages for a lot more detail on what th...
about:debugging (before Firefox 68) - Firefox Developer Tools
ts, such as background scripts parsing the manifest.json file again, so changes to permissions, content_scripts, browser_action or any other keys will take effect. Note that in Firefox 49 onwards, the Reload button is only enabled for temporary add-ons. It will be disabled for all other add-ons. Tabs In Firefox 49 onwards, a Tabs page is available in about:debugging -- this provides a
complete list of all the debuggable tabs open in the current Firefox instance. Each tab entry has a Debug button next to it -- when clicked, this will open up a toolbox specific to that tab, allowing you to debug that tab's contents. Note that this feature isn't that immediately useful to debugging desktop tabs -- you can open up a toolbox to debug a tab easily enough already -- but this will becom...
AbortController.abort() - Web APIs
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. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). ...
AbortController - Web APIs
Controller() 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. 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 ...
AddressErrors - Web APIs
ails = {}; if (!validCountries.includes(shippingAddress.country)) { ev.target.shippingOptions = []; shippingAddressErrors.country = invalidCountryError; updateDetails = { error: genericAddressError, shippingAddressErrors, ...defaultPaymentDetails }; } ev.updateWith(updateDetails); } See Handling address changes for a description of how this code works.
Complete example Here we'll see a
complete, working version of the example above (except of course that it's not connected to an actual payment handler, so no payments are actually processed). In the example, we're handling a donation to an organization that will be sending a "thank you" gift to the donor, so it requests shipping information along with allowing the donation payment itself. JavaScript P...
AnalyserNode.fftSize - Web APIs
ults to 2048. Note: If its value is not a power of 2, or it is outside the specified range, a DOMException with the name IndexSizeError is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 2048; var bufferLength = analyser.frequencyBinCount ; var dataArray = new Uint8Array(bufferLength); analyser.getByteTimeDomainData(dataArray...
AnalyserNode.frequencyBinCount - Web APIs
ed, 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 requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... analyser.fftSize = 256; var bufferLength = analyser.frequencyBinCount; console.log(bufferLength); var d...
AnalyserNode.getByteTimeDomainData() - Web APIs
he AnalyserNode.fftSize, excess elements are dropped. If it has more elements than needed, excess elements are ignored. Return value void | None Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); const analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 2048; const bufferLength = analyser.fftSize; const dataArray = new Uint8Array(bufferLength); analyser.getByteTimeDomainData(dataArray); ...
AnalyserNode.getFloatFrequencyData() - Web APIs
ith data returned from getFloatFrequencyData() analyser.getFloatFrequencyData(myDataArray); Drawing a spectrum The following example shows basic usage of an AudioContext to connect a MediaElementAudioSourceNode to an AnalyserNode. While the audio is playing, we collect the frequency data repeatedly with requestAnimationFrame() and draw a "winamp bargraph style" to a <canvas> element. For more
complete applied examples/information, check out our Voice-change-O-matic-float-data demo (see the source code too). <!doctype html> <body> <script> const audioCtx = new AudioContext(); //Create audio source //Here, we use an audio file, but this could also be e.g. microphone input const audioEle = new Audio(); audioEle.src = 'my-audio.mp3';//insert file name here audioEle.autoplay = true; audioEle.prel...
AnalyserNode.getFloatTimeDomainData() - Web APIs
nalyserNode.frequencyBinCount, excess elements are dropped. If it has more elements than needed, excess elements are ignored. Return value None. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic-float-data demo (see the source code too). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 1024; var bufferLength = analyser.fftSize; console.log(bufferLength); var dataArray = new Float32Array(bufferLength); canvasCtx.clearRect(0, 0, WID...
AnalyserNode.maxDecibels - Web APIs
urned as +1.0 or 255, respectively. Note: If a value less than or equal to AnalyserNode.minDecibels is set, an IndexSizeError exception is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... analyser.fftSize = 256; var bufferLength = analyser.frequencyBinCount; console.log(bufferLength); var d...
AnalyserNode.minDecibels - Web APIs
ill be returned as 0.0 or 0, respectively. Note: If a value greater than AnalyserNode.maxDecibels is set, an INDEX_SIZE_ERR exception is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... analyser.fftSize = 256; var bufferLength = analyser.frequencyBinCount; console.log(bufferLength); var d...
AnalyserNode.smoothingTimeConstant - Web APIs
er time. The default value is good enough for most cases. Note: If a value outside the range 0-1 is set, an INDEX_SIZE_ERR exception is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). If you 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.webkitAudioCont...
AnalyserNode - Web APIs
ray) passed into it. Examples Note: See the guide Visualizations with Web Audio API for more information on creating audio visualizations. Basic usage The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new(window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); // ... analyser.fftSize = 2048; var bufferLength = analyser.frequencyBinCount; var dataArray = new Uint8Array(bufferLength); analyser.getByteTimeDomainData(dataArray)...
Animation.finished - Web APIs
The Animation.finished read-only property of the Web Animations API returns a Promise which resolves once the animation has finished playing. Every time the animation leaves the finished play state (that is, when it starts playing again), a new Promise is created for this property. The new Promise will resolve once the new animation sequence has
completed. Syntax var animationsPromise = Animation.finished; Value A Promise object which will resolve once the animation has finished running. Examples The following code waits until all animations running on the element elem have finished, then deletes the element from the DOM tree: Promise.all( elem.getAnimations().map( function(animation) { return animation.finished } ) ).then( function() { return elem.remove(); ...
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. ...
Animation.playState - Web APIs
no pending tasks. running The animation is running. paused The animation was suspended and the Animation.currentTime property is not updating. finished The animation has reached one of its boundaries and the Animation.currentTime property is not updating. Previously, Web Animations defined a pending value to indicate that some asynchronous operation such as initiating playback was yet to
complete. This is now indicated by the separate Animation.pending property. Example In the Growing/Shrinking Alice Game example, players can get an ending with Alice crying into a pool of tears. In the game, for performance reasons, the tears should only be animating when they're visible. So they must be paused as soon as they are animated like so: // Setting up the tear animations tears.forEach(funct...
AnimationEvent.initAnimationEvent() - Web APIs
tionEvent. 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. animationend The animation
completed. animationiteration The current iteration just
completed. canBubbleArg A Boolean flag indicating if the event can bubble (true) or not (false). cancelableArg A Boolean flag indicating if the event associated action can be avoided (true) or not (false). animationNameArg A DOMString containing the value of the animation-name CSS property associated with the transit...
Attr - Web APIs
"#4D4E53" text-anchor="middle" alignment-baseline="middle">Attr</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Warning: Starting in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4), a number of deprecated properties and methods output warning messages to the console. You should revise your code accordingly. See Deprecated properties and methods for a
complete list. Properties name Read only The attribute's name. namespaceURI Read only A DOMString representing the namespace URI of the attribute, or null if there is no namespace. localName Read only A DOMString representing the local part of the qualified name of the attribute. prefix Read only A DOMString representing the namespace prefix of the attribute, or null if no prefix is specifi...
AudioBufferSourceNode.start() - Web APIs
e 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 Status Comment Web Audio APIThe definition of 'start()' in that specification. Working Draft ...
AudioContext.resume() - Web APIs
Return value A Promise that resolves when the context has resumed. The promise is rejected if the context has already been closed. ...
AudioDestinationNode.maxChannelCount - Web APIs
tination.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 definition of 'maxChannelCount' in that specification. Working Draft ...
AudioDestinationNode - Web APIs
ex set up for using an AudioDestinationNode -- by default, this simply represents the output of the user's system (e.g. their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioCtx = new AudioContext(); var source = audioCtx.createMediaElementSource(myMediaElement); source.connect(gainNode); 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 definition of 'AudioDestinationNode' in that specification. Working Draft ...
AudioListener.dopplerFactor - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.forwardX - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.forwardY - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.forwardZ - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.positionX - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.positionY - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.positionZ - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.setOrientation() - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.setPosition() - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.speedOfSound - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.upX - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.upY - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener.upZ - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioListener - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
AudioParam.setTargetAtTime() - Web APIs
wer the transition will be. Returns A reference to this AudioParam object. Some older browser implementations of this interface return void. Description The change starts at the time specified in startTime and exponentially moves towards the value given by the target parameter. The decay rate as defined by the timeConstant parameter is exponential; therefore the value will never reach target
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, ...
AudioWorklet - Web APIs
Worklet through the BaseAudioContext.audioWorklet property. Properties The AudioWorklet interface does not define any properties of its own, but does inherit properties of Worklet. Methods This interface inherits methods from Worklet. The AudioWorklet interface does not define any methods of its own. Events AudioWorklet has no events to which it responds. Examples See AudioWorkletNode for
complete examples of custom audio node creation. Specifications Specification Status Comment Web Audio APIThe definition of 'AudioWorklet' in that specification. Working Draft Initial definition. ...
AudioWorkletNode() - Web APIs
t can be used for custom initialization of the underlying AudioWorkletProcessor. Return value The newly constructed AudioWorkletNode instance. Exceptions NotSupportedError The specified options.outputChannelCount is 0 or larger than the current implementation supports. IndexSizeError The length of options.outputChannelCount array does not match options.numberOfOutputs. Example For a
complete example demonstrating user-defined audio processing, see the AudioWorkletNode page. Specifications Specification Status Comment Web Audio APIThe definition of 'AudioWorkletNode()' in that specification. Working Draft Initial definition. ...
Background Tasks API - Web APIs
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 and computations have been
completed. If you make changes that affect layout, you may force a situation in which the browser has to stop and do recalculations that would otherwise be unnecessary. If your callback needs to change the DOM, it should use Window.requestAnimationFrame() to schedule that. Avoid tasks whose run time can't be predicted. Your idle callback should avoid doing anything that could take an unpredictable amount...
BaseAudioContext.audioWorklet - Web APIs
The audioWorklet read-only property of the BaseAudioContext interface returns an instance of AudioWorklet that can be used for adding AudioWorkletProcessor-derived classes which implement custom audio processing. Syntax baseAudioContextInstance.audioWorklet; Value An AudioWorklet instance. Examples For a
complete example demonstrating user-defined audio processing, see the AudioWorkletNode page. Specifications Specification Status Comment Web Audio APIThe definition of 'audioWorklet' in that specification. Working Draft Initial definition. ...
BaseAudioContext.createAnalyser() - Web APIs
Note: For more on using this node, see the AnalyserNode page. Syntax var analyserNode = baseAudioContext.createAnalyser(); Returns An AnalyserNode. Example The following example shows basic usage of an AudioContext to create an Analyser node, then use requestAnimationFrame() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more
complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 2048; var bufferLength = analyser.frequencyBinCount; var dataArray = new Uint8Array(bufferLength); analyser.getByteTimeDomainData(dataArray)...
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). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); //set up the different audio nodes we will use for the app var analyser = audioCtx.createAnalyser(); var distortion = audioCtx.createWaveShaper(); var gainNode = audioCtx.createGain(); var biquadFilter = audioCtx.createBiquadFilter(); var convolver = audioCtx.
BaseAudioContext.createDynamicsCompressor() - Web APIs
ions 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 more
complete example, have a look at our basic Compressor example (view the source code). // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a compressor node var compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audio...
BaseAudioContext.createGain() - Web APIs
udio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's GainNode.gain a-rate parameter. 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. ...
BaseAudioContext.createPanner() - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
BaseAudioContext.decodeAudioData() - Web APIs
t Interface is used to asynchronously decode audio file data contained in an ArrayBuffer. 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. 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, WindowOrWorkerGlobalSco...
BaseAudioContext - Web APIs
source. BaseAudioContext.createWaveShaper() Creates a WaveShaperNode, which is used to implement non-linear distortion effects. BaseAudioContext.decodeAudioData() Asynchronously decodes audio file data contained in an ArrayBuffer. In this case, the ArrayBuffer is usually loaded from an XMLHttpRequest's response attribute after setting the responseType to arraybuffer. This method only works on
complete files, not fragments of audio files. Examples Basic audio context declaration: const audioContext = new AudioContext(); Cross browser variant: const AudioContext = window.AudioContext || window.webkitAudioContext; const audioContext = new AudioContext(); const oscillatorNode = audioContext.createOscillator(); const gainNode = audioContext.createGain(); const finish = audioContext.destinati...
BasicCardRequest - Web APIs
t dictionary is a JavaScript object-structure that can be used in the Payment Request API. The properties of BasicCardRequest are defined in the Basic Card Payment spec). Properties BasicCardRequest.supportedNetworks Optional Secure context An optional array of DOMStrings representing the card networks that the retailer supports (e.g. "amex", "mastercard"); see Card network identifiers for a
complete list. If the property is missing, it implies that all networks are supported. Obsolete properties These properties have been removed from the Payment Method: Basic Card specification and should no longer be used. BasicCardRequest.supportedTypes Optional Secure context This obsolete property was used to provide an optional array of DOMStrings representing the card types that the retailer ...
BatteryManager - Web APIs
ager.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. BatteryManager.dischargingTime Read only A number representing the remaining time in seconds until the battery is
completely discharged and the system will suspend. BatteryManager.level Read only A number representing the system's battery charge level scaled to a value between 0.0 and 1.0. Event handlers BatteryManager.onchargingchange A handler for the chargingchange event; This event is sent when the battery charging state is updated. BatteryManager.onchargingtimechange A handler for the chargingtimechan...
Beacon API - Web APIs
and makes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance. There are other techniques used to ensure that data is submitted. One such technique is to delay the unload to submit data by creating an Image element and setting its src attribute within the unload handler. As most user agents will delay the unload to
complete the pending image load, data can be submitted during the unload. Another technique is to create 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 provid...
BiquadFilterNode.Q - Web APIs
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. 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.webkitAudioContext)(); //set up the different audio nodes we will use for the app var analyser = audioCtx.createAnalyser(); var distortion = audioCtx.createWaveShaper(); var gainNode = audioCtx.createGain(); var biquadFilter = audioCtx.createBiquadFilter(); v...
BiquadFilterNode.detune - Web APIs
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). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); //set up the different audio nodes we will use for the app var analyser = audioCtx.createAnalyser(); var distortion = audioCtx.createWaveShaper(); var gainNode = audioCtx.createGain(); var biquadFilter = audioCtx.createBiquadFilter(); v...
BiquadFilterNode.frequency - Web APIs
uist 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.webkitAudioContext)(); //set up the different audio nodes we will use for the app var analyser = audioCtx.createAnalyser(); var distortion = audioCtx.createWaveShaper(); var gainNode = audioCtx.createGain(); var biquadFilter = audioCtx.createBiquadFilter(); v...
BiquadFilterNode.gain - Web APIs
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 (window.AudioContext || window.webkitAudioContext)(); //set up the different audio nodes we will use for the app var analyser = audioCtx.createAnalyser(); var distortion = audioCtx.createWaveShaper(); var gainNode = audioCtx.createGain(); var biquadFilter = audioCtx.createBiquadFilter(); v...
BiquadFilterNode.type - Web APIs
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 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.webkitAudioContext)(); //set up the different audio nodes we will use for the app var analyser = audioCtx.createAnalyser(); var distortion = audioCtx.createWaveShaper(); var gainNode = audioCtx.createGain(); var biquadFilter = audioCtx.createBiquadFilter(); v...
BiquadFilterNode - Web APIs
ition 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 || window.webkitAudioContext)(); //set up the different audio nodes we will use for the app var analyser = audioCtx.createAnalyser(); var distortion = audioCtx.createWaveShaper(); var gainNode = audioCtx.createGain(); var biquadFilter = audioCtx.createBiquadFilter(); v...
CSSKeyframesRule - Web APIs
It corresponds to the contents of a whole @keyframes at-rule. It implements the CSSRule interface with a type value of 7 (CSSRule.KEYFRAMES_RULE). Properties As a CSSRule, CSSKeyframesRule also implements the properties 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. ...
CSSRule - Web APIs
ialized interface it implements). The relationships between these constants and the interfaces are: Type Value Rule-specific interface Comments and examples CSSRule.STYLE_RULE 1 CSSStyleRule The most common kind of rule: selector { prop1: val1; prop2: val2; } CSSRule.IMPORT_RULE 3 CSSImportRule An @import rule. ...
CSSStyleSheet - Web APIs
atically by the browser, when a stylesheet is loaded for a document. As the stylesheet list cannot be modified directly, there's no useful way to create a new CSSStyleSheet object manually (although Constructable Stylesheet Objects is coming to the web platform soon and is already supported in Blink). To create a new stylesheet, insert a <style> or <link> element into the document. A (possibly in
complete) list of ways a stylesheet can be associated with a document follows: Reason for the style sheet to be associated with the document Appears in document. styleSheets list Getting the owner element/rule given the style sheet object The interface for the owner object Getting the CSSStyleSheet object from the owner <style> and <link> elements in the document ...
CanvasRenderingContext2D.arc() - Web APIs
ive. 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. anticlockwise Optional An optional Boolean. If true, draws the arc counter-clockwise between the start and end angles. The default is false (clockwise). Examples Drawing a full circle 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 * Ma...
CanvasRenderingContext2D.drawImage() - Web APIs
the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in height when drawn. Exceptions thrown INDEX_SIZE_ERR If the canvas or source rectangle width or height is zero. INVALID_STATE_ERR The image has no image data. TYPE_MISMATCH_ERR The specified source element isn't supported. NS_ERROR_NOT_AVAILABLE The image is not loaded yet. Use .
complete === true and .onload to determine when it is ready. Examples Drawing an image to the canvas This example draws an image to the canvas using the drawImage() method. HTML <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> JavaScript The source image is take...
CanvasRenderingContext2D.globalAlpha - Web APIs
set the globalAlpha property to 0.2 (20% opaque); this alpha level will apply to all of our transparent shapes. After that, we use a for loop to draw a series of circles with increasing radii. With each new circle, the opacity of the previous circles underneath is effectively increased. If we were to increase the step count (and thus draw more circles), the background would eventually disappear
completely from the center of the image. <canvas id="canvas" width="150" height="150"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Draw background ctx.fillStyle = '#FD0'; ctx.fillRect(0, 0, 75, 75); ctx.fillStyle = '#6C0'; ctx.fillRect(75, 0, 75, 75); ctx.fillStyle = '#09F'; ctx.fillRect(0, 75, 75, 75); ctx.fillStyle = '#F30'; ctx.fillRect(75, 75...
CanvasRenderingContext2D.lineCap - Web APIs
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 "butt" option. It's drawn
completely flush with the guides. The second is set to use the "round" option. This adds a semicircle to the end that has a radius half 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. <canvas id="canvas" width="150" height="150"></canvas> const canvas = document.getElementById('canvas'); const ctx = c...
CanvasRenderingContext2D.shadowColor - Web APIs
This example strokes and fills a rectangle with translucent colors. HTML <canvas id="canvas"></canvas> JavaScript The resulting alpha value of the fill shadow is .8 * .2, or .16. The alpha of the stroke shadow is .8 * .6, or .48. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'rgba(255, 0, 0, .8)'; ctx.shad...
Basic animations - Web APIs
nce a shape gets drawn, it stays that way. If we need to move it we have to redraw it and everything that was drawn before it. It takes a lot of time to redraw 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 ...
Clipboard.write() - Web APIs
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. 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 t...
CloseEvent - Web APIs
ocket-internal and not for the same meaning by the transported data (like when the application-layer protocol is invalid). The only permitted codes to be specified in Firefox are 1000 and 3000 to 4999 [Source, Bug]. Status code Name Description 0-999 Reserved and not used. 1000 Normal Closure Normal closure; the connection successfully
completed whatever purpose for which it was created. 1001 Going Away The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection. 1002 Protocol Error The endpoint is terminating the connection due to a protocol error. 1003 Unsupported Data The connection is bein...
Console API - Web APIs
Concepts and usage The Console API started as a largely proprietary API, with different browsers implementing it, albeit it in inconsistent ways. The Console API spec was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior -- although some implementations still have their own additional proprietary functions. ...
ConstantSourceNode.offset - Web APIs
Value An AudioParam object indicating the a-rate value returned for every sample by this node. The default value is 1.0. To access the offset parameter's current value, access the parameter's value property, as shown in the syntax box above. Example This example shows how to set up a ConstantSourceNode so its offset is used as the input to a pair of GainNodes; this snippet is derived from the
complete example you can find in Controlling multiple parameters with ConstantSourcenode. gainNode2 = context.createGain(); gainNode3 = context.createGain(); gainNode2.gain.value = gainNode3.gain.value = 0.5; volumeSliderControl.value = gainNode2.gain.value; constantSource = context.createConstantSource(); constantSource.connect(gainNode2.gain); constantSource.connect(gainNode3.gain); First, the gain ...
Constraint validation API - Web APIs
validation can prevent many common kinds of invalid values, invalid ones can still be sent by older browsers or by attackers trying to trick your web application. Therefore, you need to also validate input values on the server side, in a way that is consistent with what is done on the client side. Client side validation is a tool for giving quick feedback to the user. You should not rely on it to
completely sanitize data received by the server. Validation of constraints through the constraint validation API is done either on a single form element or at the form level, on the <form> element itself. Constraint validation interfaces ValidityState The ValidityState interface represents the validity states that a form control element can have, with respect to its defined constraints. Together, t...
ConvolverNode - Web APIs
A boolean that controls whether the impulse response from the buffer will be scaled by an equal-power normalization 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. let audioCtx = new window.AudioContext(); async function createReverb() { let convolver = audioCtx.createConvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arrayBuffer(); convolver.buffer = await audioCtx.decodeAudioDa...
CredentialsContainer.get() - Web APIs
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 Specification Status Comment Credential Ma...
DOMException - Web APIs
the DOMException.name attribute. DOMException.message Read only Returns a DOMString representing a message or description associated with the given error name. DOMException.name Read only Returns a DOMString that contains one of the strings associated with an error name. Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a
complete list. Note: Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. IndexSizeError The index is not in the allowed range. For example, this can be thrown by the Range object. (Legacy code value: 1 and legacy co...
Document: animationend event - Web APIs
If the animation aborts before reaching completion, such as if the element is removed from the DOM or the animation is removed from the element, the animationend event is not fired. Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationend The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationend. ...
Document: animationiteration event - Web APIs
mationiteration The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationiteration. ...
Document.exitFullscreen() - Web APIs
oggle in and out of a full-screen presentation whenever the mouse button is clicked within it. document.onclick = function (event) { if (document.fullscreenElement) { document.exitFullscreen() .then(() => console.log("Document Exited form Full screen mode")) .catch((err) => console.error(err)) } else { document.documentElement.requestFullscreen(); } } Note: For a more
complete example, see the Example in Element.requestFullscreen(). Specifications Specification Status Comment Fullscreen APIThe definition of 'Document.exitFullscreen()' in that specification. Living Standard Initial definition ...
Document.getElementsByTagName() - Web APIs
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. ...
Document.getElementsByTagNameNS() - Web APIs
Syntax elements = document.getElementsByTagNameNS(namespace, name) elements is a live NodeList (but see the note below) of found elements in the order they appear in the tree. namespace is the namespace URI of elements to look for (see element.namespaceURI). name is either the local name of elements to look for or the special value *, which matches all elements (see element.localName). Note: While the W3C specification says elements is a NodeList, this method returns a HTMLCollection both in Gecko and Internet Explorer. ...
Document: transitionend event - Web APIs
In the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated. Bubbles Yes Cancelable Yes Interface TransitionEvent Event handler property ontransitionend The transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. ...
Introduction to the DOM - Web APIs
ElementsByTagName(name) document.createElement(name) parentNode.appendChild(node) element.innerHTML element.style.left element.setAttribute() element.getAttribute() element.addEventListener() window.content window.onload window.scrollTo() Testing the DOM API This document provides samples for every interface that you can use in your own web development. In some cases, the samples are
complete HTML pages, with the DOM access in a <script> element, the interface (e.g, buttons) necessary to fire up the script in a form, and the HTML elements upon which the DOM operates listed as well. When this is the case, you can cut and paste the example into a new HTML document, save it, and run the example from the browser. There are some cases, however, when the examples are more concise. To run e...
Using the W3C DOM Level 1 Core - Web APIs
How can I learn more? Now that you are familiar with the basic concepts of the DOM, you may want to learn about the DOM Level 1 fundamental methods. See also the DOM Level 1 Core specification from the W3C. It's a reasonably clear spec, although it is formal. The main thing that's useful to authors is the description of the different DOM objects and all their properties and methods. A...
DynamicsCompressorNode.attack - Web APIs
t 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 MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a compressor node var compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audio...
DynamicsCompressorNode.knee - Web APIs
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 the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a compressor node var compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audio...
DynamicsCompressorNode.ratio - Web APIs
an 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 source = audioCtx.createMediaElementSource(myAudio); // Create a compressor node var compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audio...
DynamicsCompressorNode.release - Web APIs
n 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 MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a compressor node var compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audio...
DynamicsCompressorNode.threshold - Web APIs
et 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 source = audioCtx.createMediaElementSource(myAudio); // Create a compressor node var compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audio...
DynamicsCompressorNode - Web APIs
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. 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 source = audioCtx.createMediaElementSource(myAudio); // Create a compressor node var compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audio...
EXT_color_buffer_float - Web APIs
f_float and WEBGL_color_buffer_float extensions. Extended methods The following sized formats become color-renderable: gl.R16F, gl.RG16F, gl.RGBA16F, gl.R32F, gl.RG32F, gl.RGBA32F, gl.R11F_G11F_B10F. Color-renderable means: The WebGLRenderingContext.renderbufferStorage() method now accepts these formats. Framebuffers with attached textures of these formats may now be FRAMEBUFFER_
COMPLETE. Examples gl must be a WebGL2RenderingContext. This extension does not work in WebGL 1 contexts. var ext = gl.getExtension('EXT_color_buffer_float'); gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA16F, 256, 256); Specifications Specification Status Comment EXT_color_buffer_floatThe definition of 'EXT_color_buffer_float' in that specification. Recommendation I...
EffectTiming.duration - Web APIs
Element.animate(), KeyframeEffectReadOnly(), and KeyframeEffect() all accept an object of timing properties including duration. The value of duration corresponds directly to AnimationEffectTimingReadOnly.duration in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
Element.classList - Web APIs
r IE6-8, there is no way to create an immutable object (an object whose properties cannot be directly modified). In IE9, however, it is possible through extending the prototype, freezing the visible object, and overwritting native property methods. However, such actions would not work in IE6-IE8 and, in IE9, slow the performance of the entire webpage to a snail's crawl, making these modifications
completely impractical for this polyfill. A minor note is that in IE6-7, this polyfill uses the window[" uCL"] property on the window object for communicating with the CSS expressions, the x-uCLp css property on all elements, and the element[" uCL"] property on all elements to allow garbage collection and boost performance. In all polyfilled browsers (IE6-9), an additional element[" uCLp"] property is ad...
Element: click event - Web APIs
nstead of one that isn't typically interactive (e.g., <div>). Stop using click event delegation. Safari Mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug): <a> (but it must have an href) <area> (but it must have an href) <button> <img> <input> <label> (but it must be associated with a form control) <textarea> This list is in
complete; you can help MDN by doing further testing/research and expanding it. Examples This example displays the number of consecutive clicks on a <button>. HTML <button>Click</button> JavaScript const button = document.querySelector('button'); button.addEventListener('click', event => { button.innerHTML = `Click count: ${event.detail}`; }); Result Try making rapid, repeated clicks on the but...
Element.getBoundingClientRect() - Web APIs
ed 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 all the element's border-boxes are empty, then a rectangle is returned with a width and height of zero and where the top and left are the top-left of the border-box for the first CSS box (in content order) for the element. The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle. Th...
Element.requestFullscreen() - Web APIs
that control the behavior of the transition to full-screen mode. Currently, the only option is navigationUI, which controls whether or not to show navigation UI while the element is in full-screen mode. The default value is "auto", which indicates that the browser should decide what to do. Return value A Promise which is resolved with a value of undefined when the transition to full screen is
complete. 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 ...
Element.scrollIntoView() - Web APIs
o 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 'Element.scrollIntoView()' in that specification. Working Draft Initial definition ...
Element - Web APIs
ilable via the oncopy property. cut Fired when the user initiates a cut action through the browser's user interface. Also available via the oncut property. paste Fired when the user initiates a paste action through the browser's user interface. Also available via the onpaste property. Composition events compositionend Fired when a text composition system such as an input method editor
completes or cancels the current composition session. compositionstart Fired when a text composition system such as an input method editor starts a new composition session. compositionupdate Fired when a new character is received in the context of a text composition session controlled by a text composition system such as an input method editor. Focus events blur Fired when an element has lost fo...
Event.eventPhase - Web APIs
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, starting with the parent, and eventually reaching the containing Window. This is known as bubbling, and occurs only if Event.bubbles is true. Event listeners registered for this phase are triggered during this process. For more details, see section 3.1, Event dispatch an...
EventTarget.addEventListener() - Web APIs
ignored) */) { var self=this; var wrapper=function(e) { e.target=e.srcElement; e.currentTarget=self; if (typeof listener.handleEvent != 'undefined') { listener.handleEvent(e); } else { listener.call(self,e); } }; if (type=="DOMContentLoaded") { var wrapper2=function(e) { if (document.readyState=="
complete") { wrapper(e); } }; document.attachEvent("onreadystatechange",wrapper2); eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2}); if (document.readyState=="
complete") { var e=new Event(); e.srcElement=window; wrapper2(e); } } else { this.attachEvent("on"+type,wrapper...
EventTarget.dispatchEvent() - Web APIs
Otherwise it returns true. The dispatchEvent() method throws UNSPECIFIED_EVENT_TYPE_ERR if the event's type was not specified by initializing the event before the method was called, or if the event's type is null or an empty string. Exceptions Exceptions thrown by event handlers are reported as uncaught exceptions. The event handlers run on a nested callstack; they block the caller until they
complete, but exceptions do not propagate to the caller. Notes Unlike "native" events, which are fired by the DOM and invoke event handlers asynchronously via the event loop, dispatchEvent() invokes event handlers synchronously. All applicable event handlers will execute and return before the code continues on after the call to dispatchEvent(). dispatchEvent() is the last step of the create-init-dispat...
Fetch basic concepts - Web APIs
, Headers, and Body payloads, along with a global fetch method for initiating asynchronous resource requests. Because the main components of HTTP are abstracted as JavaScript objects, it is easy for other APIs to make use of such functionality. Service 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. 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 s...
Fetch API - Web APIs
sts that may be affected by cookies/user login state. Note: Find out more about using the Fetch API features in Using Fetch, and study concepts in Fetch basic concepts. Aborting a fetch Browsers have started to add experimental support for the AbortController and AbortSignal interfaces (aka The Abort API), which allow operations like Fetch and XHR to be aborted if they have not already
completed. See the interface pages for more details. Fetch Interfaces WindowOrWorkerGlobalScope.fetch() The fetch() method used to fetch a resource. Headers Represents response/request headers, allowing you to query them and take different actions depending on the results. Request Represents a resource request. Response Represents the response to a request. Fetch mixin Body Provides metho...
Using files from web applications - Web APIs
ogresses the throbber will be updated based on the latest information. The XMLHttpRequest's upload load event handler is set to update the throbber progress information to 100% to ensure the progress indicator actually reaches 100% (in case of granularity quirks during the process). It then removes the throbber since it's no longer needed. This causes the throbber to disappear once the upload is
complete. The request to upload the image file is opened by calling XMLHttpRequest's open() method to start generating a POST request. The MIME type for the upload is set by calling the XMLHttpRequest function overrideMimeType(). In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all depending on your use case. The FileReader object is used to convert the fil...
FileError - Web APIs
unsigned short The most appropriate error code for the condition. See Error codes for possible values. Error codes Note: Do not rely on the numeric values of the constants, which might change as the specifications continue to change. Use the constant names instead. Constant Value Description ENCODING_ERR 5 The URL is malformed. Make sure that the URL is
complete and valid. INVALID_MODIFICATION_ERR 9 The modification requested is not allowed. For example, the app might be trying to move a directory into its own child or moving a file into its parent directory without changing its name. INVALID_STATE_ERR 7 The operation cannot be performed on the current state of the interface object. For example, the state that was cached in ...
FileException - Web APIs
Type Description code unsigned short The most appropriate error code for the condition. Constants Note: Do not rely on the numeric values of the constants, which might change as the specifications continue to change. Use the constant names instead. Constant Value Description ENCODING_ERR 5 The URL is malformed. Make sure that the URL is
complete and valid. INVALID_MODIFICATION_ERR 9 The modification requested is not allowed. Examples of invalid modifications include moving a directory into its own child or moving a file into its parent directory without changing its name. INVALID_STATE_ERR 7 The operation cannot be performed on the current state of the interface object. For example, the state that was cached...
FileList - Web APIs
<!DOCTYPE HTML> <html> <head> </head> <body> <!--multiple is set to allow multiple files to be selected--> <input id="myfiles" multiple type="file"> </body> <script> var pullfiles=function(){ // love the query selector var fileInput = document.querySelector("#myfiles"); var files = fileInput.files; // cache files.length var fl = files.length; var i = 0; ...
FileReader: loadend event - Web APIs
The loadend event is fired when a file read has
completed, successfully or not. Bubbles No Cancelable No Interface ProgressEvent Event handler property FileReader.onloadend 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-log-contents { width: 18rem; heigh...
FileReader.readAsText() - Web APIs
Newer API avaliable The Blob.text() method is a newer promise-based API to read a file as text. Syntax instanceOfFileReader.readAsText(blob[, encoding]); Parameters blob The Blob or File from which to read. encoding Optional A string specifying the encoding to use for the returned data. By default, UTF-8 is assumed if this parameter is not specified. ...
FileReader.readyState - Web APIs
The FileReader readyState property provides the current state of the reading operation a FileReader is in. A FileReader exists in one of the following states: Value State Description 0 EMPTY Reader has been created. None of the read methods called yet. 1 LOADING A read method has been called. 2 DONE The operation is
complete. EMPTY The FileReader has been created, but no readAs method was called yet. LOADING A readAs method was invoked. A File or Blob is being read, and no error has occurred yet. DONE The read operation is
complete. This could mean that: the entire File or Blob has been read into memory, a file read error occurred, or abort() was called and the read was cancelled. Example var reader = new FileReader(); ...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
the directory as well as all of its content, hierarchically iterating over its entire subtree of descendant files and directories. To remove a single file, or an empty directory, you can also use FileSystemEntry.remove(). 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. Errors If an error occurs and an errorCallback was specified, it gets called with a single parameter: a FileError object describing the error. The File...
FileSystemFileEntry.file() - Web APIs
rs 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. 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...
FileSystemFileEntry - Web APIs
ata is written to the file by creating a blob, appending text to it, and passing the blob to FileWriter.write(). function onInitFs(fs) { fs.root.getFile('log.txt', {create: true}, function(fileEntry) { // Create a FileWriter object for our FileSystemFileEntry (log.txt). fileEntry.createWriter(function(fileWriter) { fileWriter.onwriteend = function(e) { console.log('Write
completed.'); }; fileWriter.onerror = function(e) { console.log('Write failed: ' + e.toString()); }; // Create a new Blob and write it to log.txt. var bb = new BlobBuilder(); bb.append('Meow'); fileWriter.write(bb.getBlob('text/plain')); }, errorHandler); }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorH...
FileHandle API - Web APIs
} File snapshot In many cases it can be handy to get a snapshot of the file. For example, there are many APIs that expect Blob or File objects such as FileReader (which can be easier to use to read the whole file) or XMLHttpRequest. It's possible to get a File object representing the current state of the file handled by the FileHandle object by using the getFile method. Such a File object is
completely desynchronized from the original file, which means any change made to that object will never be reflected to the handled file as well as any change made to the handled file will never be pushed to the File object. var mySnapshot = null; var request = myFileHandle.getFile(); request.onsuccess = function () { mySnapshot = this.result; } Managing progress All the methods from the LockedFile...
Introduction to the File and Directory Entries API - Web APIs
and speed) The app can write to files in place (for example, overwriting just the ID3/EXIF tags and not the entire file). Offline video viewer The app can download large files (>1GB) for later viewing. The app can access partially downloaded files (so that you can watch the first chapter of your DVD, even if the app is still downloading the rest of the content or if the app didn't
complete the download because you had to run to catch a train). Offline web mail client The client downloads attachments and stores them locally. The client caches attachments for later upload. Big concepts Before you start using the File and Directory Entries API, you need to understand a few concepts: The File and Directory Entries API is a virtual representation of a file system T...
FontFace.display - Web APIs
. This property is equivalent to the CSS font-display descriptor. When this property is used, font loading has a timeline with three periods. The lengths of the first two periods depend on the value of the property and the user agent. (See below.) block period The browser invisibly prepares a fallback font. If the font face loads during this time, it's used to display the text and display is
complete. swap period If the font face is still not loaded, the fallback font will be shown. When the font face loads, the fallback will be swaped for the downloaded font. failure period If the font face still is not loaded, the fallback font will be shown and no swap will occur. Syntax var display = FontFace.display FontFace.display = display Value A CSSOMString with one of the following values...
FontFaceSet - Web APIs
The FontFaceSet interface of the CSS Font Loading API manages the loading of font-faces and querying of their download status. Properties FontFaceSet.status Read only Indicates the font-face's loading status. It will be one of 'loading' or 'loaded'. FontFaceSet.ready Read only Promise which resolves once font loading and layout operations have
completed. Events FontFaceSet.onloading An EventListener called whenever an event of type loading is fired, indicating a font-face set has started loading. FontFaceSet.onloadingdone An EventListener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. FontFaceSet.onloadingerror An EventListener called whenever an event of type loadingerror is fired, indicating that an er...
Using FormData Objects - Web APIs
you augment the form's data before sending it along, to include additional information that's not necessarily user-editable. Sending files using a FormData object You can also send files using FormData. ...
Fullscreen API - Web APIs
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. 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 p...
GainNode.gain - Web APIs
eGain(); 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. ...
GainNode - Web APIs
.value or use the methods of AudioParam to change the effect of gain. Methods No specific method; inherits methods from its parent, AudioNode. 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. ...
GamepadHapticActuator.pulse() - Web APIs
f the pulse. This can vary depending on the hardware type, but generally takes a value between 0.0 (no intensity) and 1.0 (full intensity). duration A double representing the duration of the pulse, in milliseconds. Note: Repeated calls to pulse() override the previous calls if they are still ongoing. Return value A promise that resolves with a value of true when the pulse has successfully
completed. Examples TBC Specifications Specification Status Comment Gamepad ExtensionsThe definition of 'pulse()' in that specification. Editor's Draft Initial definition ...
GlobalEventHandlers.onanimationiteration - Web APIs
The onanimationiteration property of the GlobalEventHandlers mixin is the EventHandler for processing animationiteration events. The animationiteration event is sent when a CSS animation reaches the end of an iteration. An iteration ends when a single pass through the sequence of animation instructions is
completed by executing the last animation step. Syntax var animIterationHandler = target.onanimationiteration; target.onanimationiteration = Function Value A Function to be called when an animationiteration event occurs indicating that a CSS animation has reached the end of an iteration while running on the target, where the target object is an HTML element (HTMLElement), document (Document), or window (Window). The function receives as input a single parameter: an AnimationEven...
IDBKeyRange.upperOpen - Web APIs
ve been declared as open (true). We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its upperOpen property value to the console, which should appear as "true": the upper bound is open, so won't be included in the range. ...
IDBKeyRange - Web APIs
penCursor, declaring keyRangeValue as its optional key range value. This means that the cursor will only retrieve records with keys inside that range. This 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. ...
IDBObjectStore.delete() - Web APIs
This is used a lot below db = DBOpenRequest.result; // Run the deleteData() function to delete a record from the database deleteData(); }; function deleteData() { // open a read/write db transaction, ready for deleting the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.on
complete = function(event) { note.innerHTML += '<li>Transaction
completed.</li>'; }; transaction.onerror = function(event) { note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // Make a request to delete the specified record out of the obje...
IDBObjectStore.index() - Web APIs
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. Finally, we iterate through each record, and insert the data into an HTML table. ...
IDBObjectStore.openKeyCursor() - Web APIs
The openKeyCursor() method of the IDBObjectStore interface returns an IDBRequest object whose result will be set to an IDBCursor that can be used to iterate through matching results. Used for iterating through the keys of an object store with a cursor. To determine if the add operation has
completed successfully, listen for the results's success event. Syntax var request = objectStore.openKeyCursor(); var request = objectStore.openKeyCursor(query); var request = objectStore.openKeyCursor(query, direction); Parameters query Optional The key range to be queried. 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. direction Optional An IDBCursorDi...
IDBRequest.readyState - Web APIs
Note: This feature is available in Web Workers. Syntax var currentReadyState = request.readyState; Value The IDBRequestReadyState of the request, which takes one of the following two values: Value Meaning pending The request is pending. done The request is done. ...
IDBTransaction.commit() - Web APIs
rkers. Syntax transaction.commit(); Parameters None. Return value Void. Exceptions Exception Description InvalidStateError The transaction state is not active. Examples // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["myDB"], "readwrite"); // report on the success of opening the transaction transaction.on
complete = function(event) { note.innerHTML += '<li>Transaction
completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("myObjStore"); // add our newItem object to the object sto...
IDBTransaction.error - Web APIs
dData() { // Create a new object ready for being inserted into the IDB var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of opening the transaction transaction.on
complete = function(event) { note.innerHTML += '<li>Transaction
completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to th...
IDBTransaction.onabort - Web APIs
dData() { // Create a new object ready for being inserted into the IDB var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of opening the transaction transaction.on
complete = function(event) { note.innerHTML += '<li>Transaction
completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to the...
IDBTransaction.onerror - Web APIs
dData() { // Create a new object ready for being inserted into the IDB var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of opening the transaction transaction.on
complete = function(event) { note.innerHTML += '<li>Transaction
completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to th...
IDBTransactionSync - Web APIs
s 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 this transaction has already been committed or aborted. RECOVE...
IIRFilterNode.getFrequencyResponse() - Web APIs
each frequency value in the frequencyArray. phaseResponseOutput A Float32Array to receive the computed phase response values in radians for each frequency value in the input frequencyArray. Return value undefined Exceptions NotSupportedError The three arrays provided are not all of the same length. Examples In the following example we are using an IIR filter on a media stream (for a
complete full demo, see our stream-source-buffer demo live, or read its source.) As part of this demo, we get the frequency responses for this IIR filter, for five sample frequencies. We first create the Float32Array objects we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var myFrequencyArray = new Float32Array(5); myFrequencyArray[0] = 1000; myFre...
IdleDeadline.didTimeout - Web APIs
that can be done to keep things moving along, then schedule a new callback to try again to get the rest of the work done. Syntax var timedOut = IdleDeadline.didTimeout; Value A Boolean which is true if the callback is running due to the callback's timeout period elapsing or false if the callback is running because the user agent is idle and is offering time to the callback. Example See our
complete example in the article Cooperative Scheduling of Background Tasks API. Specifications Specification Status Comment Cooperative Scheduling of Background Tasks Proposed Recommendation ...
IdleDeadline - Web APIs
ck was installed has expired. Methods IdleDeadline.timeRemaining() Returns a DOMHighResTimeStamp, which is a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period. If the idle period is over, the value is 0. Your callback can call this repeatedly to see if there's enough time left to do more work before returning. Example See our
complete example in the article Cooperative Scheduling of Background Tasks API. Specifications Specification Status Comment Cooperative Scheduling of Background Tasks Proposed Recommendation ...
InputEvent.inputType - Web APIs
ad-only property of the InputEvent interface returns the type of change made to editible content. Possible changes include for example inserting, deleting, and formatting text. Syntax var aString = inputEvent.inputType; Value A DOMString containing the type of input that was made. There are many possible values, such as insertText, deleteContentBackward, insertFromPaste, and formatBold. For a
complete list of the available input types, see the Attributes section of the Input Events Level 1 spec. Examples This example logs the inputType for input events on an editable <div>. HTML <p id="log">Input type: </p> <div contenteditable="true" style="margin: 20px;padding: 20px;border:2px dashed red;"> <p>Some sample text. Try inserting line breaks, or deleting text in different ways, or pasting d...
InputEvent - Web APIs
rt text (such as when deleting characters, for example). InputEvent.dataTransferRead only Returns a DataTransfer object containing information about richtext or plaintext data being added to or removed from editable content. InputEvent.inputTypeRead only Returns the type of change for editable content such as, for example, inserting, deleting, or formatting text. See the property page for a
complete list of input types. InputEvent.isComposingRead only Returns a Boolean value indicating if the event is fired after compositionstart and before compositionend. Methods This interface inherits methods from its parents, UIEvent and Event. InputEvent.getTargetRanges() Returns an array of static ranges that will be affected by a change to the DOM if the input event is not canceled. Specif...
install - Web APIs
Summary Installs one or more XPI files on the local machine. Method of InstallTrigger object Syntax int install(array XPIlist [, function callBackFunc ] ) Parameters The install method has the following parameters: XPIlist An array of files to be installed (see example below). callBackFunc An optional callback function invoked when the installation is
complete (see example below). Firefox 3 note In Firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. Returns install returns True if the function succeeded and False if it did not, but these values are not always reliable as a determinant of the success of the operation. To surface detail about the status of the installation, use the option...
IntersectionObserverEntry.time - Web APIs
ment was created. Syntax var time = IntersectionObserverEntry.time; Value A DOMHighResTimeStamp which indicates the time at which the target element experienced the intersection change described by the IntersectionObserverEntry. The time is specified in milliseconds since the creation of the containing document. Example See Timing element visibility with the Intersection Observer API for a
complete example which uses the time property to track how long elements are visible to the user. Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserverEntry.time' in that specification. Working Draft Initial definition ...
Timing element visibility with the Intersection Observer API - Web APIs
watch for intersections with the document's viewport (by setting root to null). We have no margins to extend or contract the intersection root's rectangle; we want to match the boundaries of the document's viewport exactly for intersection purposes. And the threshold is set to an array containing the values 0.0 and 0.75; this will cause our callback to execute whenever a targeted element becomes
completely obscured or first starts to become unobscured (intersection ratio 0.0) or passes through 75% visible in either direction (intersection ratio 0.75). The observer, adObserver, is created by calling IntersectionObserver's constructor, passing in the callback function, intersectionCallback, and our options. We then call a function buildContents(), which we'll define later to actually generate and...
Intersection Observer API - Web APIs
e call Window.addEventListener() to start listening for the load event; once the page has finished loading, we get a reference to the element with the ID "box" using querySelector(), then call the createObserver() method we'll create in a moment to handle building and installing the intersection observer. Creating the intersection observer The createObserver() method is called once page load is
complete to handle actually creating the new IntersectionObserver and starting the process of observing the target element. function createObserver() { let observer; let options = { root: null, rootMargin: "0px", threshold: buildThresholdList() }; observer = new IntersectionObserver(handleIntersect, options); observer.observe(boxElement); } This begins by setting up an options ob...
Key Values - Web APIs
ves the state of the computer to disk and then shuts down; the computer can be returned to its previous state by restoring the saved state information. GDK_KEY_Hibernate (0x1008FFA8) Qt::Key_Hibernate (0x01000108) "Standby" [1] The Standby key. (Also known as Suspend or Sleep.) This turns off the display and puts the computer in a low power consumption mode, without
completely powering off. VK_SLEEP (0x5F) GDK_KEY_Standby (0x1008FF10) GDK_KEY_Suspend (0x1008FFA7) GDK_KEY_Sleep (0x1008FF2F) Qt::Key_Standby (0x01000093) Qt::Key_Suspend (0x0100010C) Qt::Key_Sleep (0x01020004) KEYCODE_SLEEP (223) "WakeUp" [2] The WakeUp key. Used to wake the computer from the hibernation or standby modes. GDK_KEY_WakeUp (0x1008FF2B)...
KeyboardEvent.key - Web APIs
at would result in a character being inserted into possibly an <input>, <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down. A keyup event is fired once the key is released. This
completes the process. In sequence 1 & 3, the KeyboardEvent.key attribute is defined and is set appropriately to a value according to the rules defined ealier. KeyboardEvent sequence example Consider the event sequence generated when we interact with the Shift and the 2 key using a U.S keyboard layout as compared to when we do so using a UK keyboard layout. Try experimenting using the following two t...
LockManager.request() - Web APIs
ing that multiple calls may occur simultaneously across different event handlers, tabs, or workers. async function do_read() { await navigator.locks.request('my_resource', {mode: 'shared'}, async lock => { // Read code here. }); } The do_write() function use the same lock but in 'exclusive' mode which will delay invocation of the request() call in do_read() until the write operation has
completed. This applies across event handlers, tabs, or workers. function do_write() { await navigator.locks.request('my_resource', {mode: 'exclusive'}, async lock => { // Write code here. }); } ifAvailable Example To grab a lock only if it isn't already being held, use the ifAvailable option. In this function await means the method will not return until the callback is
complete. Since the lock...
LockedFile - Web APIs
LockedFile.fileHandle Read only The FileHandle object from which the lock was opened. LockedFile.mode Read only The mode for accessing the file; can be readonly 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.on
complete 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. L...
MSManipulationEvent - Web APIs
lated has changed. Methods MSManipulationEvent.initMSManipulationEvent(): Used to create a manipulation event that can be called from JavaScript. Properties Property Description currentStateRead only Returns the current state of a manipulation event. inertiaDestinationXRead only Represents the predicted horizontal scroll offset after the inertia phase
completes. inertiaDestinationYRead only Represents the predicted vertical scroll offset after the inertia phase
completes. lastStateRead only Returns the last state after a manipulation change event. Example interface MSManipulationEvent extends UIEvent { readonly currentState: number; readonly inertiaDestinationX: number; readonly inertiaDestinationY: number;...
MediaError.message - Web APIs
This example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute. The error handler simply outputs a message to a box onscreen describing the error, including both the code and the message. Only the relevant parts of the code are displayed; you can see the
complete source code here. The example creates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist. This lets us see the behavior of the error event handler, which is received by an event handler we add to the <audio> element itself. The error handler looks like this: audioElement.onerror = function() { let s = ""; let err = aud...
MediaRecorder - Web APIs
Specifications Specification Status Comment MediaStream Recording Working Draft Initial definition ...
MediaSessionActionDetails.fastSeek - Web APIs
The Boolean property fastSeek in the MediaSessionActionDetails dictionary is an optional value which, when specified and true, indicates that the requested seekto operation is part of an ongoing series of seekto operations. Your handler should take steps to return as quickly as possible by skipping any steps of its operation which are only necessary when the seek operation is
complete. Once fastSeek is false or not present, the repeating series of seekto actions is
complete and you can finalize the state of your web app or content. Syntax let mediaSessionActionDetails = { fastSeek: shouldFastSeek }; let shouldFastSeek = mediaSessionActionDetails.fastSeek; Value A Boolean which is true if the action is part of an ongoing series of seek actions which should be treated as part of an overall s...
MediaStream.ended - Web APIs
This value once the ended event has been fired. This property has been removed from the specification; you should instead rely on the ended event or check the value of MediaStreamTrack.readyState to see if its value is "ended" for the track or tracks you want to ensure have finished playing. Syntax var hasEnded = MediaStream.ended; Value A Boolean value that returns true if the end of the stream has been reached. ...
MediaStreamTrack.stop() - Web APIs
k 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 calling stop() on every track on a given <video>. function stopStreamedVideo(videoElem) { const stream = videoElem.srcObject; const tracks = stream.getTracks(); tracks.forEach(function(track) { tra...
Recording a media element - Web APIs
lling the startRecording() function we created earlier, passing in the preview video stream (as the source media to be recorded) and recordingTimeMS as the number of milliseconds of media to record. As mentioned before, startRecording() returns a Promise whose resolution handler is called (receiving as input an array of Blob objects containing the chunks of recorded media data) once recording has
completed. Lines 11-15 The recording process's resolution handler receives as input an array of media data Blobs locally known as recordedChunks. The first thing we do is merge the chunks into a single Blob whose MIME type is "video/webm" by taking advantage of the fact that the Blob() constructor concatenates arrays of objects into one object. Then URL.createObjectURL() is used to create an URL that re...
Using the MediaStream Recording API - Web APIs
; } ); } else { console.log('getUserMedia not supported on your browser!'); } The whole thing is wrapped in a test that checks whether getUserMedia is supported before running anything else. Next, we call getUserMedia() and inside it define: The constraints: Only audio is to be captured for our dictaphone. The success callback: This code is run once the getUserMedia call has been
completed successfully. The error/failure callback: The code is run if the getUserMedia call fails for whatever reason. Note: All of the code below is placed inside the getUserMedia success callback. Capturing the media stream Once getUserMedia has created a media stream successfully, you create a new Media Recorder instance with the MediaRecorder() constructor and pass it the stream directly. This...
MediaTrackConstraints.cursor - Web APIs
y. 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 fallback In this example, the cursor property is configured to request that the cursor be visible when in motion, falling back to always being v...
MediaTrackConstraints.displaySurface - Web APIs
ag 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 specification. ...
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 they're ...
MediaTrackSettings.displaySurface - Web APIs
indows belonging to the application chosen by the user. The windows are aggragated into a single video track, with any empty space filled with a backdrop; that backdrop is selected by the user agent. browser The stream's video track presents the entire contents of a single browser tab which the user selected during the getDisplayMedia() call. monitor The video track in the stream presents the
complete contents of one or more of the user's screens. Any empty space (if the displays are of different dimensions) is filled with a backdrop chosen by the user agent. window The stream's video track presents the contents of a single window selected by the user. The window may be from any application, not necessarily just from within the user agent. Not all user agents support all of these surface t...
MerchantValidationEvent() - Web APIs
being used. 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(). 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 specif...
MerchantValidationEvent.validationURL - Web APIs
The MerchantValidationEvent property validationURL is a read-only string value providing the URL from which to fetch the payment handler-specific data needed to validate the merchant. This data should be passed into the
complete() method to let the user agent
complete the transaction. Syntax validationURL = merchantValidationEvent.validationURL; Value A read-only USVString giving the URL from which to load payment handler specific data needed to
complete the merchant verification process. Once this has been loaded, it should be passed into
complete(), either directly or using a promise. See Merchant validation in Payment processing concepts for more information on the merchant validation process. Specifications Specification Status Comment Payment Request APIThe ...
MerchantValidationEvent - Web APIs
strings 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 'MerchantV...
Microsoft API extensions - Web APIs
msAudioDeviceType HTMLMediaElement.msClearEffects() HTMLMediaElement.msInsertAudioEffect() MediaError.msExtendedCode MSGraphicsTrust msGraphicsTrustStatus msIsBoxed msPlayToDisabled msPlayToPreferredSourceUri msPlayToPrimary msPlayToSource msRealTime msSetMediaProtectionManager msSetVideoRectangle msStereo3DPackingMode msStereo3DRenderMode onMSVideoFormatChanged onMSVideoFrameStep
Completed onMSVideoOptimalLayoutChanged msFirstPaint Pinned Sites APIs MSSiteModeEvent mssitemodejumplistitemremoved msthumbnailclick Other APIs x-ms-aria-flowfrom x-ms-acceleratorkey x-ms-format-detection msCaching msCachingEnabled msCapsLockWarningOff Event.msConvertURL() mselementresize Document.msElementsFromRect() msIsStaticHTML Navigator.msLaunchUri() msLaunchUriCallback...
msFirstPaint - Web APIs
ion 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. msFirstPaint is a read-only property which gets the time when the document loaded by the window object began to be displayed to the user. Put another way, msFirstPaint utilizes the browser to measure when the first content
completes being painted in the window. It is available from javascript and can be reported from the field. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax p = object.msFirstPaint; Value An Integer value that represents the time when the document began to be displayed or 0 if the document could not be loaded. The numerical value reported represents the numbe...
NDEFWriter.write() - Web APIs
fying whether or not to skip reading for the activated reader objects. Will be ignored if overwrite is false. overwrite -- Boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional AbortSignal that allows to cancell this write operation. Return value A Promise that resolves with undefined when and if the message transfer is successfully
completed. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: AbortError The write operation was aborted with AbortSignal passed in options. NotAllowedError The permission for this operation was rejected or overwrite is false and there are already records on the tag. NotSupportedError ...
Using Navigation Timing - Web APIs
s Properties section. Determining navigation type To put the timing information obtained from PerformanceTiming into the correct perspective, you need to know more about what sort of load operation occurred. In particular, you need to know: Was this a load or a reload? Was this a navigation or a move forward or backward through history? How many (if any) redirects were required in order to
complete the navigation? This information is provided by the Performance.navigation property, which returns a PerformanceNavigation object that includes the needed information. Let's add this information to the example above. The new code looks like this: window.addEventListener("load", function() { let now = new Date().getTime(); let loadingTime = now - performance.timing.navigationStart; outp...
Navigation Timing API - Web APIs
Here, the time at which the request was initiated (requestStart). from the time at which the response was finished being received (responseEnd). Calculate page render time As another example of an interesting piece of data you can obtain using the Navigation Timing API that you can't otherwise easily get, you can get the amount of time it took to render the page: const renderTime = perfData.dom
Complete - perfData.domLoading; This is obtained by starting with the time at which loading of the DOM and its dependencies is
complete (dom
Complete) and subtracting from it the time at which parsing of the DOM began (domLoading). Specifications Specification Status Comment Navigation Timing Level 2 Working Draft Adds PerformanceNavigationTiming Navigation Tim...
Navigator.share() - Web APIs
ining 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). It will reject immediately if the data parameter is not correctly specified, and will also reject if the user cancels sharing. Examples In our Web share test (see the source code) there is a button which, when clicked, invokes the Web Share API to share MDN's URL. The JavaScript looks like this: const shareData = { tit...
Navigator.wakeLock - Web APIs
The wakeLock read-only property returns a WakeLock interface which allows a document to acquire a screen wake lock. While a screen wake lock is active, the user agent will try to prevent the device from dimming the screen, turning it off
completely, or showing a screensaver. Syntax const wakeLock = navigator.wakeLock; Specifications Specification Status Comment Screen Wake Lock API Editor's Draft Initial definition ...
NavigatorID.userAgent - Web APIs
n't affect browser detection performed by JavaScript code. Opera 6+ allows users to set the browser identification string via a menu. Microsoft Internet Explorer uses the Windows registry. Safari and iCab allow users to change the browser user agent string to predefined Internet Explorer or Netscape strings via a menu. Syntax var ua = navigator.userAgent; Value A DOMString specifying the
complete user agent string the browser provides both in HTTP headers and in response to this and other related methods on the Navigator object. The user agent string is built on a formal structure which can be decomposed into several pieces of info. Each of these pieces of info comes from other navigator properties which are also settable by the user. Gecko-based browsers comply with the following genera...
Notification.requestPermission() - Web APIs
he 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. Possible values for this string are: granted denied default Examples Assume this basic HTML: <button onclick="notifyMe()">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. function notifyMe() { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does no...
Notification - Web APIs
ailable 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. Examples Assume this basic HTML: <button onclick="notifyMe()">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. function notifyMe() { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does no...
OES_texture_float - Web APIs
type Float32Array. Limitation: Linear filtering Linear filtering on 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 floating-point textures, the texture will be marked as in
complete. To 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.createTe...
OES_texture_half_float - Web APIs
OAT_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 in
complete. 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 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 text...
OVR_multiview2 - Web APIs
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 which is currently the maximum number of views supported by multiview. FRAMEBUFFER_IN
COMPLETE_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 in
complete. Calling checkFramebufferStatus for a framebuffer in this state returns FRAMEBUFFER_IN
COMPLETE_VIEW_TARGETS_OVR. Methods framebufferTextureMultiviewOVR() Simultaneously renders to multiple element...
OfflineAudioCompletionEvent - Web APIs
Note: This interface is marked as deprecated; it is still supported for legacy reasons, but it will soon be superseded when the promise version of OfflineAudioContext.startRendering is supported in browsers, which will no longer need it. Constructor OfflineAudioCompletionEvent.OfflineAudioCompletionEvent Creates a new OfflineAudioCompletionEvent object instance. Properties Also inherits properties from its parent, Event. ...
PannerNode.distanceModel - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
PannerNode.maxDistance - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
PannerNode.orientationX - Web APIs
The orientationX property of the PannerNode interface indicates the X (horizontal) component of the direction in which the audio source is facing, in a 3D Cartesian coordinate space. The
complete vector is defined by the position of the audio source, given as (positionX, positionY, positionZ), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationX, orientationY, orientationZ). Depending on the directionality of the sound (as specified using the attributes coneInnerAngle, coneOuterAngle, and coneOuterGain), the orientation of the sound may alter the perceived volume of the sound as it's being played. If the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. The AudioParam contained...
PannerNode.orientationY - Web APIs
The orientationY property of the PannerNode interface indicates the Y (vertical) component of the direction the audio source is facing, in 3D Cartesian coordinate space. The
complete vector is defined by the position of the audio source, given as (positionX, positionY, positionZ), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationX, orientationY, orientationZ). Depending on the directionality of the sound (as specified using the attributes coneInnerAngle, coneOuterAngle, and codeOuterGain), the orientation of the sound may alter the perceived volume of the sound as it's being played. If the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. The AudioParam contained by this prop...
PannerNode.orientationZ - Web APIs
The orientationZ property of the PannerNode interface indicates the Z (depth) component of the direction the audio source is facing, in 3D Cartesian coordinate space. The
complete vector is defined by the position of the audio source, given as (positionX, positionY, positionZ), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationX, orientationY, orientationZ). Depending on the directionality of the sound (as specified using the attributes coneInnerAngle, coneOuterAngle, and codeOuterGain), the orientation of the sound may alter the perceived volume of the sound as it's being played. If the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. The AudioParam contained by this propert...
PannerNode.panningModel - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
PannerNode.positionX - Web APIs
The positionX property of the PannerNode interface specifies the X coordinate of the audio source's position in 3D Cartesian coordinates, corresponding to the horizontal axis (left-right). The
complete vector is defined by the position of the audio source, given as (positionX, positionY, positionZ), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationX, orientationY, orientationZ). Depending on the directionality of the sound (as specified using the attributes coneInnerAngle, coneOuterAngle, and codeOuterGain), the orientation of the sound may alter the perceived volume of the sound as it's being played. If the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. The AudioParam con...
PannerNode.positionY - Web APIs
The positionY property of the PannerNode interface specifies the Y coordinate of the audio source's position in 3D Cartesian coordinates, corresponding to the vertical axis (top-bottom). The
complete vector is defined by the position of the audio source, given as (positionX, positionY, positionZ), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationX, orientationY, orientationZ). Depending on the directionality of the sound (as specified using the attributes coneInnerAngle, coneOuterAngle, and codeOuterGain), the orientation of the sound may alter the perceived volume of the sound as it's being played. If the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. The AudioParam contai...
PannerNode.positionZ - Web APIs
The positionZ property of the PannerNode interface specifies the Z coordinate of the audio source's position in 3D Cartesian coordinates, corresponding to the depth axis (behind-in front of the listener). The
complete vector is defined by the position of the audio source, given as (positionX, positionY, positionZ), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationX, orientationY, orientationZ). Depending on the directionality of the sound (as specified using the attributes coneInnerAngle, coneOuterAngle, and codeOuterGain), the orientation of the sound may alter the perceived volume of the sound as it's being played. If the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. The...
PannerNode.setOrientation() - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
PannerNode.setPosition() - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
PannerNode.setVelocity() - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
PannerNode - Web APIs
ou 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 to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it su...
ParentNode.childElementCount - Web APIs
hange that shouldn't affect compatibility. Syntax var count = node.childElementCount; count The return value, which is an unsigned long (simply an integer) type. node An object representing a Document, DocumentFragment, or Element. Example var foo = document.getElementById('foo'); if (foo.childElementCount > 0) { // Do something } Polyfill for IE8 & IE9 & Safari This property is
completely unsupported prior to IE9. In IE9 and Safari, it is unsupported in the Document and DocumentFragment objects. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.childElementCount == null) { Object.defineProperty(constructor.prototype, 'childElementCount', { get: function() { var i = 0, count = 0, node, nodes = this.childNo...
PasswordCredential - Web APIs
reference to an HTMLFormElement with appropriate input fields. The form should, at the very least, contain an id and password. It could also require a CSRF token. Examples This example shows how to set up an HTMLFormElement to caputure data which we'll use to create a PasswordCredential object. Starting with the form element. <form id="form" method="post"> <input type="text" name="id" auto
complete="username" /> <input type="password" name="password" auto
complete="current-password" /> <input type="hidden" name="csrf_token" value="*****" /> </form> Then, a reference to this form element, using it to create a PasswordCredential object, and storing it in the browser's password system. var form = document.querySelector('#form'); var creds = new PasswordCredential(form); // Store the crede...
PaymentAddress - Web APIs
= new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. // Call show() to trigger the browser's payment flow. const response = await request.show(); // Process payment. const json = response.toJSON(); const httpResponse = await fetch("/pay/", { method: "POST", body: json }); const result = httpResponse.ok ? "success" : "failure"; await response.
complete(result); } doPaymentRequest(); 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, an...
PaymentRequest.PaymentRequest() - Web APIs
sh speaking countries you would say "pizza delivery" not "pizza shipping". Valid values are "shipping", "delivery", and "pickup". Quotation marks must be included. The default value is "shipping". Return value A new PaymentRequest object, configured for use as configured by the input parameters. Examples The following example shows minimal functionality and focuses instead on showing the
complete context of instantiating a PaymentRequest object. var supportedInstruments = [{ supportedMethods: 'basic-card', data: { supportedNetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'] } }]; var details = { total: {label: 'Donation', amount: {currency: 'USD', value: '65.00'}}, displayItems: [ { label: 'Original donation...
PaymentRequest.onmerchantvalidation - Web APIs
n; Value An event handler function which is to be called whenever the merchantvalidation event is fired at the PaymentRequest, indicating that the payment handler requires the merchant to validate themselves as allowed to use this payment handler. Examples An example merchant validation handler for the PaymentRequest object request looks like this: request.onmerchantvalidation = ev => { ev.
complete(async () => { const merchantServerUrl = window.location.origin + '/validation?url=' + encodeURIComponent(ev.validationURL); // get validation data, and
complete validation; return await fetch(merchantServerUrl).then(r => r.text()); }) }; const response = await request.show(); For more information, see Merchant Validation in Payment processing concepts. Specifications ...
PaymentRequest - Web APIs
shippingAddress Read only Secure context If requested via payment options, returns the shipping address chosen by the user for the purposes of calculating shipping. This property is only populated if the constructor is called with the requestShipping flag set to true. Additionally, in some browsers, the parts of the address will be redacted for privacy until the user indicates they are ready to
complete the transaction (i.e., they hit "Pay"). PaymentRequest.shippingOption Read only Secure context Returns the identifier of the 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 shi...
PaymentResponse - Web APIs
. Methods PaymentResponse.retry() Secure context If something is wrong with the payment response's data (and there is a recoverable error), this method allows a merchant to request that the user retry the payment. The method takes an object as argument, which is used to signal to the user exactly what is wrong with the payment response so they can try to correct any issues. PaymentResponse.
complete() Secure context Notifies the user agent that the user interaction is over. This causes any remaining user interface to be closed. This method should only be called after the Promise returned by the PaymentRequest.show() method. Events Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface. payerdetailchange Secure co...
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
// Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Spe...
PerformanceNavigationTiming.domInteractive - Web APIs
// Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.domInteractive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } ...
PerformanceNavigationTiming.loadEventStart - Web APIs
// Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Spe...
PerformanceNavigationTiming.redirectCount - Web APIs
// Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Spe...
PerformanceNavigationTiming.type - Web APIs
// Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Spe...
PerformanceNavigationTiming.unloadEventEnd - Web APIs
// Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Spe...
PerformanceNavigationTiming.unloadEventStart - Web APIs
// Use getEntriesByType() to just get the "navigation" events var perfEntries = performance.getEntriesByType("navigation"); for (var i=0; i < perfEntries.length; i++) { console.log("= Navigation entry[" + i + "]"); var p = perfEntries[i]; // dom Properties console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)); console.log("DOM
complete = " + p.dom
Complete); console.log("DOM interactive = " + p.interactive); // document load and unload time console.log("document load = " + (p.loadEventEnd - p.loadEventStart)); console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart)); // other properties console.log("type = " + p.type); console.log("redirectCount = " + p.redirectCount); } } Spe...
PerformanceTiming.loadEventEnd - Web APIs
in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface's PerformanceNavigationTiming.loadEventEnd read-only property instead. The legacy PerformanceTiming.loadEventEnd read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, when the load event handler terminated, that is when the load event is
completed. If this event has not yet been sent, or is not yet
completed, it returns 0. Syntax time = performanceTiming.loadEventEnd; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.loadEventEnd' in that specification. Recommendation Initial definition. ...
PerformanceTiming.redirectEnd - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceTiming.redirectEnd read-only property returns an unsigned long long representing the moment, in miliseconds since the UNIX epoch, the last HTTP redirect is
completed, that is when the last byte of the HTTP response has been received. If there is no redirect, or if one of the redirect is not of the same origin, the value returned is 0. Syntax time = performanceTiming.redirectEnd; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceTiming.redirectEnd' in that specification. Recommendation Initial definition. ...
ProgressEvent.initProgressEvent() - Web APIs
bleArg, cancelableArg, lengthComputable, loaded, total); Parameters typeArg Is a DOMString identifying the specific type of animation event that occurred. The following values are allowed: Value Meaning loadstart The operation has started. progress The operation still is in progress. error The operation failed and didn't
complete. abort The operation was cancelled and didn't
complete. load The operation
completed. loadend The operation stopped. canBubbleArg Is a Boolean flag indicating if the event can bubble (true) or not (false). cancelableArg Is a Boolean flag indicating if the event associated action can be avoided (true) or not (false). lengthComputable ...
PublicKeyCredentialCreationOptions.timeout - Web APIs
This property is optional and merely is a hint which may be overridden by the browser. Note: An analogous option exists for the fetching operation (navigators.credentials.get()), see PublicKeyCredentialRequestOptions.timeout. Syntax timeout = publicKeyCredentialCreationOptions.timeout Value A numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to
complete. Examples var publicKey = { timeout: 6000, // Accepting to wait for a minute before giving up. challenge: new Uint8Array(26) /* this actually is given from the server */, rp: { name: "Example CORP", id : "login.example.com" }, user: { id: new Uint8Array(26), /* To be changed for each user */ name: "jdoe@example.com", displayName: "John Doe", }, pubKeyCredParam...
PublicKeyCredentialCreationOptions - Web APIs
edParams An Array of element which specify the desired features of the credential, including its type and the algorithm used for the cryptographic signature operations. This array is sorted by descending order of preference. PublicKeyCredentialCreationOptions.timeout Optional A numerical hint, in milliseconds, which indicates the time the caller is willing to wait for the creation operation to
complete. This hint may be overridden by the browser. PublicKeyCredentialCreationOptions.excludeCredentials Optional An Array of descriptors for existing credentials. This is provided by the relying party to avoid creating new public key credentials for an existing user who already have some. PublicKeyCredentialCreationOptions.authenticatorSelection Optional An object whose properties are criteria use...
PublicKeyCredentialRequestOptions.timeout - Web APIs
his property is optional and merely is a hint which may be overridden by the browser. Note: An analogous option exists for the creation operation (navigators.credentials.create()), see PublicKeyCredentialCreationOptions.timeout. Syntax timeout = publicKeyCredentialRequestOptions.timeout Value A numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to
complete. Examples var options = { challenge: new Uint8Array([/* bytes sent from the server */]), timeout: 6000 // Wait a minute for the fetching operation // and maybe fail if it takes longer }; navigator.credentials.get({ "publicKey": options }) .then(function (credentialInfoAssertion) { // send assertion response back to the server // to proceed with the control of ...
PublicKeyCredentialRequestOptions - Web APIs
ufferSource, emitted by the relying party's server and used as a cryptographic challenge. This value will be signed by the authenticator and the signature will be sent back as part of AuthenticatorAssertionResponse.signature. PublicKeyCredentialRequestOptions.timeout Optional A numerical hint, in milliseconds, which indicates the time the caller is willing to wait for the retrieval operation to
complete. This hint may be overridden by the browser. PublicKeyCredentialRequestOptions.rpId Optional A USVString which indicates the relying party's identifier (ex. "login.example.org"). If this option is not provided, the client will use the current origin's domain. PublicKeyCredentialRequestOptions.allowCredentials Optional An Array of credentials descriptor which restricts the acceptable existing ...
Web Push API Notifications best practices - Web APIs
ns Web Push Notifications (created using a combination of the Notifications, Push, and Service Worker APIs) are part of the rising noise that product developers and marketers are using to get attention for their sites. Searching the web for "web push notifications," you'll find articles from marketing experts who believe you should use push to re-engage people who have left your site so they can
complete a purchase, or be sent the latest news, or receive links to recommended products. The dark side Their novelty provides a new and unexploited opportunity for enterprising sites to reach potential customers. Has the customer switched tabs to answer an email? Win them back with an expiring offer of free shipping that they can't ignore! But really, is this the best use of push notifications? Or is...
RTCDataChannelEvent - Web APIs
be monitored. The channel property provides the RTCDataChannel representing the connection to the other peer. pc.ondatachannel = function(event) { inboundDataChannel = event.channel; inboundDataChannel.onmessage = handleIncomingMessage; inboundDataChannel.onopen = handleChannelOpen; inboundDataChannel.onclose = handleChannelClose; } See A simple RTCDataChannel sample for another, more
complete, example of how to use data channels. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannelEvent' in that specification. Candidate Recommendation Initial definition. ...
RTCDtlsTransport.state - Web APIs
er Security (DTLS) transport state. Syntax let myState = dtlsTransport.state; Value A string whose value is taken from the RTCDtlsTransportState enumerated type. Its value is one of the following: new The initial 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 functi...
RTCIceCandidate.RTCIceCandidate() - Web APIs
: foundation, component, priority , ip, protocol, port, type, tcpType, relatedAddress, and relatedPort. Note: Parsing of the candidate string is performed using the candidate-attribute grammar from the WebRTC Specification. Exceptions TypeError The specified RTCIceCandidateInit has values of null in both the sdpMid and sdpMLineIndex properties. Usage notes This constructor does not do
complete validation of the specified candidateInfo object or string. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidate()' in that specification. Candidate Recommendation Initial definition. ...
RTCIceCandidate.candidate - Web APIs
udp 2043278322 192.168.0.56 44323 typ host the corresponding candidate string's value will be "candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host". The user agent always prefers candidates with the highest priority, all else being equal. In the example above, the priority is 2043278322. The attributes are all separated by a single space character, and are in a specific order. ...
RTCIceCandidateInit.candidate - Web APIs
udp 2043278322 192.168.0.56 44323 typ host the corresponding candidate string's value will be "candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host". The user agent always prefers candidates with the highest priority, all else being equal. In the example above, the priority is 2043278322. The attributes are all separated by a single space character, and are in a specific order. ...
RTCIceGathererState - Web APIs
The RTCIceGathererState enumerated type provides the string values which can be returned by an RTCIceTransport object's gatheringState. Values "new" The RTCIceTransport is newly created and has not yet started to gather ICE candidates. "gathering" The transport is in the process of gathering candidates. "
complete" The transport has finished gathering ICE candidates and has sent the end-of-candidates indicator to the remote device. The transport won't gather any further candidates unless an ICE restart occurs, at which point the gathering process starts over from scratch. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceGathererState' in that specification. Candidate Recommendation Ini...
RTCIceTransport.gatheringState - Web APIs
The read-only RTCIceTransport property gatheringState returns a DOMString from the enumerated type RTCIceGathererState that indicates what gathering state the ICE agent is currently in: "new", "gathering", or "
complete". Syntax gatherState = RTCIceTransport.gatheringState; Value A string from the RTCIceGathererState enumerated type whose value indicates the current state of the ICE agent's candidate gathering process: "new" The RTCIceTransport is newly created and has not yet started to gather ICE candidates. "gathering" The transport is in the process of gathering candidates. "
complete" The transport has finished gathering ICE candidates and has sent the end-of-candidates indicator to the remote device. The transport won't gather any further candidates unless an ICE restart occurs, a...
RTCIceTransport.state - Web APIs
candidates pairings to consider, and there may still be gathering underway on one or both of the two devices. The transport may revert from the "connected" state to the "checking" state if either peer decides to cancel consent to use the selected candidate pair, and may revert to "disconnected" if there are no candidates left to check but one or both clients are still gathering candidates. "
completed" The transport has finished gathering local candidates and has received a notification from the remote peer that no more candidates will be sent. In addition, all candidate pairs have been considered and a pair has been selected for use. If consent checks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" The ICE agent has determined that conne...
RTCIdentityErrorEvent.loginUrl - Web APIs
It can be null and is provided by the identity provider (idp). Firefox implements the interface of this property under the following name: RTCPeerConnectionIdentityErrorEvent. It is likely that it will correct this name when it will unprefix RTCPeerConnection, once spec and implementation will have been stabilized. ...
RTCIdentityErrorEvent - Web APIs
ction, once spec and implementation will have been stabilized. Properties A RTCIdentityErrorEvent being an Event, this event also implements these properties. RTCIdentityErrorEvent.idp Read only Is a DOMString describing the domain name of the identity provider (idp) generating the error response. RTCIdentityErrorEvent.loginUrl Read only Is a DOMString giving the URL where the user can
complete the authentication. It can be null and is provided by the identity provider (idp). RTCIdentityErrorEvent.protocol Read only Is a DOMString describing the Idp protocol in use. Methods A RTCIdentityErrorEvent being an Event, this event also implements these properties. There is no specific RTCIdentityErrorEvent method. Examples pc.onidpassertionerror = function( ev ) { ...
RTCPeerConnection.connectionState - Web APIs
"connecting" One or more of the ICE transports are currently in the process of establishing a connection; that is, their RTCIceConnectionState is either "checking" or "connected", and no transports are in the "failed" state. <<< Make this a link once I know where that will be documented "connected" Every ICE transport used by the connection is either in use (state "connected" or "
completed") or is closed (state "closed"); in addition, at least one transport is either "connected" or "
completed". "disconnected" At least one of the ICE transports for the connection is in the "disconnected" state and none of the other transports are in the state "failed", "connecting", or "checking". "failed" One or more of the ICE transports on the connection is in the "failed...
RTCPeerConnection.createAnswer() - Web APIs
n to create and return a new answer. In our promise handler, the returned answer is set as the description of the local end of the connection by calling setLocalDescription(). Once that succeeds, the answer is sent to the signaling server using whatever protocol you see fit. Promise.catch() is used to trap and handle errors. See Handling the invitation in Signaling and video calling to see the
complete code, in context, from which this snippet is derived; that will help you understand the signaling process and how answers work. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'createAnswer()' in that specification. Candidate Recommendation Initial definition. ...
RTCPeerConnection.createOffer() - Web APIs
emote system over the signaling channel; in this case, by using a custom function called sendToServer(). The implementation of the signaling server is independent from the WebRTC specification, so it doesn't matter how the offer is sent as long as both the caller and potential receiver are using the same one. Use Promise.catch() to trap and handle errors. See Signaling and video calling for the
complete example from which this snippet is derived; this will help you to understand how the signaling code here works. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'createOffer()' in that specification. Candidate Recommendation Initial definition. ...
RTCPeerConnection.iceConnectionState - Web APIs
hering of candidates is also still underway. "connected" A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use. "
completed" The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components. "failed" The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for som...
RTCPeerConnection.iceGatheringState - Web APIs
eturned using the RTCPeerConnection.iceGatheringState property. You can detect when this value changes by watching for an event of type icegatheringstatechange. Constant Description "new" The peer connection was just created and hasn't done any networking yet. "gathering" The ICE agent is in the process of gathering candidates for the connection. "
complete" The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to "gathering" to gather those candidates. Example var pc = new RTCPeerConnection(); var state = pc.iceGatheringState; Specifications Specification Status Comment ...
RTCPeerConnection.onicecandidate - Web APIs
ent object representing the icecandidate event. The function should deliver the ICE candidate, whose SDP can be found in the event's candidate property, to the remote peer through the signaling server. If the event's candidate property is null, ICE gathering has finished. This message should not be sent to the remote peer. When this happens, the connection's iceGatheringState has also changed to
complete. You don't need to watch for this explicitly; instead, if you need to sense the end of signaling, you should watch for a icegatheringstatechange event indicating that the ICE negotiation has transitioned to the
complete state. Example The example below, which is based on the code from the article Signaling and video calling, sets up a handler for icecandidate events to send the candidates to th...
RTCPeerConnection.onicegatheringstatechange - Web APIs
value of the iceGatheringState property each time it changes and changing the contents of a status display based on the new information. The status is simply presented as text in a <div> element: <div id="iceStatus"></div> The actual event handler looks like this: pc.onicegatheringstatechange = function() { let label = "Unknown"; switch(pc.iceGatheringState) { case "new": case "
complete": label = "Idle"; break; case "gathering": label = "Determining route"; break; } document.getElementById("iceStatus").innerHTML = label; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.onicegatheringstatechange' in that specification. Candidate R...
RTCPeerConnection.onnegotiationneeded - Web APIs
ation. This negotiation should be carried out as the offerer, because some session changes cannot be negotiated as the answerer. Most commonly, the negotiationneeded event is fired after a send track is added to the RTCPeerConnection. If the session is modified in a manner that requires negotiation while a negotiation is already in progress, no negotiationneeded event will fire until negotiation
completes, and only then if negotiation is still needed. Syntax RTCPeerConnection.onnegotiationneeded = eventHandler; Value This should be set to a function you provide which is passed a single parameter: an Event object containing the negotiationneeded event. There's no additional information provided in the event; anything you need, you can get by examining the properties of the RTCPeerConnection. ...
RTCPeerConnection.restartIce() - Web APIs
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 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(); Pa...
RTCPeerConnection.setConfiguration() - Web APIs
might call setConfiguration() to switch to new regional ICE servers, then initiate an ICE restart. You cannot change the identity information for a connection once it's already been set. Syntax RTCPeerConnection.setConfiguration(configuration); Parameters configuration An RTCConfiguration object which provides the options to be set. The changes are not additive; instead, the new values
completely replace the existing ones. Exceptions InvalidAccessError One or more of the URLs specified in configuration.iceServers is a TURN server, but
complete login information is not provided (that is, either the RTCIceServer.username or RTCIceServer.credentials is missing). This prevents successful login to the server. InvalidModificationError The configuration includes changed identity inform...
RTCPeerConnection.setLocalDescription() - Web APIs
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 is
complete. Only then does the agreed-upon configuration take effect. Syntax aPromise = RTCPeerConnection.setLocalDescription(sessionDescription); pc.setLocalDescription(sessionDescription, successCallback, errorCallback); Parameters sessionDescription Optional An RTCSessionDescriptionInit or RTCSessionDescription which specifies the configuration to be applied to the local end of the connection.
RTCRtpCapabilities - Web APIs
tely. If two sets of capabilities can be described as one, they will be. That means that, for instance, if there are two entries for the H.264 codec (as identified by the mimeType being "video/H264"), there are other values in the capabilities objects indicating how they're different in some way. The MIME type strings used by RTP differ from those used elsewhere. See RFC 3555, section 4 for the
complete IANA registry of these types. There are three special entries that should always be present, representing underlying components of the transport. Those components are: RED (REDundant Audio Data) The media type of an RED entry may vary due to there being several versions of it, but it will end with red, such as video/red or video/fwdred. The base RED standard can be found in RFC 2198. There ...
RTCRtpTransceiver.mid - Web APIs
negotiated media ID (mid) which the local and remote peers have agreed upon to uniquely identify the stream's pairing of sender and receiver. Syntax var mediaID = RTCRtpTransceiver.mid; Value A DOMString which uniquely identifies the pairing of source and destination of the transceiver's stream. Its value is taken from the media ID of the SDP m-line. This value is null if negotiation has not
completed. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpTransceiver.mid' in that specification. Candidate Recommendation ...
RTCSessionDescription - Web APIs
process it describes and of the SDP descriptor of the session. The process of negotiating a connection between two peers involves exchanging RTCSessionDescription objects back and forth, with each description suggesting one combination of connection configuration options that the sender of the description supports. Once the two peers agree upon a configuration for the connection, negotiation is
complete. Properties The RTCSessionDescription interface doesn't inherit any properties. RTCSessionDescription.type Read only An enum of type RTCSdpType describing the session description's type. RTCSessionDescription.sdp Read only A DOMString containing the SDP describing the session. Constants RTCSdpType This enum defines strings that describe the current state of the session descriptio...
RTCStatsIceCandidatePairState - Web APIs
coverable error occurred. frozen No check has been performed yet for this candidate pair, and performing the check is blocked until another check is successful. Once that check has succeeded, this pair will unfreeze and move into the waiting state. in-progress A check has been initiated for this pair, but the check's transaction is still in progress. succeeded A check for this pair has been
completed successfully. waiting This pair has not yet been checked, but the check can be performed as soon as this pair is the highest priority pair remaining in the waiting state. Specifications Specification Status Comment Identifiers for WebRTC's Statistics APIThe definition of 'RTCStatsIceCandidatePairState' in that specification. Candidate Recommendation Initial...
RTCTrackEvent - Web APIs
aStreamTrack which has been added to the connection. transceiver Read only The RTCRtpTransceiver being used by the new track. Track event types There is only one type of track event. track The track event is sent to the RTCPeerConnection when a new track has been added to the connection. By the time the track event is delivered to the RTCPeerConnection's ontrack handler, the new media has
completed its negotiation for a specific RTCRtpReceiver (which is specified by the event's receiver property). 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 e...
Range.compareNode() - Web APIs
d 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. 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. The following function can be used as replacement: function rangeCompareNode(range, node) { var nodeRange = node.ownerDocument.createRa...
ReadableStream.cancel() - Web APIs
The cancel() method of the ReadableStream interface cancels the associated stream. The supplied reason parameter 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(). 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 str...
ReadableStream.getReader() - Web APIs
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) { console.log("Stream
complete"); para.textContent = value; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and...
ReadableStream.pipeThrough() - Web APIs
eo decoder has encoded bytes written to it and uncompressed video frames read from it. options Optional The options that should be used when piping to the writable stream. Available options are: preventClose: If this is set to true, the source ReadableStream closing will no longer cause the destination WritableStream to be closed. The method will return a fulfilled promise once this process
completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventAbort: If this is set to true, errors in the source ReadableStream will no longer abort the destination WritableStream. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. preventCancel: If this i...
ReadableStream.tee() - Web APIs
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) { console.log("Stream
complete"); return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list.appendChild(listItem); // Read some more, and call this function again return reader.read().then(pro...
ReadableStream - Web APIs
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. ReadableStream.tee() The tee method tees this readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances. Each of those streams receives the same incoming data. ReadableStream[@@asyncIterator]() Alias of getIterator method. Examples In the following example, an artificial Res...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
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) { console.log("Stream
complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, an...
ReadableStreamDefaultReader.read() - Web APIs
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) { console.log("Stream
complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, an...
ReportingObserver - Web APIs
ator.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 listed. Specifications Specification Status Comment Reporting APIThe definition of ...
Reporting API - Web APIs
ator.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 listed. Specifications Specification Status Comment Reporting API spec ...
Request.cache - Web APIs
the cache. If there is no match, the browser will respond with a 504 Gateway timeout status. The "only-if-cached" mode can only be used if the request's mode is "same-origin". Cached redirects will be followed if the request's redirect property is "follow" and the redirects do not violate the "same-origin" mode. Example // Download a resource with cache busting, to bypass the cache //
completely. fetch("some.json", {cache: "no-store"}) .then(function(response) { /* consume the response */ }); // Download a resource with cache busting, but update the HTTP // cache with the downloaded resource. fetch("some.json", {cache: "reload"}) .then(function(response) { /* consume the response */ }); // Download a resource with cache busting when dealing with a // properly configured server th...
SVGDocument - Web APIs
). rootElement SVGSVGElement The root "svg" in the document hierarchy. title DOMString The title of a document as specified by the "title" sub-element of the "svg" root element (i.e., <svg><title>Here is the title</title>...</svg>) URL DOMString The
complete URI of the document. Methods The SVGDocument interface does not provide any specific methods. Browser compatibility Desktop Mobile Chrome Edge Firefox Internet Explorer Opera ...
SVGElement - Web APIs
ntAndElementEventHandlers, Element, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement, SVGElementInstance Events Listen to these events using addEventListener() or by assigning an event listener to the equivalent on... handler property defined on GlobalEventHandlers or WindowEventHandlers. abort Fired when page loading is stopped before an SVG element has been allowed to load
completely. Also available via the onabort property. error Fired when an SVG element does not load properly or when an error occurs during script execution. Also available via the onerror property. load Fires on an SVGElement when it is loaded in the browser. Also available via the onload property. resize Fired when an SVG document is being resized. Also available via the onresize property. scr...
Screen Capture API - Web APIs
e the mouse is in motion. MediaTrackConstraints.displaySurface A ConstrainDOMString indicating what type of display surface is to be captured. The value is one of application, browser, monitor, or window. MediaTrackConstraints.logicalSurface Indicates whether or not the video in the stream represents a logical display surface (that is, one which may not be entirely visible onscreen, or may be
completely offscreen). A value of true indicates a logical display surface is to be captured. MediaTrackSettings MediaTrackSettings.cursor A string which indicates whether or not the display surface currently being captured includes the mouse cursor, and if so, whether it's only visible while the mouse is in motion or if it's always visible. The value is one of always, motion, or never. MediaTrackS...
Screen Wake Lock API - Web APIs
een released'; }); Reacquiring a wake lock The following code reacquires the wake lock should the visibility of the document change and the wake lock is released. document.addEventListener('visibilitychange', () => { if (wakeLock !== null && document.visibilityState === 'visible') { wakeLock = await navigator.wakeLock.request('screen'); } }); Putting it all together You can find the
complete code on github here. The demo uses a button to acquire a wake lock and also release it, which in turn updates the UI. The UI also updates if the wake lock is released automatically for any reason. There's a checkbox which when checked, will automatically reacquire the wake lock if the document's visibility state changes and becomes visible again. Performance considerations Release the screen ...
SharedWorkerGlobalScope.onconnect - Web APIs
sage handler attached to it to handle messages coming in through the port, and its postMessage() method can be used to send messages back to the main thread using the worker. onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); } port.start(); } For a
complete running example, see our Basic shared worker example (run shared worker.) Note: The data property of the event object used to be null in Firefox. As of version 65 it is now initialized to an empty string, as per spec (bug 1508824). Specifications Specification Status Comment HTML Living StandardThe definition of 'onconnect' in that specification. Living Standard ...
SharedWorkerGlobalScope - Web APIs
The SharedWorkerGlobalScope object (the SharedWorker global scope) is accessible through the self keyword. Some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the JavaScript Reference. See the
complete list of functions available to workers. Properties This interface inherits properties from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements properties from WindowTimers, WindowBase64, and WindowEventHandlers. SharedWorkerGlobalScope.name Read only The name that the SharedWorker was (optionally) given when it was created using the SharedWorker() constructor. This is mainly useful for debugging purposes. SharedWorkerGlobalScope.applicationCache Rea...
SourceBuffer.abort() - Web APIs
end (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again. For example, consider this code: sourceBuffer.addEventListener('updateend', function (_) { ... }); sourceBuffer.appendBuffer(buf); Let's say that after the call to appendBuffer BUT before the updateend event fires (i.e. a buffer is being appended but the operation has not yet
completed) a user "scrubs" the video seeking to a new point in time. In this case you would want to manually call abort() on the source buffer to stop the decoding of the current buffer, then fetch and append the newly requested segment that relates to the current new position of the video. You can see something similar in action in Nick Desaulnier's bufferWhenNeeded demo -- in line 48, an event listene...
SourceBuffer.mode - Web APIs
be thrown when setting a new value for this property. Exception Explanation InvalidAccessError An attempt was made to set the value to segments when the initial value is sequence. InvalidStateError The SourceBuffer object is being updated (i.e. its SourceBuffer.updating property is currently true), the last media segment appended to this SourceBuffer is in
complete, or this SourceBuffer has been removed from the MediaSource. Example This snippet sets the sourceBuffer mode to 'sequence' if it is currently set to 'segments', thus setting the play order to the sequence in which media segments are appended. var curMode = sourceBuffer.mode; if (curMode == 'segments') { sourceBuffer.mode = 'sequence'; } Specifications Specification Status...
SourceBuffer - Web APIs
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. 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...
SpeechRecognitionEvent.emma - Web APIs
EMMA) -- XML -- representation of the result. Note: EMMA is defined in the specification EMMA: Extensible MultiModal Annotation markup language. You can see muliple EMMA examples in the spec. Syntax var myEmma = event.emma; Value A valid XML document. The exact contents can vary across user agents and recognition engines, but all supporting implementations will expose a valid XML document
complete with an EMMA namespace. If the speech recognition system does not supply EMMA data then the user agent will return null. Examples recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textContent = 'Result received: ' + color + '.'; bg.style.backgroundColor = color; console.log(event.emma); } ...
Storage - Web APIs
Specifications Specification Status Comment HTML Living StandardThe definition of 'Storage' in that specification. Living Standard ...
Storage API - Web APIs
as some Web Storage data as well as some IndexedDB data, but also has some free space left; its current usage hasn't yet reached its quota. Origin 2 has no data stored in it yet; it's just an empty box waiting for content. This origin, however, has a lower quota than the other two do. It may be a less-visited site, or one known to have lower data storage requirements. Origin 3's storage unit is
completely full; it's reached its quota and can't store any more data without some existing material being removed. User agents are likely to use various techniques to determine the quota for various origins. One of the most likely methods--one which the specification specifically encourages, in fact--would be to consider the popularity and/or usage levels of individual sites to determine what their quo...
Storage Access API - Web APIs
cookies and site storage that they would have access to when loaded in a first-party context. These cookie blocking policies are known to break embedded cross-origin content that requires access to its first-party storage. As an example, federated logins often require access to authentication cookies stored in first-party storage, and will require the user to sign in on each site separately (or
completely break) if those cookies are not available. In the case of breakage, site owners have often encouraged users to add their site as an exception or to disable the policy entirely. As a consequence, users who wish to continue to interact with embedded content are forced to greatly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites. The Stora...
SubtleCrypto - Web APIs
ic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. Errors in security system design and implementation can make the security of the system
completely ineffective. If you're not sure you know what you are doing, you probably shouldn't be using this API. Properties This interface doesn't inherit any properties, as it has no parent interface. Methods This interface doesn't inherit any methods, as it has no parent interface. SubtleCrypto.encrypt() Returns a Promise that fufills with the encrypted data corresponding to the clear text, a...
TextEncoder.prototype.encodeInto() - Web APIs
g 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. This may be less than string.length if uint8Array 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(). Observe. var encoder = new TextEncoder; function encodeIntoAtPosition(string, u8array, position) { return encoder.encodeInto(string, positi...
Using Touch Events - Web APIs
plify an application's input processing since a pointer represents input from any input device. Additionally, the pointer event types are very similar to mouse event types (for example, pointerdown pointerup) thus code to handle pointer events closely matches mouse handling code. The implementation status of pointer events in browsers is relatively high with Chrome, Firefox, IE11 and Edge having
complete implementations. Examples and demos The following documents describe how to use touch events and include example code: Touch Events Overview Implement Custom Gestures Introduction to Touch events in JavaScript Add touch screen support to your website (The easy way) Touch event demonstrations: Paint Program (by Rick Byers) Touch/pointer tests and demos (by Patrick H. Lauke) Communi...
TransitionEvent.initTransitionEvent() - Web APIs
tor, TransitionEvent(), to create a synthetic TransitionEvent Syntax transitionEvent.initTransitionEvent(typeArg, canBubbleArg, cancelableArg, transitionNameArg, elapsedTimeArg); Parameters typeArg Is a DOMString identifying the specific type of transition event that occurred. The following value is allowed: Value Meaning transitionend The transition
completed. canBubbleArg Is a Boolean flag indicating if the event can bubble (true) or not (false). cancelableArg Is a Boolean flag indicating if the event associated action can be avoided (true) or not (false). transitionNameArg Is a DOMString containing the name of the CSS property associated with the transition. This value is not affected by the transition-delay property. elapsedTimeA...
WEBGL_compressed_texture_etc - Web APIs
a part is encoded separately. ext.COMPRESSED_SRGB8_ETC2 Compresses sRGB8 data with no alpha channel. ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately. ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 Similar to RGB8_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.C...
WebGL2RenderingContext.clientWaitSync() - Web APIs
that the sync object was signaled when this method was called. gl.TIMEOUT_EXPIRED: Indicates that the timeout time passed and that the sync object did not become signaled. gl.CONDITION_SATISFIED: Indicates that the sync object was signaled before the timeout expired. gl.WAIT_FAILED: Indicates that an error occurred during the execution. Examples var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_
COMPLETE, 0); var status = gl.clientWaitSync(sync, 0, 0); Specifications Specification Status Comment WebGL 2.0The definition of 'clientWaitSync' in that specification. Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glClientWaitSync' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGL2RenderingContext.deleteSync() - Web APIs
The WebGL2RenderingContext.deleteSync() method of the WebGL 2 API deletes a given WebGLSync object. Syntax void gl.deleteSync(sync); Parameters sync A WebGLSync object to delete. Return value None. Examples gl must be a WebGL2RenderingContext. WebGLSync objects are not available in WebGL 1. var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_
COMPLETE, 0); // ... gl.deleteSync(sync); Specifications Specification Status Comment WebGL 2.0The definition of 'deleteSync' in that specification. Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glDeleteSync' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGL2RenderingContext.isSync() - Web APIs
s true if the passed object is a valid WebGLSync object. Syntax GLboolean gl.isSync(sync); Parameters sync A WebGLSync object to test. Return value A GLboolean indicating whether the given object is a valid WebGLSync object (true) or not (false). Examples gl must be a WebGL2RenderingContext. WebGLSync objects are not available in WebGL 1. var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_
COMPLETE, 0); // ... gl.isSync(sync); Specifications Specification Status Comment WebGL 2.0The definition of 'isSync' in that specification. Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glIsSync' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGL2RenderingContext.waitSync() - Web APIs
timeout); Parameters sync A WebGLSync object on which to wait on. flags A GLbitfield specifying a bitwise combination of flags controlling the flushing behavior. Must be 0 (exists for extensions only). timeout A GLint64 specifying a timeout the server should wait before continuing. Must be gl.TIMEOUT_IGNORED. Return value None. Examples var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_
COMPLETE, 0); gl.waitSync(sync, 0, gl.TIMEOUT_IGNORED); Specifications Specification Status Comment WebGL 2.0The definition of 'waitSync' in that specification. Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glWaitSync' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.getError() - Web APIs
command is ignored and the error flag is set. gl.INVALID_VALUE A numeric argument is out of range. The command is ignored and the error flag is set. gl.INVALID_OPERATION The specified command is not allowed for the current state. The command is ignored and the error flag is set. gl.INVALID_FRAMEBUFFER_OPERATION The currently bound framebuffer is not framebuffer
complete when trying to render to or to read from it. gl.OUT_OF_MEMORY Not enough memory is left to execute the command. gl.CONTEXT_LOST_WEBGL If the WebGL context is lost, this error is returned on the first call to getError. Afterwards and until the context has been restored, it returns gl.NO_ERROR. Examples gl.getError(); // gl.NO_ERROR (0) gl.enable(gl.FOOBAR); gl.getE...
WebGLRenderingContext.readPixels() - Web APIs
UM error is thrown if format or type is not an accepted value. A gl.INVALID_OPERATION error is thrown if type is gl.UNSIGNED_SHORT_5_6_5 and format is not gl.RGB. type is gl.UNSIGNED_SHORT_4_4_4_4 and format is not gl.RGBA. type does not match the typed array type of pixels. A gl.INVALID_FRAMEBUFFER_OPERATION error is thrown if the currently bound framebuffer is not framebuffer
complete. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels); console.log(pixels); // Uint8Array Specifications Specification Status Comment WebGL 1.0Th...
Animating objects with WebGL - Web APIs
to seconds and then subtract from it the last time to compute deltaTime which is the number of second since the last frame was rendered. At the end of drawscene we add the code to update squareRotation. squareRotation += deltaTime; This code uses the amount of time that's passed since the last time we updated the value of squareRotation to determine how far to rotate the square. View the
complete code | Open this demo on a new page << PreviousNext >> ...
Animating textures in WebGL - Web APIs
n = 0; // Draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltaTime = now - then; then = now; if (copyVideo) { updateTexture(gl, texture, video); } drawScene(gl, programInfo, buffers, texture, deltaTime); requestAnimationFrame(render); } requestAnimationFrame(render); That's all there is to it! View the
complete code | Open this demo on a new page ...
Creating 3D objects using WebGL - Web APIs
are 6 vertices per side, or 36 total vertices in the cube, even though many of them are duplicates. Finally, let's replace our variable squareRotation by cubeRotation and add a second rotation around the x axis: mat4.rotate(modelViewMatrix, modelViewMatrix, cubeRotation * .7, [0, 1, 0]); At this point, we now have an animated cube rotating, its six faces rather vividly colored. View the
complete code | Open this demo on a new page << PreviousNext >> ...
Getting started with WebGL - Web APIs
ext 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 have enough code that the WebGL context should successfully initialize, and you should wind up with a big black, empty box, ready and waiting to receive content. View the
complete code | Open this demo on a new page ...
Lighting in WebGL - Web APIs
For more advanced graphics, you'll want to implement per-pixel lighting, but this will get you headed in the right direction. You might also try experimenting with the direction of the light source, the colors of the light sources, and so forth. << Pre...
Using shaders to apply color in WebGL - Web APIs
gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color); gl.vertexAttribPointer( programInfo.attribLocations.vertexColor, numComponents, type, normalize, stride, offset); gl.enableVertexAttribArray( programInfo.attribLocations.vertexColor); } View the
complete code | Open this demo on a new page << PreviousNext >> ...
Using textures in WebGL - Web APIs
nt of texture unit 0. We then tell the shader that for the uSampler use texture unit 0. Lastly, add texture as a parameter to the drawScene() function, both where it is defined and where it is called. drawScene(gl, programInfo, buffers, texture, deltaTime); ... function drawScene(gl, programInfo, buffers, texture, deltaTime) { At this point, the rotating cube should be good to go. View the
complete code | Open this demo on a new page Cross-domain textures Loading of WebGL textures is subject to cross-domain access controls. In order for your content to load a texture from another domain, CORS approval needs to be be obtained. See HTTP access control for details on CORS. Because WebGL now requires textures to be loaded from secure contexts, you can't use textures loaded from file:/// URLs...
Using WebGL extensions - Web APIs
Note: In WebGL, unlike in other GL APIs, extensions are only available if explicitly requested. Canonical extension names, vendor prefixes and preferences Extensions may be supported by browser vendors before being officially ratified (but only when they are in draft stage). In that case, their name can be prefixed by the vendor prefix (MOZ_, WEBKIT_, etc.) or the extension is only available once a browser preference has been toggled. ...
WebGL model view projection - Web APIs
has caused that corner to extend outside clip space, thus causing the corner to be clipped away. See Perspective projection matrix below for an introduction to how to use more complex matrices to help control and prevent clipping. Exercise If that sounds a little abstract, open up the vertex shader and play around with the scale factor and watch how it shrinks vertices more towards the surface.
Completely change the w component values for really trippy representations of space. In the next section we'll take this step of copying Z into the w slot and turn it into a matrix. Simple projection The last step of filling in the w component can actually be accomplished with a simple matrix. Start with the identity matrix: var identity = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, ]; ...
A simple RTCDataChannel sample - Web APIs
connectButton.disabled = true; } function handleRemoteAddCandidateSuccess() { disconnectButton.disabled = false; } The only thing we do here is disable the "Connect" button when the local peer is connected and enable the "Disconnect" button when the remote peer connects. ...
Using DTMF with WebRTC - Web APIs
us and errors to the user. function log(msg) { logElement.innerHTML += msg + "<br/>"; } Result You can try this example here. When you click the "Dial" button, you should see a series of logging messages output, then the dialing will begin. If your browser plays the tones audibly as part of its user experience, you should hear them as they're transmitted. Once transmission of the tones is
complete, the connection is closed. You can click "Dial" again to reconnect and send the tones again. ...
WebRTC API - Web APIs
given contributing source (CSRC) including the most recent time a packet that the source contributed was played out. Events bufferedamountlow The amount of data currently buffered by the data channel--as indicated by its bufferedAmount property--has decreased to be at or below the channel's minimum buffered data size, as specified by bufferedAmountLowThreshold. close The data channel has
completed the closing process and is now in the closed state. Its underlying data transport is
completely closed at this point. You can be notified before closing
completes by watching for the closing event instead. closing The RTCDataChannel has transitioned to the closing state, indicating that it will be closed soon. You can detect the completion of the closing process by watching for the close event...
Web Video Text Tracks Format (WebVTT) - Web APIs
e to write: WEBVTT 3. Leave the second line blank, and on the third line the time for first cue is to be specified. For example, for a first cue starting at time 1 second and ending at 5 seconds, it is written as: 00:01.000 --> 00:05.000 On the next line you can write the caption for this cue which will run from 1st second to the 5th second, inclusive. Following the similar steps, a
complete WebVTT file for specific video or audio file can be made. CSS pseudo-classes CSS pseudo classes allow us to classify the type of object which we want to differentiate from other types of objects. It works in similar manner in WebVTT files as it works in HTML file. It is one of the good features supported by WebVTT is the localization and use of class elements which can be used in same way the...
Geometry and reference spaces in WebXR - Web APIs
an object is represented by some number of polygons made up of a number of points in space, applying the same transform to every point that makes up the object will apply that same transform to the entire object overall. Transforms can also be applied to vectors, since vectors are described using a coordinate value to define the direction and magnitude of the vector. On the origins of spaces A
complete XR-enhanced scene--whether virtual or augmented--is a composite of anywhere from one to potentially dozens of frames of reference. Each object within the scene that needs to directly exchange position and orientation data with the WebXR system needs to be able to report that information in a way that can be understood and adapted as needed to be comprehensible by other objects within the scene. ...
Movement, orientation, and motion: A WebXR example - Web APIs
, on the other hand, we call its end() method to stop the session. The last thing we do in this code is to check to see if xrSession is still non-NULL. If it is, we call sessionEnded(), the handler for the end event. This code should not be necessary, but there appears to be an issue in which at least some browsers are not correctly firing the end event. By running the event handler directly, we
complete the close-out process manually in this situation. Starting up the WebXR session The sessionStarted() function handles actually setting up and starting the session, by setting up event handlers, compiling and installing the GLSL code for the vertex and fragment shaders, and attaching the WebGL layer to the WebXR session before kicking off the rendering loop. It gets called as the handler for the...
WebXR performance guide - Web APIs
ect 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 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...
Rendering and the WebXR frame animation callback - Web APIs
t may not be able to accurately call your callback every frame and may have to skip frames. This is called dropping frames. This happens when the amount of time it takes to render a frame exceeds the time available between frames, whether because rendering was delayed or because rendering itself took more time than was available. In the diagram above, frame 3 is dropped because frame 2 did not
complete rendering until after frame 3 was due to be painted. The next frame drawn will be frame 4 instead. This is another reason the timestamp passed into your render callback is useful. By configuring the scene based on time rather than frame number, you can ensure your rendered frames match what's expected instead of falling behind. When a frame is dropped, the contents of the affected display area s...
Migrating from webkitAudioContext - Web APIs
er(), one which created an initially empty buffer, and one which took an existing ArrayBuffer containing encoded audio, decoded it and returned the result in the form of an AudioBuffer. The latter version of createBuffer() was potentially expensive, because it had to decode the audio buffer synchronously, and with the buffer being arbitrarily large, it could take a lot of time for this method to
complete its work, and no other part of your web page's code could execute in the mean time. Because of these problems, this version of the createBuffer() method has been removed, and you should use the asynchronous decodeAudioData() method instead. The example below shows old code which downloads an audio file over the network, and then decoded it using createBuffer(): var xhr = new XMLHttpRequest(); ...
Web Audio API - Web APIs
t to an AudioBuffer rather than to the device's speakers -- with the following. OfflineAudioContext The OfflineAudioContext interface is an AudioContext interface representing an audio-processing graph built from linked together AudioNodes. In contrast with a standard AudioContext, an OfflineAudioContext doesn't really render the audio but rather generates it, as fast as it can, in a buffer.
complete (event) The
complete event is fired when the rendering of an OfflineAudioContext is terminated. OfflineAudioCompletionEvent The OfflineAudioCompletionEvent represents events that occur when the processing of an OfflineAudioContext is terminated. The
complete event implements this interface. Obsolete interfaces The following interfaces were defined in old versions of the Web Audio API spec, ...
Web Crypto API - Web APIs
ic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle. Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. Errors in security system design and implementation can make the security of the system
completely ineffective. If you're not sure you know what you are doing, you probably shouldn't be using this API. Interfaces Some browsers implemented an interface called Crypto without having it well defined or being cryptographically sound. In order to avoid confusion, methods and properties of this interface have been removed from browsers implementing the Web Crypto API, and all Web Crypto API met...
Using the Web Speech API - Web APIs
d practice, and therefore recommended. SpeechRecognition.interimResults: Defines whether the speech recognition system should return interim results, or just final results. Final results are good enough for this simple demo. SpeechRecognition.maxAlternatives: Sets the number of alternative potential matches that should be returned per result. This can sometimes be useful, say if a result is not
completely clear and you want to display a list if alternatives for the user to choose the correct one from. But it is not needed for this simple demo, so we are just specifying one (which is actually the default anyway.) recognition.grammars = speechRecognitionList; recognition.continuous = false; recognition.lang = 'en-US'; recognition.interimResults = false; recognition.maxAlternatives = 1; Starting...
Functions and classes available to Web Workers - Web APIs
raphically strong random number generator and to cryptographic primitives. ? No support ? ? CustomEvent The CustomEvent interface represents events initialized by an application for any purpose. 48 (48) (Yes) (Yes) (Yes) DOMRequest and DOMCursor Respectively, these objects represents an ongoing operation (with listeners for reacting to the operation
completely successfully, or failing, for example), and an ongoing operation over a list of results. 41 (41) ? ? ? Fetch The Fetch spec provides an up-to-date definition of, and API for, fetching resources (e.g. across the network.) 39 (39) (mostly in 34 (34) behind pref, although a few features are later.) No support 42 41 behind pref 10.1 FileRe...
Using Web Workers - Web APIs
Array, Date, Math, and String WindowTimers.setTimeout and WindowTimers.setInterval The main thing you can't do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via DedicatedWorkerGlobalScope.postMessage, then actioning the changes from there. Note: For a
complete list of functions available to workers, see Functions and interfaces available to workers. Specifications Specification Status Comment HTML Living StandardThe definition of 'Web workers' in that specification. Living Standard ...
Window: DOMContentLoaded event - Web APIs
Bubbles Yes Cancelable Yes (although specified as a simple event that isn't cancelable) Interface Event Event handler property None The original target for this event is the Document that has loaded. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Document: DOMContentLoaded event. A different event, load, should be used only to detect a fully-loaded page. ...
Window: animationend event - Web APIs
If the animation aborts before reaching completion, such as if the element is removed from the DOM or the animation is removed from the element, the animationend event is not fired. Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationend The original target for this event is the Element that had the animation applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationend. ...
Window: animationiteration event - Web APIs
nimationiteration The original target for this event is the Element that had the animation applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationiteration. ...
window.cancelIdleCallback() - Web APIs
Summary The window.cancelIdleCallback() method cancels a callback previously scheduled with window.requestIdleCallback(). Syntax window.cancelIdleCallback(handle); Parameters handle The ID value returned by window.requestIdleCallback() when the callback was established. Return value undefined. Example See our
complete example in the article Cooperative Scheduling of Background Tasks API. Specifications Specification Status Comment Cooperative Scheduling of Background Tasks Proposed Recommendation 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 reques...
Window.locationbar - Web APIs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Various DOM Tests</title> <script> var visible = window.locationbar.visible; </script> </head> <body> <p>Various DOM Tests</p> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.locationbar' in that specification. ...
Window.menubar - Web APIs
The Window.menubar property returns the menubar object, whose visibility can be checked. Syntax objRef = window.menubar Example The following
complete HTML example demonstrates how the visible property of the menubar object is used. <html> <head> <title>Various DOM Tests</title> <script> var visible = window.menubar.visible; </script> </head> <body> <p>Various DOM Tests</p> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.menubar' in that specification. Living Standard HTML5The definition of 'Window.menubar' in that specification. Recommendation ...
Window.open() - Web APIs
ntrol of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true. How do I open a referenced resource of a link in a new tab? or in a specific tab? To open a resource in a new tab see Tabbed browser. Some Code snippets are available. If you are using the SDK, tabs are handled a bit differently K-meleon 1.1, a Mozilla-based browser, gives
complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to do that. Some advanced extensions also give Mozilla and Firefox a lot of power over how referenced resources are loaded. In a few years, the target property of the CSS3 hyperlink module may be implemented (if CSS3 Hyperlink module as it is right now is approved). And even if and when t...
Window.personalbar - Web APIs
Due to deprecation of enablePrivilege this functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17. ...
window.postMessage() - Web APIs
hat window, which might have been navigated to a different location since postMessage was called. source A reference to the window object that sent the message; you can use this to establish two-way communication between two windows with different origins. Security concerns If you do not expect to receive messages from other sites, do not add any event listeners for message events. This is a
completely foolproof way to avoid security problems. If you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, http://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, how...
window.requestIdleCallback() - Web APIs
options Optional Contains optional configuration parameters. Currently only one property is defined: timeout: If timeout is specified and has a positive value, and the callback has not already been called by the time timeout milliseconds have passed, the callback will be called during the next idle period, even if doing so risks causing a negative performance impact. Example See our
complete example in the article Cooperative Scheduling of Background Tasks API. Specifications Specification Status Comment Cooperative Scheduling of Background Tasks Proposed Recommendation 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...
Window.scrollbars - Web APIs
The Window.scrollbars property returns the scrollbars object, whose visibility can be checked. Syntax objRef = window.scrollbars Example The following
complete HTML example shows how the visible property of the scrollbars object is used. <!doctype html> <html> <head> <title>Various DOM Tests</title> <script> let visibleScrollbars = window.scrollbars.visible; </script> </head> <body> <p>Various DOM Tests</p> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.scrollbars' in that specification. Living Standard HTML5The definition of 'Window.scrollbars' in that specification. Recommendation ...
Window.setImmediate() - Web APIs
This method is not expected to become standard, and is only implemented by recent builds of Internet Explorer and Node.js 0.10+. It meets resistance both from Gecko (Firefox) and Webkit (Google/Apple). Syntax var immediateID = setImmediate(func, [param1, param2, ...]); var immediateID = setImmediate(func); where immediateID is the ID of the immediate which can be used later with window.clearImmediate. func is the function you wish to call. ...
Window.sidebar - Web APIs
kground. AddSearchProvider(descriptionURL) Dummy function; does nothing. See Autodiscovery of search plugins. addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) Obsolete since Gecko 44 Installs a search engine (Sherlock). Adding Sherlock search engines contains more details. Note: This was made obsolete in Firefox 44, and has been removed
completely in Firefox 59. IsSearchProviderInstalled(descriptionURL) Indicates if a specific search provider (OpenSearch) is installed. Specification Mozilla-specific. Not part of any standard. ...
Window.statusbar - Web APIs
The Window.statusbar property returns the statusbar object, whose visibility can be toggled in the window. Syntax objRef = window.statusbar Example The following
complete HTML example shows a way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Various DOM Tests</title> <script> // changing bar states on the existing window netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite"); window.statusbar.visible=!window.statusbar.visible; </script> </head> <body> <p>Various DOM Tests</p> </body> </html> Notes When you load the example page above, the browser display...
Window.toolbar - Web APIs
Due to deprecation of enablePrivilege this functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17. ...
Window: transitionend event - Web APIs
In the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated. Bubbles Yes Cancelable Yes Interface TransitionEvent Event handler property ontransitionend The transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. ...
WindowEventHandlers.onafterprint - Web APIs
fterprint property of the WindowEventHandlers mixin is the EventHandler for processing afterprint events for the current window. These events are raised after the user prints, or if they abort the print dialog. The beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has
completed. In general, you should prefer the use of an @media print CSS at-rule, but it may be necessary to use these events in some cases. Syntax window.addEventListener("afterprint", function(event) { ... }); window.onafterprint = function(event) { ... }; Specification Specification Status Comment HTML Living StandardThe definition of 'onafterprint' in that specification. ...
WindowEventHandlers.onbeforeprint - Web APIs
The onbeforeprint property of the WindowEventHandlers mixin is the EventHandler for processing beforeprint events for the current window. These events are raised before the print dialog window is opened. The beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has
completed. In general, you should prefer the use of an @media print CSS at-rule, but it may be necessary to use these events in some cases. Syntax window.addEventListener("beforeprint", function(event) { ... }); window.onbeforeprint = function(event) { ... }; Polyfill Safari does not implement these events, but you can create an equivalent result to the beforeprint event with window.matchMedia('print'). v...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
self with queued up XHR requests that won't necessarily return in order. In these cases, a recursive setTimeout() pattern is preferred: (function loop(){ setTimeout(function() { // Your logic here loop(); }, delay); })(); In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has
completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has
completed before recursing. Specifications Specification Status Comment HTML Living StandardThe definition of 'WindowOrWorkerGlobalScope.setInterval()' in that specification. Living Standard Method moved to the WindowOrWorkerGlobalScope ...
WindowOrWorkerGlobalScope - Web APIs
returns a Promise which resolves to an ImageBitmap. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. WindowOrWorkerGlobalScope.fetch() Starts the process of fetching a resource from the network. WindowOrWorkerGlobalScope.queueMicrotask() Enqueues a microtask--a short function to be executed after execution of the JavaScript code
completes and control isn't being returned to a JavaScript caller, but before handling callbacks and other tasks. This lets your code run without interfering with other, possibly higher priority, code, but before the browser runtime regains control, potentially depending upon the work you need to
complete. WindowOrWorkerGlobalScope.setInterval() Schedules a function to execute every time a given number ...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
Was the used SSL certificate valid and what are its details (owner, expiration, certificate authority, etc.)? Notes: This code requires elevated privileges to run; you can only call it from a browser extension or from a XULRunner application. The channel property becomes available only after the request is sent and the connection was established, that is, on readyState LOADED, INTERACTIVE or
COMPLETED. By setting the mozBackgroundRequest property of the request object and modifying the example appropriately, you can create your own alert dialog to handle SSL exceptions in your Firefox extension or XULRunner application. // Adapted from the patch for mozTCPSocket error reporting (bug 861196). const {Cc,Ci} = require("chrome"); function createTCPErrorFromFailedXHR(xhr) { let status = xhr.
Sending and Receiving Binary Data - Web APIs
ped arrays The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text". The response property will contain the entity 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. var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "arraybuffer"; oReq.onload = function (oEvent) { var arrayBuf...
XMLHttpRequest: load event - Web APIs
The load event is fired when an XMLHttpRequest transaction
completes successfully. Bubbles No Cancelable No Interface ProgressEvent Event handler property onload 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; margin: .5rem; } JS const xhrButtonSuc...
XMLHttpRequest: loadend event - Web APIs
The loadend event is fired when a request has
completed, whether successfully (after load) or unsuccessfully (after abort or error). Bubbles No Cancelable No Interface ProgressEvent Event handler property onloadend 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: ...
XMLHttpRequest.open() - Web APIs
d to use, such as "GET", "POST", "PUT", "DELETE", etc. Ignored for non-HTTP(S) URLs. url A DOMString representing the URL to send the request to. async Optional An optional Boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send() method does not return until the response is received. If true, notification of a
completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown. Note: Synchronous requests on the main thread can be easily disruptive to the user experience and should be avoided; in fact, many browsers have deprecated synchronous XHR support on the main thread entirely. Synchronous requests are permitted in Workers. user ...
XMLHttpRequest.response - Web APIs
est'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 described below. "" An empty responseType string is treated the same as "text", the default type. arraybuffer The response is a JavaScript Ar...
XMLHttpRequest.responseText - Web APIs
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 in
complete because the data has not been
completely received yet. You know the entire content has been received when the value of readyState becomes XMLHttpRequest.DONE (4), and status becomes 200 ("OK"). Exceptions InvalidStateError The XMLHttpRequest.responseType is not set to either the empty string or "text". Since the responseText property is only valid for text content, any other value is an err...
XMLHttpRequest.send() - Web APIs
null If no value is specified for the body, a default value of null is used. The best way to send binary content (e.g. in file uploads) is by using an ArrayBufferView or Blob in conjunction with the send() method. Return value undefined. Exceptions Exception Description InvalidStateError send() has already been invoked for the request, and/or the request is
complete. NetworkError The resource type to be fetched is a Blob, and the method is not GET. Example: GET var xhr = new XMLHttpRequest(); xhr.open('GET', '/server', true); xhr.onload = function () { // Request finished. Do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new Blob()); // xhr.send(new Int8Array()); // xhr.send(document); Example: POST var xhr...
XMLHttpRequest.upload - Web APIs
monitor the upload: Event Event listener Description loadstart onloadstart The upload has begun. progress onprogress Periodically delivered to indicate the amount of progress made so far. abort onabort The upload operation was aborted. error onerror The upload failed due to an error. load onload The upload
completed successfully. timeout ontimeout The upload timed out because a reply did not arrive within the time interval specified by the XMLHttpRequest.timeout. loadend onloadend The upload finished. This event does not differentiate between success or failure, and is sent at the end of the upload regardless of the outcome. Prior to this event, one of load, error, abort, or ti...
XMLHttpRequest - Web APIs
en(). XMLHttpRequest.sendAsBinary() A variant of the send() method that sends binary data. Events abort Fired when a request has been aborted, for example because the program called XMLHttpRequest.abort(). Also available via the onabort property. error Fired when the request encountered an error. Also available via the onerror property. load Fired when an XMLHttpRequest transaction
completes successfully. Also available via the onload property. loadend Fired when a request has
completed, whether successfully (after load) or unsuccessfully (after abort or error). Also available via the onloadend property. loadstart Fired when a request has started to load data. Also available via the onloadstart property. progress Fired periodically when a request receives more data. Also a...
XMLHttpRequestEventTarget - Web APIs
received by this object. XMLHttpRequestEventTarget.ontimeout Contains the function that is called if the event times out and the timeout event is received by this object; this only happens if a timeout has been previously established by setting the value of the XMLHttpRequest object's timeout attribute. XMLHttpRequestEventTarget.onloadend Contains the function that is called when the load is
completed, even if the request failed, and the loadend event is received by this object. Specifications Specification Status Comment XMLHttpRequest Living Standard WHATWG living standard ...
XRFrame.getViewerPose() - Web APIs
ntext 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 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. ...
XRInputSource.targetRayMode - Web APIs
Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSource.handedness' in that specification. Working Draft Initial definition. ...
XRInputSource.targetRaySpace - Web APIs
Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSource.targetRaySpace' in that specification. Working Draft Initial definition. ...
XRRenderState - Web APIs
viewer within which content should be rendered, the vertical field of view (for inline presentations), and a reference to the XRWebGLLayer being used as the target for rendering the scene prior to it being presented on the XR device's display or displays. When you apply changes using the XRSession method updateRenderState(), the specified changes take effect after the current animation frame has
completed, but before the next one begins. Properties The followiing properties are available on XRRenderState objects. baseLayer Read only The XRWebGLLayer from which the browser's compositing system obtains the image for the XR session. depthFar Read only The distance, in meters, of the far clip plane from the viewer. The far clip plane is the plane which is parallel to the display beyond ...
XRSession.end() - Web APIs
The end() method shuts down the XRSession on which it's called, returning a promise which resolves once the session has fully shut down. Syntax xrSession.end(); Parameters None. Return value A promise that resolves without a value after any platform-specific steps related to shutting down the session have
completed. You can use the promise to do things like update UI elements to reflect the shut down connection, trigger application shut down, or whatever else you might need to do. Example Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.end' in that specification. Working Draft Initial definition. ...
XRSession.onselect - Web APIs
This typically represents the pressing of a button or trigger, a hand gesture, or a spoken command. The select event is sent after tracking of the primary action begins, as announced by the selectstart event, and immediately before the tracking of the primary action ends, which is announced by the selectend event. To learn more about how WebXR actions work, see Inputs and input sources. ...
XRSession.onselectend - Web APIs
sort of selection by releasing a trigger, touchpad, or button, finishes speaking a command, or makes a hand gesture. For example, this might include releasing a button or joystick. Note: Not to be confused with XRSession.onselectstart and XRSession.onselect. Syntax XRSession.onselectend = function(event) { ... } Example XRSession.onselectend = function(event) { console.log("The user has
completed a primary action.") } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.onselectend' in that specification. Working Draft Initial definition. ...
XRSession.onselectstart - Web APIs
pad, or button, speaking a command, or making a hand gesture. For example, this might include pressing a button or moving a joystick. Note: Not to be confused with XRSession.onselect and XRSession.onselectend. Syntax XRSession.onselectstart = function(event) { ... } Example XRSession.onselectstart = function(event) { console.log("The user has started a primary action, but might not have
completed it.") } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.onselectstart' in that specification. Working Draft Initial definition. ...
XRSession.onsqueeze - Web APIs
These actions represent the user squeezing or gripping an object or controller. To learn more about how to use and handle WebXR controller inputs, see Inputs and input sources. Syntax xrSession.onsqueeze = squeezeHandlerFunction; Value A function to be invoked whenever the XRSession receives a squeeze event. ...
XRSession: select event - Web APIs
Examples of comon kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onselect 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. ...
XRSession: squeeze event - Web APIs
Examples of comon kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onsqueeze 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. ...
XRTargetRayMode - Web APIs
Specifications Specification Status Comment WebXR Device APIThe definition of 'XRTargetRayMode' in that specification. Working Draft Initial definition. ...
XRView - Web APIs
e 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 Initial definition. ...
XRWebGLLayer.framebuffer - Web APIs
asing, 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 in
complete and are not available for rendering other than while executing the requestAnimationFrame() callback. Attempting to clear, draw to, or read from the framebuffer results in a WebGL INVALID_FRAMEBUFFER_OPERATION error (0x0506). Calling checkFramebufferStatus() on the WebGL context from outside the animation frame callback causes the WebGL FRAMEBUFFER_UNSUPPORTED error (0x8CDD) to be reported. Opaqu...
Generating HTML - Web APIs
<span class="title"> <xsl:value-of select="/myNS:Article/myNS:Title"/> </span> </br> Authors: <br /> <xsl:apply-templates select="/myNS:Article/myNS:Authors/myNS:Author"/> </p> <p class="myBox"> <xsl:apply-templates select="//myNS:Body"/> </p> </body> </html> </xsl:template> ... Three more xsl:template's are needed to
complete the example. The first xsl:template is used for the author nodes, while the second one processes the body node. The third template has a general matching rule which will match any node and any attribute. It is needed in order to preserve the html elements in the XML document, since it matches all of them and copies them out into the HTML document the transformation creates. Figure 5 : Final 3 Te...
ARIA Screen Reader Implementors Guide - Accessibility
r example, automatically speak changes that are caused by the user's own input, as part of the context of that input. Allow global settings to turn off the presentation of live changes, present all live changes, use markup, or be "smart" (use heuristics) Details for Processing via Platform Accessibility APIs We hope browser manufacturers will work to provide consistent implementations. The most
complete implementation of live regions currently is in Firefox 3. Here is how WAI-ARIA live regions are exposed in Firefox 3. ...
Using ARIA: Roles, states, and properties - Accessibility
group heading img list listitem math none note presentation row rowgroup rowheader separator table term textbox toolbar tooltip Landmark roles banner complementary contentinfo form main navigation region search Live Region Roles alert log marquee status timer Window Roles alertdialog dialog States and properties Widget attributes aria-auto
complete aria-checked aria-current aria-disabled aria-errormessage aria-expanded aria-haspopup aria-hidden aria-invalid aria-label aria-level aria-modal aria-multiline aria-multiselectable aria-orientation aria-placeholder aria-pressed aria-readonly aria-required aria-selected aria-sort aria-valuemax aria-valuemin aria-valuenow aria-valuetext Live region attributes aria-live...
ARIA: article role - Accessibility
of using role="article", the <article> element can be used. <article> <h2>Heading of the segment</h2> <p>Paragraph for the segment.</p> <p>Another paragraph.</p> ... controls to interact with the article, share it, etc. ... </article> <article> ... </article> Description The article role denotes a section of a document, page, or site that, if it were standing on its own, could be viewed as a
complete document, page or site. The aim of a set of article sections is to indicate their relationship to one another. Articles are not considered a navigational landmark, but many assistive technologies that support landmarks also support a means to navigate among articles. They may also support indication of nesting relationships within articles. Articles can be nested, indicating that a nested artic...
ARIA: feed role - Accessibility
ith aria-label. If it does, see aria-labelledby. aria-labelledby If the feed has a visible title, the feed element has aria-labelledby referring to the element containing the title. If not, add an aria-label. aria-busy When busy, such as when articles are being added or removed from the feed, set aria-busy="true" during the update operation. Make sure it's reset to false when the operation is
complete or the changes may not become visible. article Each section of content in a feed should be contained in an <article> or element with role article. Each article should have an aria-labelledby referring to the article title or other child that can serve as a distinguishing label. Each article should preferably have aria-describedby referring to one or more elements inside the article that serve a...
ARIA: form role - Accessibility
t handler handles the event raised when the form is submitted. Anything that is not a <form> cannot be submitted, therefore you would have to use JavaScript to build an alternative data submission mechanism, for example with XMLHTTPRequest. Examples <div role="form" id="send-comment" aria-label="Add a comment"> <label for="username">Username</label> <input id="username" name="username" auto
complete="nickname" autocorrect="off" type="text"> <label for="email">Email</label> <input id="email" name="email" auto
complete="email" autocapitalize="off" autocorrect="off" spellcheck="false" type="text"> <label for="comment">Comment</label> <textarea id="comment" name="comment"></textarea> <input value="Comment" type="submit"> </div> It is recommended to use <form> instead. <form id="se...
WAI-ARIA Roles - Accessibility
imer role indicates to assistive technologies that an element is a numerical counter the amount of elapsed time from a starting point or the remaining time until an end point. Please claim the role you want to work on by adding your name after the role's name: (old pages are linked from https://developer.mozilla.org/docs/Web/Accessibility/ARIA/ARIA_Techniques). Ones for which the first draft is
completed have been removed from the below list. alertdialog banner Combobox Command Columnheader (Estelle) complementary composite Definition Directory Feed Gridcell (Eric E) Group input landmark Link - old page listbox Log - old page Marquee math menu menubar Menuitem Menuitemcheckbox Menuitemradio none note Option presentation Progressbar - old page Radio - old page r...
Basic form hints - Accessibility
d aria-required. Web developers typically use presentational strategies to indicate required or invalid fields. Assistive technologies (ATs) cannot necessarily infer this information from the presentation. ARIA provides attributes for indicating that form controls are required or invalid: The aria-required property can be applied to a form element, to indicate to an AT that it is required to
complete the form. The aria-invalid state can be programmatically applied, to indicate to an AT which data fields have incorrect data, so that the user knows they have entered invalid data. The example below shows a simple form with three fields. On lines 4 and 12, the aria-required attributes are set to true (in addition to the asterisks next to the labels), indicating that the name and email fields a...
ARIA - Accessibility
mentById("percent-loaded"); // Set its ARIA roles and states, // so that assistive technologies know what kind of widget it is. progressBar.setAttribute("role", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); // Create a function that can be called at any time to update // the value of the progress bar. function updateProgress(percent
Complete) { progressBar.setAttribute("aria-valuenow", percent
Complete); } Note that ARIA was invented after HTML4, so does not validate in HTML4 or its XHTML variants. However, the accessibility gains it provides far outweigh any technical invalidity. In HTML5, all ARIA attributes validate. The new landmark elements (<main>, <header>, <nav> etc) have built-in ARIA roles, so there is no need to duplic...
Accessibility Information for Web Authors - Accessibility
greater depth. In 30 days, you will know why your website should be accessible and how to make it more accessible. Automated Checking & Repair Cynthia says(TM) from HiSoftware(R) Company "Cynthia says(TM)" is a free online webpage accessibility validation service that is designed to identify errors in webpage related to Section 508 standards and/or the WCAG guidelines. It can perform a "
Complete Webpage Quality Check" for accessibility, privacy, searchability, metadata and even alt text attribute quality. The web author chooses the guidelines (as a basis for errors and warnings) to be used by "Cynthia says(TM)": Section 508, WCAG Priorities 1, 2 and 3. The output data report is displayed in a clear and well structured table where each and all checkpoints are identified and described (alo...
Operable - Accessibility
ponent is in focus. Understanding Character Key Shortcuts Note: Also see the WCAG description for Guideline 2.1 Keyboard Accessible: Make all functionality available from a keyboard. Guideline 2.2 -- Enough Time: Provide users enough time to read and use content This guideline covers situations in which functionality may have a time limit. For example, purchases sometimes need to be
completed within a time limit for security reasons. Success criteria How to conform to the criteria Practical resource 2.2.1 Timing is adjustable (A) For functionality with time limits (e.g. completing a hotel or flight booking often has a time limit), the user should be given controls to allow them to adjust, extend or turn off the time limit. Exceptions to this ...
-moz-image-rect - CSS: Cascading Style Sheets
e 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 one container style, then the styles for the four boxes that comprise the
complete image. The container looks like this: #container { width:267px; height:272px; top:100px; left:100px; position:absolute; font-size:16px; text-shadow:white 0px 0px 6px; text-align:center; } Then the four boxes defining the segments of the image are defined. Let's look at them one at a time. #box1 { background-image: -moz-image-rect(url(https://mdn.mozillademos.org/files/12053/...
-moz-outline-radius - CSS: Cascading Style Sheets
desired effect if you are viewing this in a browser other than Firefox. HTML <p>This element has a rounded outline!</p> CSS p { margin: 5px; border: 1px solid black; outline: dotted red; -moz-outline-radius: 12% 1em 25px; } Result Notes dotted or dashed radiused corners were rendered as solid until Firefox 50, bug 382721 Future versions of Gecko/Firefox may drop this property
completely. See bug 593717. Specifications Not part of any standard. ...
::backdrop - CSS: Cascading Style Sheets
is opened with dialog.showModal() */ dialog::backdrop { background: rgba(255,0,0,.25); } All full-screen elements are placed in a last-in/first out (LIFO) stack in the top layer, which is a special layer in the viewport which is always rendered last (and therefore on top) before drawing the viewport's contents to the screen. The ::backdrop pseudo-element makes it possible to obscure, style, or
completely hide everything located below the element when it's the topmost one in the top layer. ::backdrop neither inherits from nor is inherited by any other elements. No restrictions are made on what properties apply to this pseudo-element. Syntax ::backdrop Examples Styling the backdrop for full-screen video In this example, the backdrop style used when a video is shifted to full-screen mode is ...
:defined - CSS: Cascading Style Sheets
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 ch...
:nth-child() - CSS: Cascading Style Sheets
>Span</span> </div> <br> <h3><code>span:nth-of-type(2n+1)</code>, WITH an <code><em></code> among the child elements.</h3> <p>Children 1, 4, 6, and 8 are selected.<br> 3 isn't used in the counting or selected because it is an <code><em></code>, not a <code><span></code>, and <code>nth-of-type</code> only selects children of that type. ...
:target - CSS: Cascading Style Sheets
} /* Style italic elements within the target element */ p:target i { color: red; } Result Pure-CSS lightbox You can use the :target pseudo-class to create a lightbox without using any JavaScript. This technique relies on the ability of anchor links to point to elements that are initially hidden on the page. Once targeted, the CSS changes their display so that they are shown. Note: A more
complete pure-CSS lightbox based on the :target pseudo-class is available on GitHub (demo). HTML <ul> <li><a href="#example1">Open example #1</a></li> <li><a href="#example2">Open example #2</a></li> </ul> <div class="lightbox" id="example1"> <figure> <a href="#" class="close"></a> <figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec felis enim, placerat id ele...
unicode-range - CSS: Cascading Style Sheets
al syntax <unicode-range># Examples Using a different font for a single character In this example we create a simple HTML containing a single <div> element, including an ampersand, that we want to style with a different font. To make it obvious, we will use a sans-serif font, Helvetica, for the text, and a serif font, Times New Roman, for the ampersand. In the CSS we are in effect defining a
completely separate @font-face that only includes a single character in it, meaning that only this character will be styled with this font. We could also have done this by wrapping the ampersand in a <span> and applying a different font just to that, but that is an extra element and rule set. HTML <div>Me & You = Us</div> CSS @font-face { font-family: 'Ampersand'; src: local('Times New Roman'); ...
scripting - CSS: Cascading Style Sheets
initial-only Scripting is enabled during the initial page load, but not afterwards. enabled Scripting is supported and active on the current document. Examples HTML <p class="script-none">You do not have scripting available. ...
Detecting CSS animation support - CSS: Cascading Style Sheets
style collection. However, adding keyframes is trickier, since they're not defined using traditional CSS syntax (which makes them more flexible, but harder to define from script). To define our keyframes using JavaScript, we need to write them out as a CSS string. All we do is set up a keyframes variable, prefixing each attribute as it's constructed. This variable, once constructed, contains the
complete description of all the keyframes needed by our animation sequence. The next task is to actually add the keyframes to the page's CSS. The first thing to do is look to see if there's already a style sheet on the document; if so, we simply insert the keyframe description into that stylesheet; this is done in lines 13-15. If there isn't already a style sheet, a new <style> element is created, and i...
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
h are specific to block layout and box alignment, it should be read in conjunction with the main Box Alignment page, which details the common features of box alignment across layout methods. Note: At the time of writing (May 2018), there is no real support for the box alignment properties in block layout. This document details how the specification expects these properties to be implemented for
completeness, and is likely to change as the specification and browser implementations develop. align-content and justify-content The justify-content property does not apply to block containers or table cells. The align-content property applies to the block axis in order to align the contents of the box within its container. If a content distribution method such as space-between, space-around or space...
CSS Containment - CSS: Cascading Style Sheets
{ contain: paint; } Paint containment essentially clips the box to the padding edge of the principal box. There can be no visible overflow. The same things are true for paint containment as layout containment (see above). Another advantage is that if the containing box is offscreen, the browser does not need to paint its contained elements -- these must also be offscreen as they are contained
completely by that box. Size containment article { contain: size; } Size containment does not offer much in the way of performance optimizations when used on its own. However, it means that the size of the element's children cannot affect the size of the element itself -- its size is computed as if it had no children. If you turn on contain: size you need to also specify the size of the element you ...
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
n wrap in the container. In the next example I have ten items all with a flex-basis of 160px and the ability to grow and shrink. Once the first row gets to a point where there is not enough space to place another 160 pixel item, a new flex line is created for the items and so on until all of the items are placed. As the items can grow, they will expand larger than 160 px in order to fill each row
completely. If there is only one item on the final line it will stretch to fill the entire line. We can see the same thing happening with columns. The container will need to have a height in order that the items will start wrapping and creating new columns, and items will stretch taller to fill each column
completely. Wrapping and flex-direction Wrapping works as you might expect when combined with...
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
Instead, you will need to use a CSS pre-processor to make the most of the following. However, CSS pre-processors simply generate valid CSS, so the techniques used below can be written in pure CSS instead, if preferred. Flexbox containers Using the di...
OpenType font features guide - CSS: Cascading Style Sheets
rding to the specification you can either supply just the 4-character feature code or supply a 1 following the code (for enabling that feature) or a 0 (zero) to disable it. This is helpful if you have a feature like ligatures enabled by default but you would like to turn them off, like so: .no-ligatures { font-feature-settings: "liga" 0, "dlig" 0; } More on font-feature-settings codes 'The
Complete CSS Demo for OpenType Features' (can't vouch for the truth of the name, but it's pretty big) A list of OpenType features on Wikipedia Using CSS feature detection for implementation Since not all properties are evenly implemented, it's good practice to set up your CSS using feature detection to utilize the correct properties, with font-feature-settings as the fallback. For example, small caps...
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
tem3 { grid-area: c; } .item4 { grid-area: d; } <div class="wrapper"> <div class="item1">Item 1</div> <div class="item2">Item 2</div> <div class="item3">Item 3</div> <div class="item4">Item 4</div> </div> Keep in mind that once you set align-items: start, the height of each child <div> will be determined by the contents of the <div>. This is in contrast to omitting align-items
completely, in which case the height of each <div> stretches to fill its grid area. The align-items property sets the align-self property for all of the child grid items. This means that you can set the property individually, by using align-self on a grid item. In this next example, I am using the align-self property, to demonstrate the different alignment values. The first area, is showing the default ...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
For some things, for example, where a grid contains text content, this switching may be exactly what you want. For other usage it may not. The strange order of values in the grid-area property You can use the grid-area property to specify all four lines of a grid area as one value. When people first encounter this, they are often surprised that the values do not follow the s...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
display: flex; flex-direction: column; } .listing .cta { margin-top: auto; border-top: 1px solid #ffe066; padding: 10px; text-align: center; } .listing .body { padding: 10px; } This is really one of the key reasons I would use flexbox rather than grid, if I am just aligning or distributing something in a single dimension, that's a flexbox use case. This is all looking fairly
complete now, however we sometimes have these cards which contain far more content than the others. It might be nice to cause those to span two tracks, and then they won't be so tall. I have a class of wide on my larger item, and I add a rule grid-column-end with a value of span 2. Now when grid encounters this item, it will assign it two tracks. At some breakpoints, this means that we'll get a gap in the...
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
In this guide, I will explain how a grid fits together with other techniques you may already be using. Grid and flexbox The basic difference between CSS Grid Layout and CSS Flexbox Layout is that flexbox was designed for layout in one dimension - either a row or a column. Grid was designed for two-dimensional layout - rows, and columns at the same time. The two specifications share some common features, however, and if you have already learned how to use flexbox, the similarities should help you get to grips with Grid. One-dimensional vs. ...
Consistent list indentation - CSS: Cascading Style Sheets
there's no reason why you have to stick with pixel-based indentation. If you want to reset lists to have no indentation, then you still have to zero out both padding and margin: ul {margin-left: 0; padding-left: 0;} Remember, though, that in so doing, you'll have the bullets hanging outside the list and its parent element. If the parent is the body, there's a strong chance your bullets will be
completely outside the browser window, and thus will not be visible. Conclusion In the end, we can see that none of the browsers mentioned in this article is right or wrong about how they lay out lists. They use different default styles, and that's where the problems creep in. By making sure you style both the left padding and left margin of lists, you can find much greater cross-browser consistency in ...
Stacking with floated blocks - CSS: Cascading Style Sheets
This happens according to standard float behaviour. This behavior can be shown with an added rule to the above list: The background and borders of the root element Descendant non-positioned blocks, in order of appearance in the HTML Floating blocks Descendant non-positioned inline elements Descendant positioned elements, in orde...
Shapes From Images - CSS: Cascading Style Sheets
same value as the value of shape-outside. The linear gradient goes from purple to transparent, so by changing the value of shape-image-threshold I can decide how transparent the pixels need to be that create my shape. You can play with that value in the example below to see how the diagonal line will move across the shape depending on that value. You could also try removing the background image
completely, thus using the gradient purely to create the shape and not displaying it on the page at all. In this next example I am using a radial gradient with an ellipse, once again using a transparent part of the gradient to create the shape. You can experiment directly in these live examples, to see how changing the gradient will change the path of your shape. ...
CSS Tutorials - CSS: Cascading Style Sheets
Learning CSS may be a daunting task. In order to help you, we have written numerous tutorials about CSS. Some are aimed at
complete beginners, while others present complex features to be used by more experienced users. This page lists them all, with a short description. They are grouped by complexity so that you can choose the most appropriate for your level. Editor's note: We should look at using "difficulty level" tags on the tutorial/guide pages so that difficulty-based lists can be automatically built. Beginner-level CSS tutorials Getting started This guide is aimed at
complete beginners: You haven't written one single line of CSS? -- this is for you. It explains the fundamental concepts of the language and guides you in writing basic stylesheets. Using multiple backgrounds ...
animation-duration - CSS: Cascading Style Sheets
The animation-duration CSS property sets the length of time that an animation takes to
complete one cycle. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. It is often convenient to use the shorthand property animation to set all animation properties at once. Syntax /* Single animation */ animation-duration: 6s; animation-duration: 120ms; /* Multiple animations */ animation-duration: 1.64s, 15.22s; animation-duration: 10s, 35s, 230ms; Values <time> The time that an animation takes to
complete one cycle. This may be specified in either seconds (s) or milliseconds (ms). The value must be positive or zero and the u...
animation-timing-function - CSS: Cascading Style Sheets
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 animation, slowing back down at the end. linear Equal to cubic-bezier(0.0, 0.0, 1.0, 1.0), animates at an even speed. ease-in Equal to cubic-bezier(0.42, 0, 1.0, 1.0), starts off slowly, with the speed of the transition of the animating properting increasing until
complete. ease-out Equal to cubic-bezier(0, 0, 0.58, 1.0), starts quickly, slowing down the animation continues. o ease-in-out Equal to cubic-bezier(0.42, 0, 0.58, 1.0), with the animating properties slowly transitioning, speeding up, and then slowing down again. cubic-bezier(p1, p2, p3, p4) An author defined cubic-bezier curve, where the p1 and p3 values must be in the range of 0 to 1. steps(n, <j...
border-color - CSS: Cascading Style Sheets
, <alpha-value>? ) | rgba( <number>#{3} , <alpha-value>? )<hsl()> = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
border-image-slice - CSS: Cascading Style Sheets
Formal syntax <number-percentage>{1,4} && fill?where <number-percentage> = <number> | <percentage> Examples Adjustable border width and slice The folowing example shows a simple <div> with a border image set on it. The source image for the borders is as follows: The diamonds are 30px across, therefore setting 30 pixels as the value for both border-width and border-image-slice will get you
complete and fairly crisp diamonds in your border: border-width: 30px; border-image-slice: 30; These are the default values we have used in this example. However, we have also provided two sliders to allow you to dynamically change the values of the above two properties, allowing you to appreciate the effect they have: border-image-slice Changes the size of the image slice sampled for use in each borde...
clip-path - CSS: Cascading Style Sheets
ding-box circle(25% at 25% 25%); } .shape9 { clip-path: content-box circle(25% at 25% 25%); } .defs { width: 0; height: 0; margin: 0; } pre { margin-bottom: 0; } svg { margin: 1em; font-family: sans-serif; width: 192px; height: 192px; } svg rect { stroke: pink; stroke-width: 16px; } svg text { fill: pink; text-anchor: middle; } svg text.em { font-style: italic; }
Complete example HTML <img id="clipped" src="https://udn.realityripple.com/samples/db/4f9fbd7dfb.svg" alt="MDN logo"> <svg height="0" width="0"> <defs> <clipPath id="cross"> <rect y="110" x="137" width="90" height="90"/> <rect x="0" y="110" width="90" height="90"/> <rect x="137" y="0" width="90" height="90"/> <rect x="0" y="0" width="90" height="90"/> </clipPath> ...
contain - CSS: Cascading Style Sheets
ement and its descendants, those effects don't escape the containing element. Note that this value is marked "at-risk" in the spec and may not be supported everywhere. paint Indicates that descendants of the element don't display outside its bounds. If the containing box is offscreen, the browser does not need to paint its contained elements -- these must also be offscreen as they are contained
completely by that box. And if a descendant overflows the containing element's bounds, then that descendant will be clipped to the containing element's border-box. Formal definition Initial valuenoneApplies toall elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax none | strict | content | [ size | layout | style | paint ] Examples Simple layout The markup below consi...
brightness() - CSS: Cascading Style Sheets
itory. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax brightness(amount) Parameters amount The brightness of the result, specified as a <number> or a <percentage>. 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. The lacuna value for interpolation is 1. Examples Setting brightness using numbers and percentages brightness(0%) /*
Completely black */ brightness(0.4) /* 40% brightness */ brightness(1) /* No effect */ brightness(200%) /* Double brightness */ Specifications Specification Status Filter Effects Module ...
contrast() - CSS: Cascading Style Sheets
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 contrast(amount) Parameters amount The contrast of the result, specified as a <number> or a <percentage>. A value under 100% decreases the contrast, while a value over 100% increases it. A value of 0% will create an image that is
completely gray, while a value of 100% leaves the input unchanged. The lacuna value for interpolation is 1. Examples Setting contrast using numbers and percentages contrast(0) /*
Completely gray */ contrast(65%) /* 65% contrast */ contrast(1) /* No effect */ contrast(200%) /* Double contrast */ Specifications Specification Status Filter Effects Module Level 1The d...
grayscale() - CSS: Cascading Style Sheets
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. Syntax grayscale(amount) Parameters amount The amount of the conversion, specified as a <number> or a <percentage>. A value of 100% is
completely grayscale, while a value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. Default value when omitted is 1. The initial value for interpolation is 0. Examples grayscale(0) /* No effect */ grayscale(.7) /* 70% grayscale */ grayscale(100%) /*
Completely grayscale */ Specifications Specification Status Filter Ef...
invert() - CSS: Cascading Style Sheets
ts 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. Syntax invert(amount) Parameters amount The amount of the conversion, specified as a <number> or a <percentage>. A value of 100% is
completely inverted, while a value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. The lacuna value for interpolation is 0. Examples invert(0) /* No effect */ invert(.6) /* 60% inversion */ invert(100%) /*
Completely inverted */ Specifications Specification Status Filter Effects Module Level 1The definition of 'invert...
opacity() - CSS: Cascading Style Sheets
se clone https://github.com/mdn/interactive-examples and send us a pull request. Note: This function is similar to the more established opacity property. The difference is that with filters, some browsers provide hardware acceleration for better performance. Syntax opacity(amount) Parameters amount The amount of the conversion, specified as a <number> or a <percentage>. A value of 0% is
completely transparent, while a value of 100% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. The lacuna value for interpolation is 1. Examples opacity(0%) /*
Completely transparent */ opacity(50%) /* 50% transparent */ opacity(1) /* No effect */ Specifications Specification Status Filter Effects Module Level 1The definition ...
saturate() - CSS: Cascading Style Sheets
in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax saturate(amount) Parameters amount The amount of the conversion, specified as a <number> or a <percentage>. A value under 100% desaturates the image, while a value over 100% super-saturates it. A value of 0% is
completely unsaturated, while a value of 100% leaves the input unchanged. The lacuna value for interpolation is 1. Examples saturate(0) /*
Completely unsaturated */ saturate(.4) /* 40% saturated */ saturate(100%) /* No effect */ saturate(200%) /* Double saturation */ Specifications Specification Status Filter Effects Module Level 1The definition of 'saturate()' in th...
sepia() - CSS: Cascading Style Sheets
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. Syntax sepia(amount) Parameters amount The amount of the conversion, specified as a <number> or a <percentage>. A value of 100% is
completely sepia, while a value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. The lacuna value for interpolation is 0. Examples sepia(0) /* No effect */ sepia(.65) /* 65% sepia */ sepia(100%) /*
Completely sepia */ Specifications Specification Status Filter Effects Module Level 1The definition of 'sepia()' in that sp...
font-family - CSS: Cascading Style Sheets
, "Trebuchet MS", "Liberation Sans", "Nimbus Sans L", sans-serif. monospace All glyphs have the same fixed width. E.g. "Fira Mono", "DejaVu Sans Mono", Menlo, Consolas, "Liberation Mono", Monaco, "Lucida Console", monospace. cursive Glyphs in cursive fonts generally have either joining strokes or other cursive characteristics beyond those of italic typefaces. The glyphs are partially or
completely connected, and the result looks more like handwritten pen or brush writing than printed letterwork. E.g. "Brush Script MT", "Brush Script Std", "Lucida Calligraphy", "Lucida Handwriting", "Apple Chancery", cursive. fantasy Fantasy fonts are primarily decorative fonts that contain playful representations of characters. E.g. Papyrus, Herculanum, Party LET, Curlz MT, Harrington, fantasy. ...
object-fit - CSS: Cascading Style Sheets
letterboxed" if its aspect ratio does not match the aspect ratio of the box. cover The replaced content is sized to maintain its aspect ratio while filling the element's entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit. fill The replaced content is sized to fill the element's content box. The entire object will
completely fill the box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be stretched to fit. none The replaced content is not resized. scale-down The content is sized as if none or contain were specified, whichever would result in a smaller concrete object size. Formal definition Initial valuefillApplies toreplaced elementsInheritednoComputed valueas s...
text-overflow - CSS: Cascading Style Sheets
space to display the ellipsis, it is clipped. <string> The <string> to be used to represent clipped text. The string is displayed inside the content area, shortening the size of the displayed text. If there is not enough space to display the string itself, it is clipped. fade This keyword clips the overflowing inline content and applies a fade-out effect near the edge of the line box with
complete transparency at the edge. fade( <length> | <percentage> ) This function clips the overflowing inline content and applies a fade-out effect near the edge of the line box with
complete transparency at the edge. The argument determines the distance over which the fade effect is applied. The <percentage> is resolved against the width of the line box. Values lower than 0 are clipped to 0. Values ...
transition-duration - CSS: Cascading Style Sheets
By default, the value is 0s, meaning that no animation will occur. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. You may specify multiple durations; each duration will be applied to the corresponding property as specified by the transition-property property, which acts as a master list. If there are fewer durations specified than in the master list, the user agent repeat the list of durations. ...
transition-timing-function - CSS: Cascading Style Sheets
ber 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 Equal to cubic-bezier(0.0, 0.0, 1.0, 1.0), transitions at an even speed. ease-in Equal to cubic-bezier(0.42, 0, 1.0, 1.0), starts off slowly, with the transition speed increasing until
complete. ease-out Equal to cubic-bezier(0, 0, 0.58, 1.0), starts transitioning quickly, slowing down the transition continues. o ease-in-out Equal to cubic-bezier(0.42, 0, 0.58, 1.0), starts transitioning slowly, speeds up, and then slows down again. cubic-bezier(p1, p2, p3, p4) An author defined cubic-Bezier curve, where the p1 and p3 values must be in the range of 0 to 1. steps( n, <jumpt...
writing-mode - CSS: Cascading Style Sheets
Candidate Recommendation Add sideways-lr and sideways-rl CSS Writing Modes Module Level 3The definition of 'writing-mode' in that specification. Proposed Recommendation Initial definition ...
WAI ARIA Live Regions/API Support - Developer guides
What types of mutations are possibly relevant? See [#Events_fired_for_web_page_mutations the mutation events list] to match the type of event with this attribute's value, to determine whether the author believed the event should be presented to the user or not. aria-relevant on ancestor element container-busy "true" | "false" | "error" "false" The current changes are not yet
complete. A state change event for the A11y API's BUSY state will be fired on the container object currently marked as BUSY, once it is no longer BUSY. This is especially important in atomic regions. The entire atomic region should be presented once when it is finally no longer BUSY. aria-busy on ancestor element container-atomic "true" | "false" "false" Is this change inside a region...
Guide to Web APIs - Developer guides
The web includes a wide array of APIs that can be used from JavaScript to build increasingly more powerful and capable applications, running either on the web, locally, or through technology such as Node.js, on a server. On this page you'll find a
complete list of all of the APIs provided by the full web technology stack. Web APIs from A to Z AAmbient Light EventsBBackground TasksBattery API BeaconBluetooth APIBroadcast Channel APICCSS Counter StylesCSS Font Loading API CSSOMCanvas APIChannel Messaging APIConsole APICredential Management APIDDOMEEncoding APIEncrypted Media ExtensionsFFetch APIFile System API Frame Timing APIFullscreen APIGGamepad API Geolocation APIHHTML Drag and Drop APIHigh Resolution TimeHistory APIIImage Capture APIIndexedDBIntersection Observer APILLong Tasks...
Web Audio playbackRate explained - Developer guides
t's starting by looking at a brief example of playbackRate usage: var myAudio = document.createElement('audio'); myAudio.setAttribute('src','audiofile.mp3'); myAudio.playbackRate = 0.5; Here we create an <audio> element, and set its src to a file of our choice. ...
Challenge solutions - Developer guides
ns. The sections below correspond to the titles of the tutorial sections. Why use CSS Colors Challenge Without looking up a reference, find five more color names that work in your stylesheet. Solution CSS supports common color names like orange, yellow, blue, green, or black. It also supports some more exotic color names like chartreuse, fuschia, or burlywood. See CSS Color value for a
complete list as well as other ways of specifying colors. How CSS works DOM inspector Challenge In DOMi, click on a STRONG node. Use DOMi's right-hand pane to find out where the node's color is set to red, and where its appearance is made bolder than normal text. Solution In the menu above the right-hand pane, choose CSS Rules. You see two items listed, one that references an internal resource a...
Index - Developer guides
ics, such as images.These articles provide insight into how you can accomplish this. 28 Guide to Web APIs API, Guide, Landing, Web The web includes a wide array of APIs that can be used from JavaScript to build increasingly more powerful and capable applications, running either on the web, locally, or through technology such as Node.js, on a server. On this page you'll find a
complete list of all of the APIs provided by the full web technology stack. 29 Index Guide, Index Found 31 pages: 30 Introduction to Web development Beginner, CSS, CodingScripting, Development, HTML, JavaScript, Web Whether you're just getting started with Web development, or are just expanding your horizons into new realms of Web awesomeness, the links here shoul...
Introduction to Web development - Developer guides
y. HTML beginners tutorial -- a tutorial and exercise that recap and take you through the basics you've learned above. HTML elements reference guide -- a comprehensive guide to HTML elements with details on how browsers support them CSS Getting started with CSS -- an absolute beginners guide to CSS covers basic concepts and fundamentals CSS reference guide -- a
complete guide to CSS with details on the level of Gecko/Firefox support for each. The W3C introduction to styling with CSS -- a brief guide to styling web pages for beginners. Common CSS questions -- common questions and answers for beginners Intermediate CSS concepts -- grouping, pseudo-classes and more. JavaScript Beginning Getting started with JavaScript -- wha...
A hybrid approach - Developer guides
ontent on the server side, but still allows our layouts to benefit from the flexibility and future-readiness of responsive design. Using user-agent detection specifically for content and not layout also allows you to have a single URL for each piece of content, so that the content can adapt its layout to the user's browser. This is generally thought to be a good thing. Instead of maintaining two
completely different sites, we simply redirect users to pages for the content they care about. And since the design is responsive, you know that each page looks as good as possible on the user's screen. We can also address some of the performance problems with responsive design by incorporating server-side techniques. For example, an often-criticized point about responsive web design is that full-resolut...
HTML attribute: accept - HTML: Hypertext Markup Language
".png, .jpg, .jpeg" -- Accept PNG or JPEG files. accept="image/*" -- Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.) accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" -- accept anything that smells like an MS Word document. ...
disabled - HTML: Hypertext Markup Language
his Boolean attribute prevents the user from interacting with the button. If this attribute isn't set, the button can still be disabled from a containing element, for example <fieldset>; if there is no containing element with the disabled attribute set, then the button is enabled. Firefox will, unlike other browsers, persist the dynamic disabled state of a <button> across page loads. Use the auto
complete attribute to control this feature. Attribute interactions The difference between disabled and readonly is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled. Because a disabled field cannot have it's value changed, required does n...
HTML attribute: multiple - HTML: Hypertext Markup Language
, but support varies between browsers. Specifications Specification Status Comment HTML Living StandardThe definition of 'multiple attribute' in that specification. Living Standard HTML5The definition of 'multiple attribute' in that specification. Recommendation Accessibility concerns Provide instructions to help users understand how to
complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the multiple attribute, inform the user that multiple values are allowed and provide directions on how to provide multiple values, such as "separate email addresses with a comma." Setting size="1" on a multiple select can make it appear as a single select ...
HTML attribute: step - HTML: Hypertext Markup Language
idation and stepMismatch for more information. Specifications Specification Status Comment HTML Living StandardThe definition of 'step attribute' in that specification. Living Standard HTML5The definition of 'step attribute' in that specification. Recommendation Accessibility concerns Provide instructions to help users understand how to
complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the min attribute, ensure this minimum requirement is understood by the user. Providing instructions within the <label> may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using aria-l...
HTML attribute reference - HTML: Hypertext Markup Language
alignment of the element. allow <iframe> Specifies a feature-policy for the iframe. alt <applet>, <area>, <img>, <input> Alternative text in case an image can't be displayed. async <script> Executes the script asynchronously. autocapitalize Global attribute Sets whether input is automatically capitalized when entered by user auto
complete <form>, <input>, <select>, <textarea> Indicates whether controls in this form can by default have their values automatically
completed by the browser. autofocus <button>, <input>, <keygen>, <select>, <textarea> The element should be automatically focused after the page loaded. autoplay <audio>, <video> The audio or video should play as soon as possible. ...
Block-level elements - HTML: Hypertext Markup Language
complex set of content categories. While the "inline" category roughly corresponds to the category of phrasing content, the "block-level" category doesn't directly correspond to any HTML5 content category, but "block-level" and "inline" elements combined together correspond to the flow content in HTML5. There are also additional categories, e.g. interactive content. Elements The following is a
complete list of all HTML "block-level" elements (although "block-level" is not technically defined for elements that are new in HTML5). <address> Contact information. <article> Article content. <aside> Aside content. <blockquote> Long ("block") quotation. <details> Disclosure widget. <dialog> Dialog box. <dd> Describes a term in a description list. <div> Document division. <dl> Descr...
Date and time formats used in HTML - HTML: Hypertext Markup Language
Years prior to the year 1 C.E. are not supported, so HTML doesn't support years 1 B.C.E. (1 B.C.) or earlier. A year is normally 365 days long, except during leap years. Leap years A leap year is any year which is divisible by 400 or the year is divisible by 4 but not by 100. Although the calendar year is normally 365 days long, it actually takes the planet Earth approximately 365.2422 days to
complete a single orbit around the sun. Leap years help to adjust the calendar to keep it synchronized with the actual position of the planet in its orbit. Adding a day to the year every four years essentially makes the average year 365.25 days long, which is close to correct. The adjustments to the algorithm (taking a leap year when the year can be divided by 400, and skipping leap years when the year i...
<basefont> - HTML: Hypertext Markup Language
rs, never implemented it in the same way: practically, using it has always brought indeterminate results. The <basefont> element was deprecated in the standard at the same time as all elements related to styling only. Starting with HTML 4, HTML does not convey styling information anymore (outside the <style> element or the style attribute of each element). In HTML5, this element has been removed
completely. For any new web development, styling should be written using CSS only. The former behavior of the <font> element can be achieved, and even better controlled using the CSS Fonts properties. DOM interface This element implements the HTMLBaseFontElement interface. Example <basefont color="#FF0000" face="Helvetica" size="+2" /> ...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
ase clone https://github.com/mdn/interactive-examples and send us a pull request. Each embedded browsing context has its own session history and document. The browsing context that embeds the others is called the parent browsing context. The topmost browsing context -- the one with no parent -- is usually the browser window, represented by the Window object. Because each browsing context is a
complete document environment, every <iframe> in a page requires increased memory and other computing resources. While theoretically you can use as many <iframe>s as you like, check for performance problems. Content categories Flow content, phrasing content, embedded content, interactive content, palpable content. Permitted content None. Tag omission None, both the st...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts. Responsive image hints with sizes and srcset (see also the <picture> element and our Responsive images tutorial). Supported image formats The HTML standard doesn't list what image formats to support, so each user agent supports different formats. A
complete guide to image formats supported by web browsers is available. Below is a list of the image formats that are most commonly used on the web, as well as some older formats that should no longer be used, despite existing content possibly still using them. Abbreviation File format MIME type File extension(s) Browser compatibility APNG Animated Portable Network Gr...
<input type="button"> - HTML: Hypertext Markup Language
uerySelector('input'); const fieldset = document.querySelector('fieldset'); button.addEventListener('click', disableButton); function disableButton() { fieldset.disabled = true; window.setTimeout(function() { fieldset.disabled = false; }, 2000); } Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> across page loads. Use the auto
complete attribute to control this feature. Validation Buttons don't participate in constraint validation; they have no real value to be constrained. Examples The below example shows a very simple drawing app created using a <canvas> element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, ...
<input type="color"> - HTML: Hypertext Markup Language
source for this interactive example is stored in a GitHub repository. If you'd like to 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 auto
complete 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 emp...
<input type="hidden"> - HTML: Hypertext Markup Language
<input> elements of type hidden let web developers include data that cannot be seen or modified by users when a form is submitted. For example, the ID of the content that is currently being ordered or edited, or a unique security token. Hidden inputs are
completely invisible in the rendered page, and there is no way to make it visible in the page's content. Note: There is a live example below the following line of code -- if it is working correctly, you should see nothing! <input id="prodId" name="prodId" type="hidden" value="xm234jq"> Value A DOMString representing the value of the hidden data you want to pass back to the server. Events None. Supported Common Attributes auto
complete IDL attributes value Methods None. No...
<input type="radio"> - HTML: Hypertext Markup Language
d item in the group value The string to use as the value of the radio when submitting the form, if the radio is currently toggled on checked A Boolean attribute which, if present, indicates that this radio button is the currently selected one in the group. Unlike other browsers, Firefox by default persists the dynamic checked state of an <input> across page loads. Use the auto
complete attribute to control this feature. value The value attribute is one which all <input>s share; however, it serves a special purpose for inputs of type radio: when a form is submitted, only radio buttons which are currently checked are submitted to the server, and the reported value is the value of the value attribute. If the value is not otherwise specified, it is the string on by default. This ...
<input type="range"> - HTML: Hypertext Markup Language
e https://github.com/mdn/interactive-examples and send us a pull request. If the user's browser doesn't support type range, it will fall back and treat it as a text input. Value A DOMString containing the string representation of the selected numeric value; use valueAsNumber to get the value as a Number. ...
<input type="reset"> - HTML: Hypertext Markup Language
pecially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it's not a
complete solution for accessibility purposes. Disabling and enabling a reset button To disable a reset button, simply specify the disabled global attribute on it, like so: <input type="reset" value="Disabled" disabled> You can enable and disable buttons at run time by simply setting disabled to true or false; in JavaScript this looks like btn.disabled = true or btn.disabled = false. Note: See the ...
<input type="submit"> - HTML: Hypertext Markup Language
pecially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it's not a
complete solution for accessibility purposes. Disabling and enabling a submit button To disable a submit button, simply specify the disabled global attribute on it, like so: <input type="submit" value="Disabled" disabled> You can enable and disable buttons at run time by simply setting disabled to true or false; in JavaScript this looks like btn.disabled = true or btn.disabled = false. See the <in...
<input type="week"> - HTML: Hypertext Markup Language
ts to fill in week and year values, a pop-up calendar interface to select them more visually, and an "X" button to clear the control'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 auto
complete, 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 ...
<isindex> - HTML: Hypertext Markup Language
ch results. Kevin replies that he doesn't like the boolean nature of isindex and would prefer a system where everything is searchable and proposes to extend the current WWW Framework with a specific httpd configuration and defined that some URIs mapping create search queries. In 2016, after it was removed from Edge and Chrome, it was proposed to remove isindex from the standard; this removal was
completed the next day, after which Safari and Firefox also removed support. HTML Reference The HTML Standard classifies it as a obsolete and non-conforming feature. ISINDEX element deprecated in HTML 4.01 ISINDEX in HTML 3.2 ISINDEX in HTML 2.0 as well the description of the behavior in Queries and Indexes (HTML 2.0) ISINDEX in HTML+ ...
<object> - HTML: Hypertext Markup Language
4 onlyObsolete since HTML5 The content type of the data specified by classid. data The address of the resource as a valid URL. At least one of data and type must be defined. declareHTML 4 onlyObsolete since HTML5 The presence of this Boolean attribute makes this element a declaration only. The object must be instantiated by a subsequent <object> element. In HTML5, repeat the <object> element
completely each that that the resource is reused. formHTML5 The form element, if any, that the object element is associated with (its form owner). The value of the attribute must be an ID of a <form> element in the same document. height The height of the displayed resource, in CSS pixels. -- (Absolute values only. NO percentages) name The name of valid browsing context (HTML5), or the name of the co...
<progress>: The Progress Indicator element - HTML: Hypertext Markup Language
DOM interface HTMLProgressElement Attributes This element includes the global attributes. max This attribute describes how much work the task indicated by the progress element requires. The max attribute, if present, must have a value greater than 0 and be a valid floating point number. The default value is 1. value This attribute specifies how much of the task that has been
completed. It must be a valid floating point number between 0 and max, or between 0 and 1 if max is omitted. If there is no value attribute, the progress bar is indeterminate; this indicates that an activity is ongoing with no indication of how long it is expected to take. Note: Unlike the <meter> element, the minimum value is always 0, and the min attribute is not allowed for the <progress> element. ...
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
xample, we provide an annotation for the original character equivalent of "Kanji": <ruby> <rb>?<rb>? <rp>(</rp><rt>kan<rt>ji<rp>)</rp> </ruby> Note how we've included two <rb> elements, to delimit the two separate parts of the ruby base text. The annotation on the other hand is delimited by two <rt> elements. Note that we could also write this example with the two base text parts annotated
completely separately. In this case we don't need to include <rb> elements: <ruby> ? <rp>(</rp><rt>Kan</rt><rp>)</rp> ? <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> <ruby> <rb>?<rb>? <rp>(</rp><rt>kan<rt>ji<rp>)</rp> </ruby> body { font-size: 22px; } The output looks like so: The HTML above might look something like this when rendered by a browser without ruby support: ?? (kan ji) body { ...
<samp>: The Sample Output element - HTML: Hypertext Markup Language
The CSS to override the default font face would look like this: samp { font-family: "Courier"; } If you need an element which will serve as a container for output generated by your website or app's JavaScript code, you should instead use the <output> element. Examples Basic example In this simple example, a paragraph includes an example of the output of a program. <p>When the process is
complete, the utility will output the text <samp>Scan
complete. Found <em>N</em> results.</samp> You can then proceed to the next step.</p> The resulting output looks like this: Sample output including user input You can nest the <kbd> element within a <samp> block to present an example that includes text entered by the user. For example, consider this text presenting a transcript of a Linux (or macO...
<select>: The HTML Select element - HTML: Hypertext Markup Language
any options should be shown at once. It also accepts most of the general form input attributes such as required, disabled, autofocus, etc. You can further nest <option> elements inside <optgroup> elements to create separate groups of options inside the dropdown. For further examples, see The native form widgets: Drop-down content. Attributes This element includes the global attributes. auto
complete A DOMString providing a hint for a user agent's auto
complete feature. See The HTML auto
complete attribute for a
complete list of values and details on how to use auto
complete. autofocus This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form element in a document can have the autofocus attribute. disabled This Boolean attribute i...
<slot> - HTML: Hypertext Markup Language
In addition, you can find an explanation at Using templates and slots. Specifications Specification Status Comments HTML Living StandardThe definition of '<slot>' in that specification. Living Standard DOMThe definition of 'Slots' in that specification. Living Standard ...
<sub>: The Subscript element - HTML: Hypertext Markup Language
f a given element within a chemical formula (such as every developer's best friend, C8H10N4O2, otherwise known as "caffeine"). See Chemical formulas. Examples Footnote numbers Traditional footnotes are denoted using numbers which are rendered in subscript. This is a common use case for <sub>: <p>According to the computations by Nakamura, Johnson, and Mason<sub>1</sub> this will result in the
complete annihilation of both particles.</p> The resulting output looks like this: Variable subscripts In mathematics, families of variables related to the same concept (such as distances along the same axis) are represented using the same variable name with a subscript following. For example: <p>The horizontal coordinates' positions along the X-axis are represented as <var>x<sub>1</sub></var> ... <...
<xmp> - HTML: Hypertext Markup Language
Summary The HTML Example Element (<xmp>) renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line. Note: Do not use this element. It has been deprecated since HTML3.2 and was not implemented in a consistent way. It was
completely removed from the language in HTML5. Use the <pre> element or, if semantically adequate, the <code> element instead. Note that you will need to escape the '<' character as '<' to make sure it is not interpreted as markup. A monospaced font can also be obtained on any element, by applying an adequate CSS style using monospace as the generic-font value for the font-family property. Attributes This...
hidden - HTML: Hypertext Markup Language
Browsers won't render elements with the hidden attribute set. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
itemid - HTML: Hypertext Markup Language
definition of that identifier within the specified vocabulary. The vocabulary defines whether several items with the same global identifier can coexist and, if so, how items with the same identifier are handled. Note: The WHATWG definition specifies that an itemid must be a URL. However, the following example correctly illustrates that a URN may also be used. This inconsistency may reflect the in
complete nature of the Microdata specification. Example HTML <dl itemscope itemtype="http://vocab.example.net/book" itemid="urn:isbn:0-330-34032-8"> <dt>Title <dd itemprop="title">The Reality Dysfunction <dt>Author <dd itemprop="author">Peter F. Hamilton <dt>Publication date <dd><time itemprop="pubdate" datetime="1996-01-26">26 January 1996</time> </dl> Structured data itemscope i...
itemprop - HTML: Hypertext Markup Language
The only difference is that if the user drags the figcaption out of the document, the item will be included in the drag-and-drop data. The image associated with the item won't be included. Names and values A property is an unordered set of unique tokens that are case-sensitive and rep...
HTML: Hypertext Markup Language
uppercase, lowercase, or a mixture. For example, the <title> tag can be written as <Title>, <TITLE>, or in any other way. The articles below can help you learn more about HTML. HTML Introduction If you're new to Web development, be sure to read our HTML Basics article to learn what HTML is and how to use it. HTML Tutorials For articles about how to use HTML, as well as tutorials and
complete examples, check out our HTML Learning Area. HTML Reference In our extensive HTML reference section, you'll find the details about every element and attribute in HTML. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Beginner's tutorials Our HTML Learning Area feat...
Evolution of HTTP - HTTP
ng blocks: A textual format to represent hypertext documents, the HyperText Markup Language (HTML). A simple protocol to exchange these documents, the HypertText Transfer Protocol (HTTP). A client to display (and accidentally edit) these documents, the first Web browser called WorldWideWeb. A server to give access to the document, an early version of httpd. These four building blocks were
completed by the end of 1990, and the first servers were already running outside of CERN by early 1991. On August 6th 1991, Tim Berners-Lee's post on the public alt.hypertext newsgroup is now considered as the official start of the World Wide Web as a public project. The HTTP protocol used in those early phases was very simple, later dubbed HTTP/0.9, and sometimes as the one-line protocol. HTTP/0.9 - Th...
Basics of HTTP - HTTP
es. Frame and message structure in HTTP/2 HTTP/2 encapsulates and represents HTTP/1.x messages in a binary frame. This article explains the frame structure, its purpose, and the way it's encoded. Connection management in HTTP/1.x HTTP/1.1 was the first version of HTTP to support persistent connection and pipelining. This article explains both concepts. Connection management in HTTP/2 HTTP/2
completely revisited how connections are created and maintained. This article explains how HTTP frames allow multiplexing and solve the 'head-of-line' blocking problem of former HTTP versions. Content Negotiation HTTP introduces a set of headers, starting with Accept as a way for a browser to announce the format, language, or encoding it prefers. This article explains how this advertisement happens, how...
Cross-Origin Resource Sharing (CORS) - HTTP
GOTHER, Content-Type HTTP/1.1 204 No Content Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2 Access-Control-Allow-Origin: https://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER, Content-Type Access-Control-Max-Age: 86400 Vary: Accept-Encoding, Origin Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Once the preflight request is
complete, the real request is sent: POST /doc HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive X-PINGOTHER: pingpong Content-Type: text/xml; charset=UTF-8 Referer: https://foo.exa...
HTTP caching - HTTP
the request method and target URI (oftentimes only the URI is used as only GET requests are caching targets). Common forms of caching entries are: Successful results of a retrieval request: a 200 (OK) response to a GET request containing a resource like HTML documents, images or files. Permanent redirects: a 301 (Moved Permanently) response. Error responses: a 404 (Not Found) result page. In
complete results: a 206 (Partial Content) response. Responses other than GET if something suitable for use as a cache key is defined. A cache entry might also consist of multiple stored responses differentiated by a secondary key, if the request is target of content negotiation. For more details see the information about the Vary header below. Controlling caching The Cache-Control header The Cache-C...
HTTP conditional requests - HTTP
more recent than the one given in this header. If-Unmodified-Since Succeeds if the Last-Modified date of the distant resource is older or the same than the one given in this header. If-Range Similar to If-Match, or If-Unmodified-Since, but can have only one single etag, or one date. If it fails, the range request fails, and instead of a 206 Partial Content response, a 200 OK is sent with the
complete resource. Use cases Cache update The most common use case for conditional requests is updating a cache. With an empty cache, or without a cache, the requested resource is sent back with a status of 200 OK. Together with the resource, the validators are sent in the headers. In this example, both Last-Modified and ETag are sent, but it could equally have been only one of them. These validato...
Connection management in HTTP/1.x - HTTP
odes. A related topic is the concept of HTTP connection upgrades, wherein an HTTP/1.1 connection is upgraded to a different protocol, such as TLS/1.0, WebSocket, or even HTTP/2 in cleartext. This protocol upgrade mechanism is documented in more detail elsewhere. Short-lived connections The original model of HTTP, and the default one in HTTP/1.0, is short-lived connections. Each HTTP request is
completed on its own connection; this means a TCP handshake happens before each HTTP request, and these are serialized. The TCP handshake itself is time-consuming, but a TCP connection adapts to its load, becoming more efficient with more sustained (or warm) connections. Short-lived connections do not make use of this efficiency feature of TCP, and performance degrades from optimum by persisting to trans...
Content negotiation - HTTP
d client hints. Client hints advertise what kind of device the user agent runs on (for example, if it is a desktop computer or a mobile device). Even if server-driven content negotiation is the most common way to agree on a specific representation of a resource, it has several drawbacks: The server doesn't have total knowledge of the browser. Even with the Client Hints extension, it has not a
complete knowledge of the capabilities of the browser. Unlike reactive content negotiation where the client makes the choice, the server choice is always somewhat arbitrary. The information by the client is quite verbose (HTTP/2 header compression mitigates this problem) and a privacy risk (HTTP fingerprinting) As several representations of a given resource are sent, shared caches are less efficient and...
Using HTTP cookies - HTTP
ccepted in a Set-Cookie header only if it is marked with the Secure attribute and was sent from a secure origin. This is weaker than the __Host- prefix. Cookies with these prefixes that are not compliant with their restrictions are rejected by the browser. Note that this ensures that if a subdomain were to create a cookie with a prefix, it would either be confined to the subdomain or be ignored
completely. As the application server checks for a specific cookie name only when determining if the user is authenticated or a CSRF token is correct, this effectively acts as a defence measure against session fixation. On the application server, the web application must check for the full cookie name including the prefix--user agents do not strip the prefix from the cookie before sending it in a reques...
Accept-Encoding - HTTP
compression requirement. Typically, Microsoft recommends not to compress if a server uses more than 80% of its computational power. As long as the identity value, meaning no encoding, is not explicitly forbidden, by an identity;q=0 or a *;q=0 without another explicitly set value for identity, the server must never send back a 406 Not Acceptable error. Notes: An IANA registry maintains a
complete list of official content encodings. Two others content encoding, bzip and bzip2, are sometimes used, though not standard. They implement the algorithm used by these two UNIX programs. Note that the first one was discontinued due to patent licensing problems. Header type Request header Forbidden header name yes Syntax Accept-Encoding: gzip Accept-Encoding: com...
Accept-Patch - HTTP
is able to understand. Accept-Patch in response to any method means that PATCH is allowed on the resource identified by the Request-URI. Two common cases lead to this: A server receiving a PATCH request with an unsupported media type could reply with 415 Unsupported Media Type and an Accept-Patch header referencing one or more supported media types. Notes: An IANA registry maintains a
complete list of official content encodings. Two others content encoding, bzip and bzip2, are sometimes used, though not standard. They implement the algorithm used by these two UNIX programs. Note that the first one was discontinued due to patent licensing problems. Header type Response header Forbidden header name yes Syntax Accept-Patch: application/example, text/e...
Feature-Policy: unsized-media - HTTP
This restriction solves "layout instability" problem caused by providing default dimensions for images whose size is not specified in advance so that image doesn't change size after loading. ...
Upgrade - HTTP
K). If the server decides to upgrade the connection, it must: Send back a 101 Switching Protocols response status with an Upgrade header that specifies the protocol(s) being switched to. For example: HTTP/1.1 101 Switching Protocols Upgrade: foo/2 Connection: Upgrade Send a response to the original request using the new protocol (the server may only switch to a protocol with which it can
complete the original request). A server may also send the header as part of a 426 Upgrade Required response, to indicate that the server won't perform the request using the current protocol, but might do so if the protocol is changed. The client can then request a protocol change using the process above. More detail and examples are provided in the topic Protocol upgrade mechanism. Syntax Connection...
X-DNS-Prefetch-Control - HTTP
p of specific hostnames without providing specific anchors using that hostname by using the rel attribute on the <link> element with a link type of dns-prefetch: <link rel="dns-prefetch" href="https://www.mozilla.org/contribute/"> In this example, the domain name "www.mozilla.org/contribute" will be pre-resolved. Similarly, the link element can be used to resolve hostnames without providing a
complete URL, but only, by preceding the hostname with two slashes: <link rel="dns-prefetch" href="//www.mozilla.org/contribute/"> Forced prefetching of hostnames might be useful, for example, on the homepage of a site to force pre-resolution of domain names that are referenced frequently throughout the site even though they are not used on the home page itself. This will improve the overall performanc...
Link prefetching FAQ - HTTP
ers when serving up static content. When the user visits a prefetched document for real, the remaining portion of the document will be fetched using a HTTP byte-range request. What if I'm downloading something in the background? Will link prefetching compete for bandwidth? Yes and no. If you are downloading something using Mozilla, link prefetching will be delayed until any background downloads
complete. For example, if you load a bookmark group (which opens several tabs), any prefetch requests initiated by one of the bookmarked pages will not begin until all of the tabs finish loading. If you are using another application which uses the network, link prefetching in Mozilla may compete for bandwidth with the other application. This is a problem that we hope to address in the future by leveraging...
HTTP Messages - HTTP
he format of this request target varies between different HTTP methods. It can be An absolute path, ultimately followed by a '?' and query string. This is the most common form, known as the origin form, and is used with GET, POST, HEAD, and OPTIONS methods. POST / HTTP/1.1 GET /background.png HTTP/1.0 HEAD /test.html?query=alibaba HTTP/1.1 OPTIONS /anypage.html HTTP/1.0 A
complete URL, known as the absolute form, is mostly used with GET when connected to a proxy. GET http://developer.mozilla.org/docs/Web/HTTP/Messages HTTP/1.1 The authority component of a URL, consisting of the domain name and optionally the port (prefixed by a ':'), is called the authority form. It is only used with CONNECT when setting up an HTTP tunnel. CONNECT developer.mozilla.org:80 HTTP/1...
PATCH - HTTP
A PATCH is not necessarily idempotent, although it can be. ...
Protocol upgrade mechanism - HTTP
switched to. If it does not (or cannot) upgrade the connection, it ignores the Upgrade header and sends back a regular response (for example, a 200 OK). Right after sending the 101 status code, the server can begin speaking the new protocol, performing any additional protocol-specific handshakes as necessary. Effectively, the connection becomes a two-way pipe as soon as the upgraded response is
complete, and the request that initiated the upgrade can be
completed over the new protocol. Common uses for this mechanism Here we look at the most common use cases for the Upgrade header. Upgrading to a WebSocket connection By far, the most common use case for upgrading an HTTP connection is to use WebSockets, which are always implemented by upgrading an HTTP or HTTPS connection. Keep in mind that i...
Proxy Auto-Configuration (PAC) file - HTTP
d to a file with a .pac filename extension: proxy.pac And the MIME type should be set to: application/x-ns-proxy-autoconfig Next, you should configure your server to map the .pac filename extension to the MIME type. Notes: The JavaScript function should always be saved to a file by itself but not be embedded in 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. (Of course, the JavaScripts must be edited to reflect your site's domain name and/or subnets.) Predefined functions and environment These functions can be used in building the PAC file: Hostname based conditions isPlainHostName() dnsDomainIs() localHostOrDomainIs() isResolvable() isInNet() Rela...
Redirections in HTTP - HTTP
after modifying a server configuration, this is likely a redirection loop. Sometimes, the server won't detect it: a redirection loop can spread over several servers which each don't have the full picture. In this case, browsers will detect it and display an error message. Firefox displays: Firefox has detected that the server is redirecting the request for this address in a way that will never
complete. ...while Chrome displays: This Webpage has a redirect loop In both cases, the user can't do much (unless a corruption is happening on their side, like a mismatch of cache or cookies). It is important to avoid redirection loops, as they
completely break the user experience. ...
A typical HTTP session - HTTP
Strict-Transport-Security: max-age=63072000 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Vary: Accept-Encoding,Cookie X-Cache: Error from cloudfront <!DOCTYPE html... (contains a site-customized page helping the user to find the missing resource) Response status codes HTTP response status codes indicate if a specific HTTP request has been successfully
completed. Responses are grouped into five classes: informational responses, successful responses, redirects, client errors, and servers errors. 200: OK. The request has succeeded. 301: Moved Permanently. This response code means that the URI of requested resource has been changed. 404: Not Found. The server cannot find the requested resource. ...
202 Accepted - HTTP
The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. 202 is non-committal, meaning that there is no way for the HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. ...
406 Not Acceptable - HTTP
ult representation. Proactive content negotiation headers include: Accept Accept-Charset Accept-Encoding Accept-Language In practice, this error is very rarely used. Instead of responding using this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. It is assumed that even if the user won't be
completely happy, they will prefer this to an error code. If a server returns such an error status, the body of the message should contain the list of the available representations of the resources, allowing the user to choose among them. Status 406 Not Acceptable Specifications Specification Title RFC 7231, section 6.5.6: 406 Not Acceptable Hypertext Transfer Protocol (HTTP/1...
504 Gateway Timeout - HTTP
The HyperText Transfer Protocol (HTTP) 504 Gateway Timeout server error response code indicates that the server, while acting as a gateway or proxy, did not get a response in time from the upstream server that it needed in order to
complete the request. Note: A Gateway might refer to different things in networking and a 504 error is usually not something you can fix, but requires a fix by the web server or the proxies you are trying to get access through. Status 504 Gateway Timeout Specifications Specification Title RFC 7231, section 6.6.5: 504 Gateway Timeout Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
507 Insufficient Storage - HTTP
The HyperText Transfer Protocol (HTTP) 507 Insufficient Storage response status code may be given in the context of the Web Distributed Authoring and Versioning (WebDAV) protocol (see RFC 4918). It indicates that a method could not be performed because the server cannot store the representation needed to successfully
complete the request. Status 507 Insufficient Storage Specifications Specification Title RFC 4918, section 11.5: 507 Insufficient Storage Web Distributed Authoring and Versioning ...
HTTP
in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP message headers. HTTP Request Methods The different operations that can be done with HTTP: GET, POST, and also less common requests like OPTIONS, DELETE, or TRACE. HTTP Status Response Codes HTTP response codes indicate whether a specific HTTP request has been successfully
completed. Responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors. CSP directives The Content-Security-Policy response header fields allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script end...
A re-introduction to JavaScript (JS tutorial) - JavaScript
host environment to provide mechanisms for communicating with the outside world. The most common host environment is the browser, but JavaScript interpreters can also be found in a huge list of other places, including Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, server-side environments such as Node.js, NoSQL databases like the open source Apache CouchDB, embedded computers,
complete desktop environments like GNOME (one of the most popular GUIs for GNU/Linux operating systems), and others. Overview JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages -- many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming ...
Loops and iteration - JavaScript
} n += i; console.log(n); } // 1,3,6,10,15 Example 2 A statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program terminates the current iteration of checkj and begins the next iteration. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is
completed, and checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj. If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement. let i = 0; let j = 10; checkiandj: while (i < 4) { console.log(i); i += 1; checkj: while (j > 4) { console.log(j); ...
JavaScript modules - JavaScript
<< Previous This guide gives you all you need to get started with JavaScript module syntax. A background on modules JavaScript programs started off pretty small -- most of its usage in the early days was to do isolated scripting tasks, providing a bit of interactivity to your web pages where needed, so large scripts were generally not needed. Fast forward a few years and we now have
complete applications being run in browsers with a lot of JavaScript, as well as JavaScript being used in other contexts (Node.js, for example). It has therefore made sense in recent years to start thinking about providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed. Node.js has had this ability for a long time, and there are a number of JavaScri...
Memory Management - JavaScript
// The 'a' property of the object originally in x // has zero references to it. It can be garbage collected. Limitation: Circular references There is a limitation when it comes to circular references. In the following example, two objects are created with properties that reference one another, thus creating a cycle. They will go out of scope after the function call has
completed. At that point they become unneeded and their allocated memory should be reclaimed. However, the reference-counting algorithm will not consider them reclaimable since each of the two objects has at least one reference pointing to them, resulting in neither of them being marked for garbage collection. Circular references are a common cause of memory leaks. function f() { var x = {}; var y = ...
SyntaxError: missing ] after element list - JavaScript
fter element list" occurs when there is an error with the array initializer syntax somewhere. Likely there is a closing bracket ("]") or a comma (",") missing. Message SyntaxError: missing ] after element list Error type SyntaxError. ...
Generator.prototype.return() - JavaScript
n 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 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: fals...
Intl.Locale.prototype.baseName - JavaScript
The Intl.Locale.prototype.baseName property returns a substring of the Locale's string representation, containing core information about the Locale. Description An Intl.Locale object represents a parsed local and options for that locale. The baseName property returns basic, core information about the Locale in the form of a substring of the
complete data string. Specifically, the property returns the substring containing the language, and the script and region if available. baseName returns the language ["-" script] ["-" region] *("-" variant) subsequence of the unicode_language_id grammar. Examples Basic Example let myLoc = new Intl.Locale("fr-Latn-CA"); // Sets locale to Canadian French console.log(myLoc.toString()); // Prints out "fr-Latn-CA-u-ca-gregory" console.log(myLoc.baseName); // ...
Intl.Locale.prototype.maximize() - JavaScript
es project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax locale.maximize() Return value A Locale instance whose baseName property returns the result of the Add Likely Subtags algorithm executed against locale.baseName. Description Sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an in
complete 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...
Intl.Locale.prototype.script - JavaScript
icular language. For instance, the script associated with English is Latin, whereas the script typically associated with Korean is Hangul. In many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. There are exceptions to this rule, however, and it is important to indicate the script whenever possible, in order to have a
complete Unicode language identifier. Examples Setting the script in the locale identifer string argument The script is the second part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the Locale constructor. Note that the script is not a required part of a locale identifier. let scriptStr = new Intl.Locale("en-Latn-US"); c...
Intl.Locale - JavaScript
ode does. This is a simple and lightweight solution that works well. Adding a Locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. Constructor Intl.Locale() Creates a new Locale object. Instance properties Intl.Locale.prototype.baseName Returns basic, core information about the Locale in the form of a substring of the
complete data string. Intl.Locale.prototype.calendar Returns the part of the Locale that indicates the Locale's calendar era. Intl.Locale.prototype.caseFirst Returns whether case is taken into account for the locale's collation rules. Intl.Locale.prototype.collation Returns the collation type for the Locale, which is used to order strings according to the locale's rules. Intl.Locale.prototype.hourC...
Object.create() - JavaScript
ding property names. These properties correspond to the second argument of Object.defineProperties(). Return value A new object with the specified prototype object and properties. Exceptions The proto parameter has to be either null or an Object excluding primitive wrapper objects. If proto is neither of these a TypeError is thrown. Custom and Null objects A new object created from a
completely custom object (especially one created from the null object, which is basically a custom object with NO members) can behave in unexpected ways. This is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or simply lose information (especially if using silent error-traps that ignore errors). For example, here are two objects: o...
Object.defineProperties() - JavaScript
descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown. Return value The object that was passed to the function. Polyfill Assuming a pristine execution environment with all names and properties referring to their initial values, Object.defineProperties is almost
completely equivalent (note the comment in isCallable) to the following reimplementation in JavaScript: function defineProperties(obj, properties) { function convertToDescriptor(desc) { function hasProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function isCallable(v) { // NB: modify as necessary if other values than functions are callable. ...
Promise() constructor - JavaScript
you can say that it is "resolved", but still cannot be said to be "settled". Examples Creating a new Promise A Promise object is created using the new keyword and its constructor. This constructor takes a function, called the "executor function", as its parameter. This function should take two functions as parameters. The first of these functions (resolve) is called when the asynchronous task
completes successfully and returns the results of the task as a value. The second (reject) is called when the task fails, and returns the reason for failure, which is typically an error object. const myFirstPromise = new Promise((resolve, reject) => { // do something asynchronous which eventually calls either: // // resolve(someValue) // fulfilled // or // reject("failure reason") /...
Promise.all() - JavaScript
olved, or if any of the promises reject. See the example about "Asynchronicity or synchronicity of Promise.all" below. Returned values will be in order of the Promises passed, 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 i...
Promise.any() - JavaScript
A pending Promise in all other cases. This returned 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 fulfille...
Promise - JavaScript
action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future. A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation
completed successfully. rejected: meaning that the operation failed. A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there i...
String.fromCharCode() - JavaScript
03 "Night with Stars". Examples Using fromCharCode() BMP characters, in UTF-16, use a single code unit: String.fromCharCode(65, 66, 67); // returns "ABC" String.fromCharCode(0x2014); // returns "--" String.fromCharCode(0x12014); // also returns "--"; the digit 1 is truncated and ignored String.fromCharCode(8212); // also returns "--"; 8212 is the decimal form of 0x2014
Complete UTF 16 Table. Supplementary characters, in UTF-16, require two code units (i.e. a surrogate pair): String.fromCharCode(0xD83C, 0xDF03); // Code Point U+1F303 "Night with String.fromCharCode(55356, 57091); // Stars" == "\uD83C\uDF03" String.fromCharCode(0xD834, 0xDF06, 0x61, 0xD834, 0xDF07); // "\uD834\uDF06a\uD834\uDF07" Specifications Specification ECMAScript (ECMA-262)...
String.prototype.match() - JavaScript
egexp 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 capturing groups are returned. In this case, the returned item will have additional properties as described below. Additional properties As explained above, some results contain additional properties as described below. groups An object of named capt...
Symbol() constructor - JavaScript
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. ...
Symbol.asyncIterator - JavaScript
Built-in Async Iterables There are currently no built-in JavaScript objects that have the [Symbol.asyncIterator] key set by default. However, WHATWG Streams are set to be the first built-in object to be async iterable, with [Symbol.asyncIterator] recently landing in the spec. Specifications Specification ECMAScript (ECMA...
WeakRef() constructor - JavaScript
The WeakRef constructor creates a WeakRef object referring to a given target object. Syntax new WeakRef(targetObject); Parameters targetObject The target object the WeakRef should refer to (also called the referent). Examples Creating a new WeakRef object See the main WeakRef page for a
complete example. class Counter { constructor(element) { // Remember a weak reference to a DOM element this.ref = new WeakRef(element); this.start(); } } Specifications Specification WeakRefsThe definition of 'WeakRef constructor' in that specification. ...
WeakRef.prototype.deref() - JavaScript
s 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. 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 definit...
decodeURI() - JavaScript
function decodes a Uniform Resource Identifier (URI) previously created by encodeURI() or by a similar routine. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax decodeURI(encodedURI) Parameters encodedURI A
complete, encoded Uniform Resource Identifier. Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). Exceptions Throws an URIError ("malformed URI sequence") exception when encodedURI contains invalid character sequences. Description Replaces each escape sequence in the encoded URI with the character that it represents, but does not dec...
Iteration protocols - JavaScript
llowing 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 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() retu...
Lexical grammar - JavaScript
ECMAScript specification mentions three rules of semicolon insertion. 1. A semicolon is inserted before, when a Line terminator or "}" is encountered that is not allowed by the grammar. { 1 2 } 3 // is transformed by ASI into { 1 2 ;} 3; 2. A semicolon is inserted at the end, when the end of the input stream of tokens is detected and the parser is unable to parse the single input stream as a
complete program. Here ++ is not treated as a postfix operator applying to variable b, because a line terminator occurs between b and ++. a = b ++c // is transformend by ASI into a = b; ++c; 3. A semicolon is inserted at the end, when a statement with restricted productions in the grammar is followed by a line terminator. These statements with "no LineTerminator here" rules are: PostfixExpression...
yield - JavaScript
ed 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, executi...
continue - JavaScript
continue; } n += i; } Using continue with a label In the following example, a statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program continues at the top of the checkj statement. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is
completed. If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement. See also label. var i = 0; var j = 8; checkiandj: while (i < 4) { console.log('i: ' + i); i += 1; checkj: while (j > 4) { console.log('j: ' + j); j -= 1; if ((j % 2) == 0) continue checkj; console.log(j + ' is odd.'); } console.log('i = ' + i); consol...
try...catch - JavaScript
try_statements The statements to be executed. catch_statements_1, catch_statements_2 Statements that are executed if an exception is thrown in the try-block. exception_var_1, exception_var_2 An identifier to hold an exception object for the associated catch-block. condition_1 A conditional expression. finally_statements Statements that are executed after the try statement
completes. These statements execute regardless of whether an exception was thrown or caught. Description The try statement consists of a try-block, which contains one or more statements. {} must always be used, even for single statements. At least one catch-block, or a finally-block, must be present. This gives us three forms for the try statement: try...catch try...finally try...catch...finally ...
Strict mode - JavaScript
mes are a syntax error in strict mode: This is no longer the case in ECMAScript 2015 (bug 1041128). 'use strict'; var o = { p: 1, p: 2 }; // !!! syntax error Fifth, strict mode requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through arguments[i], so they're not
completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error: function sum(a, a, c) { // !!! syntax error 'use strict'; return a + a + c; // wrong if this code ran } Sixth, a strict mode in ECMAScript 5 forbids octal syntax. The octal syntax isn't part of ECMAScript 5, bu...
Template literals (Template strings) - JavaScript
ced form of template literals are tagged templates. Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions. The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string. (Alternatively, it can return something
completely different, as described in one of the following examples.) The name of the function used for the tag can be whatever you want. let person = 'Mike'; let age = 28; function myTag(strings, personExp, ageExp) { let str0 = strings[0]; // "That " let str1 = strings[1]; // " is a " // There is technically a string after // the final expression (in our example), // but it is empty (""), s...
Authoring MathML - MathML
That is, you use command-line programs to generate them and publish these static pages on your server. pros: You get static Web pages: the LaTeX source don't need to be parsed at each page load, the MathML code is exposed to Web crawlers and you can put them easily on any Web server. Binary programs may run faster than Javascript programs and can be more sophisticated e.g. have a much
complete LaTeX support or generate other formats like EPUB. You can keep compatibility with other tools to generate pdf e.g. you can use the same .tex source for both latex and latexml. cons: This requires to install programs on your computer, which may be a bit more difficult or they may not be available on all platforms. You must run the programs on your computer and have some kind of ...
MathML: Deriving the Quadratic Formula - MathML
This page outlines the derivation of the Quadratic Formula. We take a quadratic equation in its general form, and solve for x: a x 2 + b x + c = 0 a x 2 + b x = - c x 2 + b a ? x = -c a Divide out leading coefficient. x 2 + b a ? x + b 2 a 2 = - c ( 4 a ) a ( 4 a ) + b 2 4 a 2
Complete the square. ( x + b 2 a ) ( x + b 2 a ) = b 2 - 4 a c 4 a 2 Discriminant revealed. ( x + b 2 a ) 2 = b 2 - 4 a c 4 a 2 x + b 2 a = b 2 - 4 a c 4 a 2 x = -b 2 a +-{C} b 2 - 4 a c 4 a 2 There's the vertex formula. x = - b +-{C} b 2 - 4 a c 2 a ...
Web audio codec guide - Web media technologies
e speech sounds that we need in order to understand what's being said lie in the frequency range of 500 Hz to 3,000 Hz or so. That means voice-only codecs can throw away everything else. The voice-specific codecs are all inherently very lossy, however, and any sound with significant information in the frequency bands outside the vocal range captured will be entirely lost. This makes these codecs
completely unsuitable for anything but spoken words. Even audio that contains only voices, but singing rather than simply speaking, will likely not be of acceptable quality in one of these formats. Voice recording and playback usually needs to be low-latency in order to synchronize with video tracks, or in order to avoid cross-talk or other problems. Fortunately, the characteristics that lead to speech c...
Digital audio concepts - Web media technologies
d left/right (L/R) stereo or simple stereo. Joint stereo is a method of storing stereo audio samples in a more space-efficient manner by taking into account that usually the sound entering each ear is similar. Thus, rather than storing every bit of each channel's sample, a base amplitude and a per-channel amplitude deviation value are stored, wherein the deviation value may use fewer bits than a
complete sample. There are two types of joint stereo: mid-side and intensity. Over the duration of an audio file, the encoder may change which format is being used to represent the stereo signal over the course of the audio file. Mid-side stereo coding Mid-side stereo coding (MS) works by recording frames that contain a fundamental mid channel, which is the average amplitude of the original left and ri...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
eally useful for responsive layouts, but unfortunately it causes the jank problem to return -- the above CSS overrides the width and height attribute information, meaning that if the image has not loaded for some reason, its height will be set to 0. When the image finally loads, the same jank will occur as the page layout is shifted to make space for it. A new way of sizing images before loading
completes Recognizing the problem, a WICG community group formed to propose an intrinsicsize attribute. Folks from Mozilla then expanded on this thinking, working on a proposal in the CSS Box Sizing Level 4 draft to define an aspect-ratio property and propose the idea of using the width and height attributes to compute layout. Fantasai & Jen Simmons collaborated with Emilio, who worked on an experimental...
Animation performance and frame rate - Web Performance
canvas element is different. In the <canvas> scenario, the page layout is not changing. Rather, the page is being repainted, repeatedly, based on JavaScript canvas API functions. When a canvas is animating a drawing, the canvas animation can be described as a waterfall consisting of the following steps: These sequenced need to fit into a single frame, since the screen isn't updated until it is
complete. CSS property cost In the context of the rendering waterfall, some properties are more expensive than others: Property type Cost Examples Properties that affect an element's geometry or position trigger a style recalculation, a layout and a repaint. left max-width border-width margin-left font-size Properties that ...
Lazy loading - Web Performance
lazy" alt="..." /> <iframe src="video-player.html" loading="lazy"></iframe> The load event fires when the eagerly-loaded content has all been loaded; at that time, it's entirely possible (or even likely) that there may be lazily-loaded images that are within the visual viewport that haven't yet loaded. You can determine if a given image has finished loading by examining the value of its Boolean
complete property. Polyfill Include this polyfill to provide support for older and currently incompatible browsers: loading-attribute-polyfill Intersection Observer API Intersection Observers allow the user to know when an observed element enters or exits the browser's viewport. Event handlers When browser compatibility is crucial, there are a few options: polyfill intersection observer fallbac...
Add to Home screen - Progressive web apps (PWAs)
r Android available, use it to navigate to our demo at https://mdn.github.io/pwa-examples/a2hs/. You'll see fox pictures, but more important, you'll see a "home" icon with a plus (+) icon inside it -- this is the "Add to Home screen" icon displayed for any site that has the necessary features in place. Tapping this will show a confirmation banner -- pressing the big + ADD TO HOME SCREEN button
completes the action, adding the app to the Home screen. (Note: In Android 8 and higher, a system-level "Add to Home screen" permission dialog will be shown first.) If you have Mobile Chrome available, the experience is slightly different; upon loading our site, you'll see an install banner pop up asking whether you want to add this app to your Home screen. Note: You can find out a lot more about C...
Installing and uninstalling web apps - Progressive web apps (PWAs)
re isn't a standard for icons and symbols used for operations such as this. Firefox for Android On an Android device using Firefox, you'll see a "home" icon with a plus (+) icon inside it--this is the "Add to Home screen" icon displayed for any site that has the necessary features in place. Tapping this will show a confirmation banner--pressing the banner's big "+ ADD TO HOME SCREEN" button
completes the action, adding the app to the Home screen. Note that in Android 8 and higher, a system-level "Add to Home screen" permission dialog will be shown first. Samsung Internet Browser If you have Samsung Internet in your mobile device you will see a different icon. Tapping that icon should then take you to the same confirmation banner shown in Firefox above. Google Chrome for Android If y...
Introduction to progressive web apps - Progressive web apps (PWAs)
ophy for building web apps, involving some specific patterns, APIs, and other features. It's not that obvious if a web app is a PWA or not from first glance. An app could be considered a PWA when it meets certain requirements, or implements a set of given features: works offline, is installable, is easy to synchronize, can send push notifications, etc. In addition, there are tools to measure how
complete (as a percentage) a web app is, such as Lighthouse. By implementing various technological advantages, we can make an app more progressive, thus ending up with a higher Lighthouse score. But this is only a rough indicator. There are some key principles a web app should try to observe to be identified as a PWA. It should be: Discoverable, so the contents can be found through search engines. In...
Progressive loading - Progressive web apps (PWAs)
src already assigned, or by wrapping <img> tags with <a> elements pointing at the target images, so the user can click and access them when desired. We won't do that because the app itself is dependent on JavaScript -- without it, the list of games wouldn't even be loaded, and the Service Worker code wouldn't be executed. We could rewrite the loading process to load not only the images, but the
complete items consisting of full descriptions and links. It would work like an infinite scroll -- loading the items on the list only when the user scrolls the page down. That way the initial HTML structure would be minimal, loading time even smaller, and we would have even greater performance benefits. Conclusion Less files to load initially, smaller files split into modules, use of placeholders, and l...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
ation.pushManager.getSubscription() .then(async function(subscription) { // registration part }); }) .then(function(subscription) { // subscription part }); It is a little bit more complicated than the service worker we saw in the js13kPWA demo. In this particular case, after registering, we use the registration object to subscribe, and then use the resulting subscription object to
complete the whole process. In the registration part, the code looks like this: if(subscription) { return subscription; } If the user has already subscribed, we then return the subscription object and move to the subscription part. If not, we initialize a new subscription: const response = await fetch('./vapidPublicKey'); const vapidPublicKey = await response.text(); const convertedVapidKey = urlB...
Media - Progressive web apps (PWAs)
e ensures that every H1 element starts on a new page: h1 {page-break-before: always;} More details For full details of CSS support for paged media, see Paged media in the CSS Specification. Like other features of CSS, printing depends on browser choice and its settings. For example, the Mozilla browser supplies default margins, headers, and footers for printing. Keep in mind that you can't
completely control the printed format. It is impossible to anticipate every user's browser choice and settings at the time of printing. User interfaces CSS has some special properties for devices that support a user interface, like computer displays. These properties dynamically change the appearance of content as the user works with the interface. There are five special selectors: Selector ...
bbox - SVG: Scalable Vector Graphics
The bbox attribute defines the maximal bounding box of a font. Only one element is using this attribute: <font-face> Usage notes Value <string> Default value None Animatable No <string> A comma-separated list of exactly four numbers specifying, in order, the lower left x, lower left y, upper right x, and upper right y of the bounding box for the
complete font. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'bbox' in that specification. Recommendation Initial definition ...
type - SVG: Scalable Vector Graphics
used. For the <animateTransform> element, it defines the type of transformation, whose values change over time. For the <feColorMatrix> element, it indicates the type of matrix operation. The keyword matrix indicates that a full 5x4 matrix of values will be provided. The other keywords represent convenience shortcuts to allow commonly used color operations to be performed without specifying a
complete matrix. For the <feFuncR>, <feFuncG>, <feFuncB>, and <feFuncA> elements, it Indicates the type of component transfer function. For the <feTurbulence> element, it indicates whether the filter primitive should perform a noise or turbulence function. For the <style> and <script> elements, it defines the content type of the element. Usage context For the <animateTransform> elements Ca...
<a> - SVG: Scalable Vector Graphics
ation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility XLink Attributes Most notably: xlink:title ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<circle> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<ellipse> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<feColorMatrix> - SVG: Scalable Vector Graphics
alpha A, plus a shift r5. These specified amounts can be any real number, though the final R' will be clamped between 0 and 1. The same goes for G', B', and A'. R' = r1 * R + r2 * G + r3 * B + r4 * A + r5 New red = [ r1 * old red ] + [ r2 * old green ] + [ r3 * old Blue ] + [ r4 * old Alpha ] + [ shift of r5 ] If, say, we want to make a
completely black image redder, we can make the r5 a positive real number x, boosting the redness on every pixel of the new image by x. An identity matrix looks like this: R G B A W R' | 1 0 0 0 0 | G' | 0 1 0 0 0 | B' | 0 0 1 0 0 | A' | 0 0 0 1 0 | In it, every new value is exactly 1 times its old value, with nothing else added. It is recommended to start manipulating the matrix from here. Usag...
<foreignObject> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<g> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<line> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<marker> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<path> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<polygon> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<polyline> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<rect> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<svg> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<symbol> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<text> - SVG: Scalable Vector Graphics
olor-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<textPath> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<tspan> - SVG: Scalable Vector Graphics
olor-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
<use> - SVG: Scalable Vector Graphics
: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-auto
complete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orienta...
SVG 1.1 Support in Firefox - SVG: Scalable Vector Graphics
Only stored in the DOM, no user interface. title Implemented. The title is displayed as a tooltip when the mouse hovers over the SVG object. metadata Implemented. Only stored in the DOM, no user interface. symbol Implemented. use Implemented. Doesn't
completely follow <svg:use> cascading rules (bug 265894). Doesn't deliver events to a SVGElementInstance tree (bug 265895). Conditional Processing Module switch Implemented. Image Module image Implemented. Style Module style Implemented. Shape Module pa...
Basic Transformations - SVG: Scalable Vector Graphics
Actually, that's its only purpose. An example: <svg width="30" height="10"> <g fill="red"> <rect x="0" y="0" width="10" height="10" /> <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. ...
Clipping and masking - SVG: Scalable Vector Graphics
now have a semicircle without having to deal with arcs in path elements. For the clipping, every path inside the clipPath is inspected and evaluated together with its stroke properties and transformation. Then every part of the target lying in a transparent area of the resulting clipPath's content will not be rendered. Color, opacity and such have no effect as long as they don't let parts vanish
completely. Masking The effect of masking is most impressively presented with a gradient. If you want an element to fade out, you can achieve this effect quite quickly with masks. <svg width="200" height="200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <linearGradient id="Gradient"> <stop offset="0" stop-color="black" /> <stop o...
Getting started - SVG: Scalable Vector Graphics
the SVG for other types of validation the version and baseProfile attributes should always be used instead. Both version and baseProfile attributes are deprecated in SVG 2. as an XML dialect, SVG must always bind the namespaces correctly (in the xmlns attribute). See the Namespaces Crash Course page for more info. The background is set to red by drawing a rectangle <rect> that covers the
complete image area. A green circle <circle> with a radius of 80px is drawn atop the center of the red rectangle (center of circle offset 150px to the right, and 100px downward from the top left corner). The text "SVG" is drawn. The interior of each letter is filled in with white. The text is positioned by setting an anchor where we want the midpoint to be: in this case, the midpoint should correspond t...
Tools for SVG - SVG: Scalable Vector Graphics
most prominent promoter of SVG. From this time stems the good support of SVG in Illustrator. However, the resulting SVG often shows some quirks, that make it necessary to post-process it for general applicability. Apache Batik URL: xmlgraphics.apache.org/batik/ Batik is a set of open source tools under the roof of the Apache Software Foundation. The toolkit is written in Java and offers almost
complete SVG 1.1 support, as well as some features that were originally planned for SVG 1.2. Batik offers a viewer (Squiggle), a rasterizer for PNG output, an SVG pretty printer to format SVG files, and a TrueType-to-SVG-Font converter. Together with Apache FOP Batik can transform SVG to PDF. Other renderers Several projects exist that can create a raster image from an SVG source. ImageMagick is one o...
Securing your site - Web security
There are a number of things you can do to help secure your site. This article offers an assortment of suggestions, as well as links to other articles providing more useful information. Note: This article is a work in progress, and is neither
complete nor does following its suggestions guarantee your site will be fully secure. User information security How to turn off form autocompletion Form fields support autocompletion in Gecko; that is, their values can be remembered and automatically brought back the next time the user visits your site. For certain types of data, you may wish to disable this feature. Privacy and the :visited selector This article discusses changes made to the getComputedStyle() method that eliminates the ability for malicious sites to figure out the user's ...
Subresource Integrity - Web security
n. How Subresource Integrity helps Using Content Delivery Networks (CDNs) to host files such as scripts and stylesheets that are shared among multiple sites can improve site performance and conserve bandwidth. However, using CDNs also comes with a risk, in that if an attacker gains control of a CDN, the attacker can inject arbitrary malicious content into files on the CDN (or replace the files
completely) and thus can also potentially attack all sites that fetch files from that CDN. Subresource Integrity enables you to mitigate some risks of attacks such as this, by ensuring that the files your web application or web document fetches (from a CDN or anywhere) have been delivered without a third-party having injected any additional content into those files -- and without any other changes of any...
Transport Layer Security - Web security
e like are correct will result in a server that just doesn't work. TLS 1.3 RFC 8446: TLS 1.3 is a major revision to TLS. TLS 1.3 includes numerous changes that improve security and performance. The goals of TLS 1.3 are: Remove unused and unsafe features of TLS 1.2. Include strong security analysis in the design. Improve privacy by encrypting more of the protocol. Reduce the time needed to
complete a handshake. TLS 1.3 changes much of the protocol fundamentals, but preserves almost all of the basic capabilities as previous versions of TLS. For the web, TLS 1.3 can be enabled without affecting compatibility with some rare exceptions (see below). The major changes in TLS 1.3 are: The TLS 1.3 handshake
completes in one round trip in most cases, reducing handshake latency. A server can e...
Using shadow DOM - Web Components
Dom = myCustomElem.shadowRoot; If you attach a shadow root to a custom element with mode: closed set, you won't be able to access the shadow DOM from the outside -- myCustomElem.shadowRoot returns null. This is the case with built in elements that contain shadow DOMs, such as <video>. Note: As this blog post shows, it is actually fairly easy to work around closed shadow DOMs, and the hassle to
completely hide them is often more than it's worth. If you are attaching a shadow DOM to a custom element as part of its constructor (by far the most useful application of the shadow DOM), you would use something like this: let shadow = this.attachShadow({mode: 'open'}); When you've attached a shadow DOM to an element, manipulating it is a matter of just using the same DOM APIs as you use for the regu...
Using templates and slots - Web Components
ate> element, since you are unlikely to need to define a pattern based on an already-rendered element. In addition, even if it is not already rendered, the purpose of the container as a template should be more semantically clear when using the <template>. In addition, <template> can have items directly added to it, like <td>, which would disappear when added to a <div>. Note: You can find this
complete example at element-details (see it running live also). Creating a template with some slots First of all, we use the <slot> element within a <template> element to create a new "element-details-template" document fragment containing some named slots: <template id="element-details-template"> <style> details {font-family: "Open Sans Light",Helvetica,Arial} .name {font-weight: bold; color: #...
Index - XSLT: Extensible Stylesheet Language Transformations
this data should eventually be presented. This intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network. 14 An Overview NeedsHelp, NeedsMarkupWork, Transforming_XML_with_XSLT, XML, XSLT The eXtensible Stylesheet Language/Transform is a very powerful language, and a
complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of Netscape's capabilities that follows. 15 For Further Reading NeedsContent, NeedsHelp, Transforming_XML_with_XSLT, XML, XSLT http://www.amazon.com/XSLT-Programme.../dp/0764543814 16 Resources Extensions, Nee...
An Overview - XSLT: Extensible Stylesheet Language Transformations
An XSLT stylesheet is an XML document. Unlike CSS, which has its own specialized syntax, an XSLT stylesheet is an XML document, which must conform to all XML rules, including well-formedness. So the model for transformation is that one XML document is used to transform another XML document. ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
sing 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 value of the parameter using $myOrder. However, the value needs to be an XPATH expression and not a string, so {$myOrder} is used. Using {} evaluates the content as an XPath expression. Once the transformation is
complete, the result is appended to the document, as shown in this example. Figure 7: Sorting based on div contentview 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 XSLTPro...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
with some glue code added into load the generated wasm, run it, etc. Open it in your browser and you'll see much the same output as the last example. Note: You could specify outputting just the JavaScript "glue" file* rather than the full HTML by specifying a .js file instead of an HTML file in the -o flag, e.g. emcc -o hello2.js hello2.c -O3 -s WASM=1. You could then build your custom HTML
completely from scratch, although this 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 th...
WebAssembly Concepts - WebAssembly
evelopers with the ability to create modules, memories, tables, and instances. Given a WebAssembly instance, JavaScript code can synchronously call its exports, which are exposed as normal JavaScript functions. Arbitrary JavaScript functions can also be synchronously called by WebAssembly code by passing in those JavaScript functions as the imports to a WebAssembly instance. Since JavaScript has
complete control over how WebAssembly code is downloaded, compiled and run, JavaScript developers could even think of WebAssembly as just a JavaScript feature for efficiently generating high-performance functions. In the future, WebAssembly modules will be loadable just like ES2015 modules (using <script type='module'>), meaning that JavaScript will be able to fetch, compile, and import a WebAssembly mod...
Understanding WebAssembly text format - WebAssembly
ule import the memory, or we can have the WebAssembly module create the memory and export it to JavaScript. For simplicity, let's create it in JavaScript then import it into WebAssembly. Our import statement is written as follows: (import "js" "mem" (memory 1)) The 1 indicates that the imported memory must have at least 1 page of memory (WebAssembly defines a page to be 64KB.) So let's see a
complete module that prints the string "Hi". In a normal compiled C program, you'd call a function to allocate some memory for the string, but since we're just writing our own assembly here and we own the entire linear memory, we can just write the string contents into global memory using a data section. Data sections allow a string of bytes to be written at a given offset at instantiation time and are ...