Search completed in 1.24 seconds.
419 results for "json":
Your results are loading. Please wait...
JSON.stringify() - JavaScript
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax JSON.stringify(value[, replacer[, space]]) Parameters value The value to convert to a JSON string. replacer Optional A function that alters the behavior of the stringification process, or an array of String and Number that serve as an allowlist for selecting/filtering the properties of the value object to be included in th...
....com/mdn/interactive-examples and send us a pull request. Syntax JSON.stringify(value[, replacer[, space]]) Parameters value The value to convert to a JSON string. replacer Optional A function that alters the behavior of the stringification process, or an array of String and Number that serve as an allowlist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string. space Optional A String or Number object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is ...
...he number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used. ...
...And 41 more matches
Working with JSON - Learn web development
Previous Overview: Objects Next JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You'll come across it quite often, so in this article we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand how to work with...
...u need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand how to work with data stored in JSON, and create your own JSON objects. No, really, what is JSON? ...
...an access data within it, and creating JSON. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects). Objective: To understand how to work with data stored in JSON, and create your own JSON objects. No, really, what is JSON? JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON. JSON exists as a string -- useful when you want to transmit data across a network. It ne...
...And 30 more matches
SyntaxError: JSON.parse: bad parsing - JavaScript
The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON. ...
... The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON. ...
... The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON. ...
...And 28 more matches
nsIJSON
dom/interfaces/json/nsIJSON.idlScriptable This interface provides a convenient way to encode and decode JSON strings from JavaScript code. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Note: This interface may only be used from JavaScript code, with the exception of the legacyDecodeToJSVal() method. However, you should use native JSON instead if at all possible. Implemented by: @mozilla.org/dom/json;1. ...
... Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Note: This interface may only be used from JavaScript code, with the exception of the legacyDecodeToJSVal() method. However, you should use native JSON instead if at all possible. Implemented by: @mozilla.org/dom/json;1. To create an instance, use: var nativeJSON = Components.classes["@mozilla.org/dom/json;1"] .createInstance(Components.interfaces.nsIJSON); Method overview Note: The IDL file has portions of the IDL commented out because they represent things that can't actually be properly described by IDL; however, for the purposes of this article, we'll pretend they can be and ignore that issue. JSObject decode(in AString s...
... decodeToJSVal() ...
...And 12 more matches
JSON.parse() - JavaScript
reviver Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. ...
...pt value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax JSON.parse(text[, reviver]) Parameters text The string to parse as JSON. See the JSON object for a description of JSON syntax. reviver Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. Return value The Object, Array, string, number, boolean, or null value corresponding to the given JSON text. Exceptions Throws a Synt...
...g to parse as JSON. See the JSON object for a description of JSON syntax. reviver Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. Return value The Object, Array, string, number, boolean, or null value corresponding to the given JSON text. Exceptions Throws a SyntaxError exception if the string to parse is not valid JSON. ...
...And 11 more matches
package.json - Archive of obsolete content
The package.json file contains manifest data for your add-on, providing not only descriptive information about the add-on for presentation in the Add-ons Manager, but other metadata required of add-ons. Some of its entries, such as icon, name, and description, have direct analogues in the install manifest format, and entries from package.json are written into the install manifest when the add-on is built using jpm xpi. Others, such as lib, permissions, and preferences, represent instructions to the jpm tool itself to generate and include particular code and data structures in your add-on. Creating a manifest The package.json file is initially generated in your add-on's root directory the first time you run jpm init. It looks like this (assuming the add-on's directory is "my-addon"): { ...
...in your add-on's root directory the first time you run jpm init. It looks like this (assuming the add-on's directory is "my-addon"): { "name": "my-addon", "title": "my-addon", "id": "jid1-1FERGV45e4f4f@jetpack", "description": "a basic add-on", "author": "", "license": "MPL-2.0", "version": "0.1" } If you are using the new jpm tool, you can easily access manifest data from package.json by requiring it like any other module: var title = require("./package.json").title; Key reference package.json may contain the following keys: author The name of the package's original author; this could be the name of a person or a company. Defaults to an empty string. It may include a optional URL in parentheses and an email address in angle brackets. This value will b...
...on New in jpm 1.2.0. Boolean value: true if the add-on contains an embedded WebExtension. homepage The URL of the add-on's website. This value will be used as the add-on's em:homepageURL element in its install.rdf. icon The path to an image file containing the icon for the add-on. Optional: you can have no icon field in package.json and put your icon named "icon.png" in the root directory of your add-on. If no icon is specified, the standard add-on icon will be used by default. When using jpm, using a relative path to the data directory (to make it re-usable for add-on HTML content) does not work. You can generate the URL to your add-on icon in the data directory using the URL format below, where "your-addon-n...
...And 7 more matches
JSON - JavaScript
The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can't be called or constructed, and aside from its two method properties, it has no interesting functionality of its own. Description JavaScript and JSON differences JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON. Objects and Arrays Property names must be double-quoted strings; trailing commas are forbidden. Numbers Leading zeros are prohibited. A decimal point must be followed by at least one digit. NaN and Infinity are unsupported. Any JSON text is a valid JavaScript expression... ...But only in JavaScript engines that have implemented the pr...
...rom it: some JavaScript is not JSON. Objects and Arrays Property names must be double-quoted strings; trailing commas are forbidden. Numbers Leading zeros are prohibited. A decimal point must be followed by at least one digit. NaN and Infinity are unsupported. Any JSON text is a valid JavaScript expression... ...But only in JavaScript engines that have implemented the proposal to make all JSON text valid ECMA-262. In engines that haven't implemented the proposal, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but their use in these features in JavaScript string literals is a SyntaxError. ...
...Script expression... ...But only in JavaScript engines that have implemented the proposal to make all JSON text valid ECMA-262. In engines that haven't implemented the proposal, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but their use in these features in JavaScript string literals is a SyntaxError. Consider this example where JSON.parse() parses the string as JSON and eval executes the string as JavaScript: let code = '"\u2028\u2029"' JSON.parse(code) // evaluates to "\u2028\u2029" in all engines eval(code) // throws a SyntaxError in old engines Other differences include allowing only double-quoted strings and having no provisions for undefined or comments. For those who wish to use a more human-friendly configu...
...And 7 more matches
PerformanceEntry.toJSON() - Web APIs
function run_PerformanceEntry() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
... Example The following example shows the use of the toJSON() method. function run_PerformanceEntry() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
... Example The following example shows the use of the toJSON() method. function run_PerformanceEntry() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...And 6 more matches
PushMessageData.json() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
... Examples self.addEventListener('push', function(event) { var myData = event.data.json(); // do something with your data }); Specifications Specification Status Comment Push APIThe definition of 'json()' in that specification. Working Draft Initial definition. ...
...And 4 more matches
Downloading JSON and JavaScript in extensions - Archive of obsolete content
Once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into JavaScript objects. This practice is dangerous and will not, in fact, pass an AMO review. So the extension will not be allowed to move out of the AMO sandbox. The practice is dangerous because the decoded JavaScript has full chrome privileges and could perform some nasty actions. ...
... decoded JavaScript has full chrome privileges and could perform some nasty actions. How could the JavaScript an extension downloads perform nasty actions? Fairly easy if the webserver where the JavaScript is hosted were to be hijacked or compromised. It happens to the best of us. AMO takes the threat very seriously. The good news is there are several ways to workaround the problem. ...
...ivileges and could perform some nasty actions. How could the JavaScript an extension downloads perform nasty actions? Fairly easy if the webserver where the JavaScript is hosted were to be hijacked or compromised. It happens to the best of us. AMO takes the threat very seriously. The good news is there are several ways to workaround the problem. ...
...And 3 more matches
Test your skills: JSON - Learn web development
This aim of this skill test is to assess whether you've understood our Working with JSON article. Note: You can try out the solution in the interactive editor below. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the example below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). JSON 1 The one and only task in this article concerns accessing JSON data and using it in your page. JSON data about some mother cats and their kittens is available in sample.json. ...
...ere is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). JSON 1 The one and only task in this article concerns accessing JSON data and using it in your page. JSON data about some mother cats and their kittens is available in sample.json. The JSON is loaded into the page as a text string and made available in the catString parameter of the displayCatInfo() function, called when the provided promise chain (which starts by fetching the JSON data) is fulfilled. Your task is to fill in the missing parts of the displayCatInfo() function to store: The names of the three mother cats, separated by commas, in the motherInfo variable. The total ...
...ON data) is fulfilled. Your task is to fill in the missing parts of the displayCatInfo() function to store: The names of the three mother cats, separated by commas, in the motherInfo variable. The total number of kittens, and how many are male and female, in the kittenInfo variable. The values of these variables are then printed to the screen inside paragraphs. Some hints/questions: The JSON data is provided as text inside the displayCatInfo() function. You'll need to parse it into JSON before you can get any data out of it. You'll probably want to use an outer loop to loop through the cats and add their names to the motherInfo variable string, and an inner loop to loop through all the kittens, add up the total of all/male/female kittens, and add those details to the kittenInfo vari...
...And 3 more matches
performance.toJSON() - Web APIs
Recommendation Defines toJson(). ...
... Recommendation Defines toJson(). ...
... Recommendation Defines toJson(). ...
...And 3 more matches
PerformanceServerTiming.toJSON - Web APIs
Working Draft Initial definition. ...
... Working Draft Initial definition. ...
... Return value A DomString containing JSON. Exceptions None. ...
...And 3 more matches
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
JavaScript Object Notation (JSON) is a data-interchange format. Although not a strict subset, JSON closely resembles a subset of JavaScript syntax. Though many programming languages support JSON, JSON is especially useful for JavaScript-based apps, including websites and browser extensions. JSON can 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. ...
..., 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. ...
...alize 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. ...
...And 2 more matches
AuthenticatorResponse.clientDataJSON - Web APIs
The clientDataJSON property of the AuthenticatorResponse interface stores a JSON string in an ArrayBuffer, representing the client data that was passed to CredentialsContainer.create() or CredentialsContainer.get(). This property is only accessed on one of the child objects of AuthenticatorResponse, specifically AuthenticatorAttestationResponse or AuthenticatorAssertionResponse. Syntax var arrayBuffer = AuthenticatorAttestationResponse.clientDataJSON; var arrayBuffer = AuthenticatorAssertionResponse.clientDataJSON; Value An ArrayBuffer. ...
...e() or CredentialsContainer.get(). This property is only accessed on one of the child objects of AuthenticatorResponse, specifically AuthenticatorAttestationResponse or AuthenticatorAssertionResponse. Syntax var arrayBuffer = AuthenticatorAttestationResponse.clientDataJSON; var arrayBuffer = AuthenticatorAssertionResponse.clientDataJSON; Value An ArrayBuffer. Properties After the clientDataJSON object is converted from an ArrayBuffer to a JavaScript object, it will have the following properties: type A string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created. challenge The base64url encoded version of the cryptographic challenge sent from the relying party's server. The original value is passed via PublicK...
...en binding ID which was used for the communication. Should this property be absent, it would indicate that the client does not support token binding. ...
...And 2 more matches
JS_ParseJSON
This article covers features introduced in SpiderMonkey 1.8.6 Parse a string using the JSON syntax described in ECMAScript 5 and return the corresponding value. Syntax JSBool JS_ParseJSON(JSContext *cx, const jschar *chars, uint32 len, jsval *vp); JSBool JS_ParseJSONWithReviver(JSContext *cx, const jschar *chars, uint32 len, jsval reviver, jsval *vp); Name Type Description cx JSContext * Pointer to a JS context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ch JSObject * The object to be searched. chars const jschar * The characters of the string. len uint32 The length of the string. index jsint (in JS_ParseJSONWithReviver only) A reviver function to apply to the created value after parsing; see JSON.parse. vp jsval...
... uint32 The length of the string. index jsint (in JS_ParseJSONWithReviver only) A reviver function to apply to the created value after parsing; see JSON.parse. vp jsval * Out parameter. *vp receives the value after parsing (and optionally, processing by the reviver). If an error occurs, the value left in *vp is undefined. Description Use these functions to parse a sequence of characters as JSON. The parsing rules applied by these methods are exactly those specified by ECMAScript 5. Various JSON extensions like trailing commas, unquoted property names, more generous number parsing, and so on are not supported. ...
...ng by the reviver). If an error occurs, the value left in *vp is undefined. Description Use these functions to parse a sequence of characters as JSON. The parsing rules applied by these methods are exactly those specified by ECMAScript 5. ...
... occurs, the value left in *vp is undefined. Description Use these functions to parse a sequence of characters as JSON. The parsing rules applied by these methods are exactly those specified by ECMAScript 5. ...
URL.toJSON() - Web APIs
Web › API › URL › toJSON
Living Standard Initial definition. ...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
...he URL, although in practice it seems to have the same effect as URL.toString(). Note: This feature is available in Web Workers. Syntax const href = url.toJSON() Return value A USVString. Examples const url = new URL("/docs/Web/API/URL/toString"); url.toJSON(); // should return the URL as a string Specifications Specification Status Comment URLThe definition of 'toJSON()' in that specification. Living Standard Initial definition. ...
Body.json() - Web APIs
Web › API › Body › json
The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. Syntax response.json().then(data => { // do something with your data }); Parameters None. Return value A Promise that resolves to a JavaScript object. This object could be anything that can be represented by JSON -- an object, an array, a string, a number... Example In our fetch json example (run fetch json live), we create a new request using the Request() constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const myList = do...
...mple (run fetch json live), we create a new request using the Request() constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const myList = document.querySelector('ul'); const myRequest = new Request('products.json'); fetch(myRequest) .then(response => response.json()) .then(data => { for (const product of data.products) { let listItem = document.createElement('li'); listItem.appendChild( document.createElement('strong') ).textContent = product.Name; listItem.append( ` can be found in ${ product.Location }. Cost: ` ); listItem.ap...
... Living Standard Initial definition ...
PaymentAddress.toJSON() - Web APIs
Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
...inition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternettoJSON()Chrome Full support 61Disabled Full support 61Disabled Disabled From version 61: this feature is behind the #web-payments preference (needs to be set to Enabled). To change preferences in Chrome, visit chrome://flags.Edge Full support 15Firefox F...
PerformanceNavigationTiming.toJSON() - Web APIs
The toJSON() method is a serializer - it returns a JSON representation of the PerformanceNavigationTiming object. Syntax json = resourcePerfEntry.toJSON(); Arguments None Return value json A JSON object that is the serialization of the PerformanceNavigationTiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. ...
...ON(); Arguments None Return value json A JSON object that is the serialization of the PerformanceNavigationTiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. Example // Get a resource performance entry var perfEntries = performance.getEntriesByType("navigation"); var entry = perfEntries[0]; // Get the JSON and log it var json = entry.toJSON(); var s = JSON.stringify(json); console.log("PerformanceNavigationTiming.toJSON() = " + s); Specifications Specification Status Comment Navigation Timing Level 2The definition of 'toJSON()' in that specification. Working Draft Initial definition. ...
PerformanceResourceTiming.toJSON() - Web APIs
The toJSON() method is a serializer that returns a JSON representation of the PerformanceResourceTiming object. Syntax json = resourcePerfEntry.toJSON(); Arguments None Return value json A JSON object that is the serialization of the PerformanceResourceTiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. ...
...toJSON(); Arguments None Return value json A JSON object that is the serialization of the PerformanceResourceTiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. Example // Get a resource performance entry var perfEntries = performance.getEntriesByType("resource"); var entry = perfEntries[0]; // Get the JSON and log it var json = entry.toJSON(); var s = JSON.stringify(json); console.log("PerformanceEntry.toJSON = " + s); Specifications Specification Status Comment Resource Timing Level 2The definition of 'toJSON' in that specification. Working Draft ...
RTCIceCandidate. toJSON() - Web APIs
The RTCIceCandidate method toJSON() converts the RTCIceCandidate on which it's called into JSON in the form of an RTCIceCandidateInit object. Syntax json = rtcIceCandidate.toJSON(); Return value An object conforming to the RTCIceCandidateInit dictionary, whose members' values are set to the corresponding values in the RTCIceCandidate object. You can then get a stringified version of the object by calling stringify() on the returned object. See the example below. Example This simple example obtains a JSON string representing an RTCIceCandidate found in the variable candidate. ...
...lue An object conforming to the RTCIceCandidateInit dictionary, whose members' values are set to the corresponding values in the RTCIceCandidate object. You can then get a stringified version of the object by calling stringify() on the returned object. See the example below. Example This simple example obtains a JSON string representing an RTCIceCandidate found in the variable candidate. var jsonString = candidate.toJSON().stringify(); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidate.toJSON()' in that specification. Candidate Recommendation Initial definition. ...
RTCSessionDescription.toJSON() - Web APIs
The RTCSessionDescription.toJSON() method generates a JSON description of the object. Both properties, type and sdp, are contained in the generated JSON. Syntax var jsonValue = sd.toJSON(); The result value is a JSON object containing the following values: "type", containing the value of the RTCSessionDescription.type property and can be one of the following values: "offer", "answer", "pranswer" or null. "sdp", containing a DOMString, or null, with the SDP message corresponding to RTCSessionDescription.sdp property. Example // sd is a RTCSessionDescriptor alert(JSON.stringify(sd)); // This call the toJSON() method behind the scene. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTC...
...containing a DOMString, or null, with the SDP message corresponding to RTCSessionDescription.sdp property. Example // sd is a RTCSessionDescriptor alert(JSON.stringify(sd)); // This call the toJSON() method behind the scene. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCSessionDescription: toJSON()' in that specification. Candidate Recommendation Initial specification. ...
Date.prototype.toJSON() - JavaScript
The toJSON() method returns a string representation of the Date object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.toJSON() Return value A string representation of the given date. Description Date instances refer to a specific point in time. Calling toJSON() returns a string (using toISOString()) representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization. ...
...s and send us a pull request. Syntax dateObj.toJSON() Return value A string representation of the given date. Description Date instances refer to a specific point in time. Calling toJSON() returns a string (using toISOString()) representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization. Examples Using toJSON() var jsonDate = (new Date()).toJSON(); var backToDate = new Date(jsonDate); console.log(jsonDate); //2015-10-26T07:46:36.611Z Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toJSON' in that specification. ...
JSON viewer - Firefox Developer Tools
The JSON viewer is new in Firefox 44. Before Firefox 53, the JSON viewer is enabled by default only in Firefox Developer Edition and Firefox Nightly. To enable this feature in other release channels, set the devtools.jsonview.enabled preference to true. From Firefox 53 onwards, the JSON viewer is also enabled by default in Beta and the normal release version of Firefox. Firefox includes a JSON viewer. If you open a JSON file in the browser, or view a remote URL with the Content-Type set to application/json, it is parsed and given syntax highlighting. Arrays and objects are shown collapsed, and you can expand them using the "+" icons. The JSON viewer provides a search box that you can use to filter the JSON. You can also view the raw JSON and pretty-print it. Finally, if the d...
DOMPointReadOnly.toJSON() - Web APIs
The DOMPointReadOnly method toJSON() returns a DOMPointInit object giving the JSON form of the point object. Syntax pointJSON = DOMPointReadOnly.toJSON(); Parameters None. Return value A new DOMPointInit object whose properties are set to the values in the DOMPoint or DOMPointReadOnly on which the method was called. Example This example creates a DOMPoint object representing the top-left corner of the current window, in screen coordinates, then converts that to JSON. var topLeft = new DOMPoint(window.screenX, window.screenY); var pointJSON = topLeft.toJSON(); Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMPointReadOnly.toJSON()' in that specification. Candidate Recommendation Initial definition ...
PushSubscription.toJSON() - Web APIs
The toJSON() method of the PushSubscription interface is a standard serializer: it returns a JSON representation of the subscription properties, providing a useful shortcut. Syntax mySubscription = subscription.toJSON() Parameters None. Returns A JSON object. It currently only contains the subscription endpoint, as an endpoint member. Example navigator.serviceWorker.ready.then(function(reg) { reg.pushManager.getSubscription().then(function(subscription) { var mySubscription = subscription.toJSON(); // do something with subscription details }) }); Specifications Specification Status Comment Push APIThe definition of 'PushSubscription: toJSON' in that specification. Working Draft ...
JXON - Archive of obsolete content
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 imagine you have this sample XML document: example.x...
...The Object.freeze() method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from bei...
...The Object.freeze() method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from bei...
...And 23 more matches
Index - Web APIs
Web › API › Index
219 AuthenticatorAssertionResponse.userHandle API, AuthenticatorAssertionResponse, Property, Reference, Web Authentication API, WebAuthn The userHandle read-only property of the AuthenticatorAssertionResponse interface is an ArrayBuffer object which is an opaque identifier for the given user. Such an identifier can be used by the relying party's server to link the user acco...
...e, Web Authentication API, WebAuthn The AuthenticatorResponse interface of the Web Authentication API is the base interface for interfaces that provide a cryptographic root of trust for a key pair. The child interfaces include information from the browser such as the challenge origin and either may be returned from PublicKeyCredential.response. 224 AuthenticatorResponse.clientDataJSON API, AuthenticatorResponse, Property, Reference, Web Authentication API, WebAuthn The clientDataJSON property of the AuthenticatorResponse interface stores a JSON string in an ArrayBuffer, representing the client data that was passed to CredentialsContainer.create() or CredentialsContainer.get(). This property is only accessed on one of the child objects of AuthenticatorResponse, specif...
...-only property of the Body mixin contains a Boolean that indicates whether the body has been read yet. 359 Body.formData() API, BODY, Experimental, Fetch, Fetch API, FormData, Method, NeedsExample, Reference The formData() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object. 360 Body.json() API, BODY, Experimental, Fetch, JSON, Method, Reference The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. 361 Body.text() API, BODY, Experimental, Fetch, Method, Reference, Text The text() method of the Body mixin takes a Response stream and r...
...And 17 more matches
TypeScript support in Svelte - Learn web development
e stores.js and localStore.js files to TypeScript. Tip: the script npm run validate, which uses the svelte-check tool, will only check our application's .svelte files. If you want to also check the .ts files you can run npm run validate && npx tsc --noemit, which tells the TypeScript compiler to check for errors without generating the .js output files. You could even add a script to your package.json file that runs that command. We'll start with stores.js. Rename the file to stores.ts. Set the type of our initialTodos array to TodoType[]. This is how the contents will end up: // stores.ts import { writable } from 'svelte/store' import { localStore } from './localStore.js' import type { TodoType } from './types/todo.type' export const alert = writable('Welcome to the To-Do lis...
.... Update the import statement in stores.ts, like so: import { localStore } from './localStore' Start by renaming the file to localStore.ts. TypeScript is telling us to specify the type of the key, initial, and value variables. The first one is easy -- the key of our local web storage should be a string. But initial and value should be any object that could be converted to a valid JSON string with the JSON.stringify method. So it is in fact any JavaScript object with a couple limitations, for example undefined, functions, and symbols are not valid JSON values. So we'll create the type JsonValue to specify these conditions. Create the file json.type.ts in the types folder. Give it the following content: export type JsonValue = string | number | boolean | null | Js...
...fy method. So it is in fact any JavaScript object with a couple limitations, for example undefined, functions, and symbols are not valid JSON values. So we'll create the type JsonValue to specify these conditions. Create the file json.type.ts in the types folder. Give it the following content: export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue } The | operator lets us declare variables that could store values of two or more types. A JsonValue could be a string, a number, a boolean, and so on. In this case we are also making use of recursive types, to specify that a JsonValue can have an array of JsonValue, and also an object with properties of type JsonValue. We will import our JsonValue type and use it accordingly. Updat...
...And 16 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
e taken to avoid evaluating arbitrary text as HTML. Failure to do so can lead to execution or remote scripts, and in the worst cases to privilege escalation which can leave a user's PC open to remote attack. Building DOM Trees In most cases, DOM trees should be built exclusively with DOM creation methods. The following methods will all safely create a DOM tree without risk of remote execution. ...
...evaluating arbitrary text as HTML. Failure to do so can lead to execution or remote scripts, and in the worst cases to privilege escalation which can leave a user's PC open to remote attack. Building DOM Trees In most cases, DOM trees should be built exclusively with DOM creation methods. The following methods will all safely create a DOM tree without risk of remote execution. ...
...ch can leave a user's PC open to remote attack. Building DOM Trees In most cases, DOM trees should be built exclusively with DOM creation methods. The following methods will all safely create a DOM tree without risk of remote execution. JSON Templating jsonToDOM.namespaces = { html: "http://www.w3.org/1999/xhtml", xul: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" }; jsonToDOM.defaultNamespace = jsonToDOM.namespaces.html; function jsonToDOM(jsonTemplate, doc, nodes) { function namespace(name) { var reElemNameParts = /^(?:(.*):)?(.*)$/.exec(name); return { namespace: jsonToDOM.namespaces[reElemNameParts[1]], shortName: reElemNameParts[2] }; } // Note that 'elemNameOrArray' is: either the full element name (eg. [html:]div) or an array of...
...And 11 more matches
Using the Performance API - Web APIs
ethod returns a timestamp (of type DOMHighResTimeStamp) that is a discrete point in time. By calling this method before and after a task, the time it takes to do the task can be measured. ...
... a discrete point in time. By calling this method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var startTime; var endTime; startTime = performance.now(); do_task(); endTime = performance.now(); return (endTime - startTime); } Serializing the Performance object JSON serialization of the Performance object is done via the toJSON() method. ...
...s method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var startTime; var endTime; startTime = performance.now(); do_task(); endTime = performance.now(); return (endTime - startTime); } Serializing the Performance object JSON serialization of the Performance object is done via the toJSON() method. ...
...And 11 more matches
cfx - Archive of obsolete content
h are more likely to be useful to SDK developers than to add-on developers. cfx init Create a new directory called "my-addon", change into it, and run cfx init. ...
... will create an skeleton add-on, as a starting point for your own add-on development, with the following file structure: my-addon data docs main.md lib main.js package.json README.md tests test-main.js cfx run This command is used to run the add-on. Called with no options it looks for a file called package.json in the current directory, loads the corresponding add-on, and runs it under the version of Firefox it finds in the platform's default install path. Supported Options You can point cfx run at a different package.json file using the --pkgdir option, and pass arguments to your add-on using the --static-args option. You can specify a different version of the host application using the --binary opt...
... as a path relative to the current directory. See "Using --profiledir" for more information. --package-path=PACKAGEPATH Extra directories for package search. --pkgdir=PKGDIR Use an add-on located in PKGDIR. PKGDIR may be specified as a full path or as a path relative to the current directory. --static-args=STATIC_ARGS Pass arguments to your add-on, in JSON format. Experimental Options -a APP, --app=APP By default, cfx run uses Firefox as the host application. This option enables you to select a different host. You can specify "firefox", "xulrunner", "fennec", or "thunderbird". But note that at present only Firefox is supported. --no-run With this option cfx will not execute the command, but will print out the co...
...And 10 more matches
Promises - Archive of obsolete content
less complexity. Representative Example Usage Components.utils.import("resource://gre/modules/osfile.jsm"); Task.spawn(function* () { // Retrieve file metadata to check modification time. let info = yield OS.File.stat(configPath); if (info.lastModificationDate <= timestamp) return; timestamp = info.lastModificationDate; // Read the file as a UTF-8 string, parse as JSON. let config = JSON.parse( yield OS.File.read(configPath, { encoding: "utf-8" })); let files = []; // Get the directory contents from a list of directories. for (let dir of config.directories) { // Iterate over the contents of the directory. let iter = new OS.File.DirectoryIterator(dir); yield iter.forEach(entry => { if (!entry.isDir) ...
....add(data); } // Now write the processed files back out, as a binary blob. yield OS.File.writeAtomic(config.processedPath, processor.process(), { tmpPath: config.processedPath + "." + Math.random() }); // And write out a new config file. config.indexStats = processor.stats; yield OS.File.writeAtomic(configPath, JSON.stringify(config), { tmpPath: configPath + "." + Math.random(), encoding: "UTF-8" }) timestamp = new Date; }); HTTP Requests HTTP requests should, in nearly all circumstances, be made via the standard XMLHttpRequest API. While this API does not have direct support for promises, its standard usage is very easy to adapt to a promis...
.... Moreover, many third-party wrappers for the XMLHttpRequest API now support Promises out of the box. Example Direct Usage Task.spawn(function* () { // Make the initial request. let resp = yield new Promise((resolve, reject) => { let xhr = new XMLHttpRequest; xhr.onload = resolve; xhr.onerror = reject; xhr.open("GET", dataURL); xhr.responseType = "json"; xhr.send(); }); let data = resp.target.response; // Use the response to construct form data object for the // second request. let form = new FormData; form.append("id", data.id); form.append("content", data.content); // Make the second request. resp = yield new Promise((resolve, reject) => { let xhr = new XMLHttpRequest; xhr.onload ...
...And 10 more matches
Using Fetch - Web APIs
cross site session using fetch. Set-Cookie headers from other sites are silently ignored. fetch won't send cookies, unless you set the credentials init option. (Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.) A basic fetch request is really simple to set up. Have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch() takes one argument -- the path to the resource you want to fetch -- and returns a promise containing the response (a Response object). This is just an HTTP response, not the actual JSON. To extract the JSON bo...
... .then(data => console.log(data)); Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch() takes one argument -- the path to the resource you want to fetch -- and returns a promise containing the response (a Response object). This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.) Note: The Body mixin also has similar methods to extract other types of body content; see the Body section for more. Fetch requests are controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's retrieving. Supplying request options The...
...ta(url = '', data = {}) { // Default options are marked with * const response = await fetch(url, { method: 'POST', // *GET, POST, PUT, DELETE, etc. ...
...And 8 more matches
Ajax navigation example - Web APIs
hree pages (first_page.php, second_page.php and third_page.php). To see how it works, please create the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): Note: For fully integrating the <form> elements within this mechanism, please take a look at the paragraph Submitting forms and uploading files. first_page.php: <?php $page_title = "First page"; $as_json = false; if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { $as_json = true; ob_start(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>This paragraph is shown only when the navigation starts from <stron...
...tml> <head> <?php include "include/header.php"; echo "<title>" . $page_title . ...
... include "include/header.php"; echo "<title>" . $page_title . ...
...And 8 more matches
Introduction to automated testing - Learn web development
o inside your test directory and initialize it, with the following: cd node-test npm init This second command will ask you many questions to find out the information required to set up the project; you can just select the defaults for now. Once all the questions have been asked, it will ask you if the information entered is OK. type yes and press Enter/Return and npm will generate a package.json file in your directory. This file is basically a config file for the project. You can customize it later, but for now it'll look something like this: { "name": "node-test", "version": "1.0.0", "description": "Test for npm projects", "main": "index.js", "scripts": { "test": "test" }, "author": "Chris Mills", "license": "MIT" } With this, you are ready to move on. Setting u...
...to first install it via npm, then require any dependencies at the top of the gulpfile.js file, then add your test(s) to the bottom of it, and finally add the name of your task inside the default task. html-tidy Install using the following line: npm install --save-dev gulp-htmltidy Note: --save-dev adds the package as a dependency to your project. If you look in your project's package.json file, you'll see an entry for it in the devDependencies property. Add the following dependency to gulpfile.js: const htmltidy = require('gulp-htmltidy'); Add the following test to the bottom of gulpfile.js: function html(cb) { return gulp.src('src/index.html') .pipe(htmltidy()) .pipe(gulp.dest('build')); cb(); } Here we are grabbing our development index.ht...
...best solution out there, but it works for us and it is fairly accessible to beginners. You could also try using other solutions: Grunt works in a very similar way to Gulp, except that it relies on tasks specified in a config file, rather than using written JavaScript. See Getting started with Grunt for more details. You can also run tasks directly using npm scripts located inside your package.json file, without needing to install any kind of extra task runner system. This works on the premise that things like Gulp plugins are basically wrappers around command line tools. So, if you can work out how to run the tools using the command line, you can then run them using npm scripts. It is a bit trickier to work with, but can be rewarding for those who are strong with their command line skills.
...And 7 more matches
Package management basics - Learn web development
ll it as part of an experimental app. Setting up the app as an npm package First of all, create a new directory to store our experimental app in, somewhere sensible that you'll find again. ...
...Just press Return to accept the default parcel-experiment. version: The starting version number for the app: Again, Just press Return to accept the default 1.0.0. description: A quick description of the app's purpose. Type in something really simple, like "A simple npm package to learn about using npm", then press Return. ...
...mmand, git repository, and keywords: press Return to leave each of these blank for now. author: The author of the project. Type your own name, and press Return. license: The license to publish the package under: Press Return to accept the default for now. Press Return one more time to accept these settings. Go into your parcel-experiment directory and you should now find you've got a package.json file. Open it up and it should look something like this: { "name": "parcel-experiment", "version": "1.0.0", "description": "A simple npm package to learn about using npm", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Chris Mills", "license": "ISC" } So this is the config file that defines your package. This is good for ...
...And 7 more matches
nsISessionStore
ode forgetClosedWindow( in unsigned long aIndex ); Parameters aIndex Is the index of the closed window to be removed (FIFO ordered). Return value Exceptions thrown NS_ERROR_INVALID_ARG When aIndex does not map to a closed window. getBrowserState() Returns the current state of all of windows and all of their tabs. AString getBrowserState(); Parameters None. Return value A JSON string representing the current state of all windows in the web browser. getClosedTabCount() Returns the number of restorable tabs for a given window. unsigned long getClosedTabCount( in nsIDOMWindow aWindow ); Parameters aWindow The window whose restorable tab count should be returned. Return value The number of restorable tabs in the window. getClosedTabData() Returns a list of ...
...DOMWindow aWindow ); Parameters aWindow The window whose restorable tab count should be returned. Return value The number of restorable tabs in the window. getClosedTabData() Returns a list of closed tabs for a specified window. AString getClosedTabData( in nsIDOMWindow aWindow ); Parameters aWindow The browser window whose closed tab list is to be retrieved. Return value A JSON string representing the list of closed tabs for the window specified by aWindow. The list is in last in/first out (LIFO) order, so that the first item in the list is the last tab that was closed. getClosedWindowCount() Returns the number of restorable windows. unsigned long getClosedWindowCount(); Parameters None. Return value The number of restorable windows. getClosedWindowData() Retu...
...st in/first out (LIFO) order, so that the first item in the list is the last tab that was closed. getClosedWindowCount() Returns the number of restorable windows. unsigned long getClosedWindowCount(); Parameters None. Return value The number of restorable windows. getClosedWindowData() Returns a list of closed windows. AString getClosedWindowData(); Parameters None. ...
...And 7 more matches
Visual typescript game engine - Game development
Project structure builds/ is autogenerated. Don't edit or add content in this folder. src,/ is the main client part (Browser web application). Main file: app.ts src/libs/ is a common and smart pack of classes, interfaces etc. easy access. server/ folder is fully independent server size. I use one git repo but consider '/server' represent the standalone application. ...
...ain client part (Browser web application). Main file: app.ts src/libs/ is a common and smart pack of classes, interfaces etc. easy access. server/ folder is fully independent server size. I use one git repo but consider '/server' represent the standalone application. There's server package.json independently from the client part also config is not common. I just like it like that. ...
...er web application). Main file: app.ts src/libs/ is a common and smart pack of classes, interfaces etc. easy access. server/ folder is fully independent server size. I use one git repo but consider '/server' represent the standalone application. There's server package.json independently from the client part also config is not common. I just like it like that. ...
...And 6 more matches
Handling common JavaScript problems - Learn web development
start, the JavaScript console will report errors in your code. Make a local copy of our broken-ajax.html example (see the source code also). If you look at the console, you'll see the error message "Uncaught TypeError: can't access property "length", heroes is undefined", and the referenced line number is 49. ...
...ole will report errors in your code. Make a local copy of our broken-ajax.html example (see the source code also). If you look at the console, you'll see the error message "Uncaught TypeError: can't access property "length", heroes is undefined", and the referenced line number is 49. ...
...the console, you'll see the error message "Uncaught TypeError: can't access property "length", heroes is undefined", and the referenced line number is 49. If we look at the source code, the relevant code section is this: function showHeroes(jsonObj) { let heroes = jsonObj['members']; for(i = 0; i < heroes.length; i++) { ... So the code falls over as soon as we try to access a property of jsonObj (which as you might expect, is supposed to be a JSON object). ...
...And 6 more matches
Signaling and video calling - Web APIs
E subsystem instructs you to send signaling data to the other peer, you do so, and the other peer knows how to receive this information and deliver it to its own ICE subsystem. All you have to do is channel the information back and forth. The contents don't matter at all to the signaling server. Readying the chat server for signaling Our chat server uses the WebSocket API to send information as JSON strings between each client and the server. The server supports several message types to handle tasks, such as registering new users, setting usernames, and sending public chat messages. To allow the server to support signaling and ICE negotiation, we need to update the code. We'll have to allow directing messages to one specific user instead of broadcasting to all connected users, and ensure un...
... and delivered, without the server needing to know what they are. This lets us send signaling messages using this same server, instead of needing a separate server. Let's take a look which changes we need to make to the chat server support WebRTC signaling. This is in the file chatserver.js. First up is the addition of the function sendToOneUser(). As the name suggests, this sends a stringified JSON message to a particular username. function sendToOneUser(target, msgString) { var isUnique = true; var i; for (i=0; i<connectionArray.length; i++) { if (connectionArray[i].username === target) { connectionArray[i].send(msgString); break; } } } This function iterates over the list of connected users until it finds one matching the specified username, then sends the m...
...get, msgString) { var isUnique = true; var i; for (i=0; i<connectionArray.length; i++) { if (connectionArray[i].username === target) { connectionArray[i].send(msgString); break; } } } This function iterates over the list of connected users until it finds one matching the specified username, then sends the message to that user. The parameter msgString is a stringified JSON object. We could have made it receive our original message object, but in this example it's more efficient this way. Since the message has already been stringified, we can send it with no further processing. Each entry in connectionArray is a WebSocket object, so we can just call its send() method directly. Our original chat demo didn't support sending messages to a specific user. The next task ...
...And 6 more matches
cfx to jpm - Archive of obsolete content
d in the add-on's Install Manifest (install.rdf) file. The ID is used for a variety of purposes. For example: addons.mozilla.org uses it to distinguish between new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on. ...
...ling with cfx When you use cfx, the ID is taken from the id field in the add-on's package.json file. You can edit this file to create your own ID, but if you don't, cfx will generate one for you, which will look something like "jid1-F3BoogbjQJE67A". Add-on IDs need to be one of two types: a GUID or a string that includes an "@" symbol. The SDK expects the latter format, and if the ID in package.json doesn't contain "@", then cfx xpi will append "@jetpack" to the package.json field, and make that the add-on ID. So: if you never did anything with IDs when using cfx, then the value in your add-on's package.json will be something like "jid1-F3BoogbjQJE67A", and the corresponding ID in the install.rdf will be "jid1-F3BoogbjQJE67A@jetpack". ID handling with jpm When you create an XPI with jpm x...
...then cfx xpi will append "@jetpack" to the package.json field, and make that the add-on ID. So: if you never did anything with IDs when using cfx, then the value in your add-on's package.json will be something like "jid1-F3BoogbjQJE67A", and the corresponding ID in the install.rdf will be "jid1-F3BoogbjQJE67A@jetpack". ID handling with jpm When you create an XPI with jpm xpi: if the package.json does not include an id field, then the ID written into the install.rdf is the value of the name field prepended with "@". if the package.json does include an id field, and it contains "@", then this is written into the install.rdf as the add-on ID. if the package.json does include an id field, and it does not contain "@", then jpm xpi raises an error and the XPI will not be built. What you ne...
...And 5 more matches
jpm - Archive of obsolete content
to some URL. jpm sign Package your add-on as an XPI file, and then retrieve a new XPI signed by Mozilla. jpm init This command initializes a new add-on from scratch. Create a new directory, change into it, and run jpm init. ...
... initializes a new add-on from scratch. Create a new directory, change into it, and run jpm init. 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. title name: this defaults to the name of the directory in which you are running jpm init. Unless an id field is present in package.json, jpm prepends "@" to name and use the result as the id field in 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...
.... 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. ...
...And 5 more matches
SubtleCrypto.importKey() - Web APIs
cepts several import formats: see Supported formats for details. Syntax const result = crypto.subtle.importKey( format, keyData, algorithm, extractable, usages ); Parameters format is a string describing the data format of the key to import. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. jwk: JSON Web Key format. keyData is an ArrayBuffer, a TypedArray, a DataView, or a JSONWebKey object containing the key in the given format. algorithm is a dictionary object defining the type of key to import and providing extra algorithm-specific parameters. For RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP: Pass an RsaHashedImportParams object. For ECDSA or ECDH: Pass an EcKeyImportParams obje...
...e promise is rejected when one of the following exceptions is encountered: SyntaxError Raised when keyUsages is empty but the unwrapped key is of type secret or private. TypeError Raised when trying to use an invalid format or if the keyData is not suited for that format. Supported formats This API supports four different key import/export formats: Raw, PKCS #8, SubjectPublicKeyInfo, and JSON Web Key. Raw You can use this format to import or export AES or HMAC secret keys, or Elliptic Curve public keys. In this format the key is supplied as an ArrayBuffer containing the raw bytes for the key. PKCS #8 You can use this format to import or export RSA or Elliptic Curve private keys. The PKCS #8 format is defined in RFC 5208., using the ASN.1 notation: PrivateKeyInfo ::= SEQUENCE { ...
...jLaDF743LgM/JLq CDPUBUA3HLsZUhKm3BbSkd7Q9Ngkjv3+yByo4/fL+fkYRa8j9Ypa2N0Iw53LFb3B gQIDAQAB -----END PUBLIC KEY----- Just as with PKCS #8, to get this into a format you can give to importKey() you need to do two things: base64-decode the part between header and footer, using window.atob(). convert the resulting string into an ArrayBuffer. See the Examples section for more concrete guidance. ...
...And 5 more matches
Writing WebSocket client applications - Web APIs
no guarantee that calling the send() method immediately after creating a WebSocket object will be successful. ...
...er creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an onopen event handler to do the work: exampleSocket.onopen = function (event) { exampleSocket.send("Here's some text that the server is urgently awaiting!"); }; Using JSON to transmit objects One handy thing you can do is use JSON to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data: // Send text to all users through the server function sendText() { // Construct a msg object containing the data the server needs to process the message from the chat client. var msg = { type: "message", text: docu...
... document.getElementById("text").value = ""; } Receiving messages from the server WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. ...
...And 5 more matches
eval() - JavaScript
n be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate. Fortunately, there's a very good alternative to eval(): simply using window.Function(). See this example of how to convert code using a dangerous eval() to using Function(), see below. ...
...type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate. Fortunately, there's a very good alternative to eval(): simply using window.Function(). See this example of how to convert code using a dangerous eval() to using Function(), see below. ...
...e. Fortunately, there's a very good alternative to eval(): simply using window.Function(). See this example of how to convert code using a dangerous eval() to using Function(), see below. Bad code with eval(): function looseJsonParse(obj){ return eval("(" + obj + ")"); } console.log(looseJsonParse( "{a:(4-1), b:function(){}, c:new Date()}" )) Better code without eval(): function looseJsonParse(obj){ return Function('"use strict";return (' + obj + ')')(); } console.log(looseJsonParse( "{a:(4-1), b:function(){}, c:new Date()}" )) Comparing the two code snippets above, the two code snippets might seem to work the same way, but think again: the eval() one is a great deal slower. Notice c: new Date() in the evaluated object. In the function without the eval(), the object is be...
...And 5 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
lla Add-ons Gallery or not. In order to host your add-on with Mozilla it is crucial to minimize or completely eliminate eval use in order to receive a positive review and have your add-on made public. If it cannot be easily proven that an eval() call is benign and necessary because there are no viable alternatives, a Mozilla Add-ons Gallery reviewer will generally reject the submission! Parsing JSON Mozilla provides native JSON support since Firefox 3. There is simply no need to parse JSON using eval. Additionally, parsing JSON retrieved from a remote location becomes a security vulnerability when parsed with the eval function. Basically, you are executing remote code with full chrome access; that is, introducing a remote code execution vulnerability. Even if you trust the remote server; fo...
...because it is one you rent and administer yourself, there is a huge security risk, because of, but not limited to: You might discontinue your project or sell it, so that it is possible another person with malicious intentions takes over your domain. The server and/or domain name might be compromised. If using an unencrypted, insecure connection, a Man-in-the-middle attacker might replace the JSON with attack code before it arrives at the user. Use Native JSON Since Firefox 3.5 you should use JSON. Really, just use it! Note: Do not use JSON parsers implemented in JavaScript. These implementations are less efficient and often also contain serious security vulnerabilities. Such implementations are meant to be used within a very different security context, namely a website, where the orig...
...se it! ...
...And 4 more matches
TypeError: cyclic object value - JavaScript
The JavaScript exception "cyclic object value" occurs when object references were found in JSON. JSON.stringify() doesn't try to solve them and fails accordingly. Message TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge) Error type TypeError What went wrong? ...
... The JavaScript exception "cyclic object value" occurs when object references were found in JSON. JSON.stringify() doesn't try to solve them and fails accordingly. Message TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge) Error type TypeError What went wrong? ...
... JSON. JSON.stringify() doesn't try to solve them and fails accordingly. Message TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge) Error type TypeError What went wrong? ...
...And 4 more matches
BigInt - JavaScript
valueOf() method. Usage recommendations Coercion Because coercing between Number and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types. Cryptography The operations supported on BigInts are not constant time. BigInt is therefore unsuitable for use in cryptography. ...
...thod. Usage recommendations Coercion Because coercing between Number and BigInt can lead to loss of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types. Cryptography The operations supported on BigInts are not constant time. BigInt is therefore unsuitable for use in cryptography. ...
... of precision, it is recommended to only use BigInt when values greater than 253 are reasonably expected and not to coerce between the two types. Cryptography The operations supported on BigInts are not constant time. BigInt is therefore unsuitable for use in cryptography. Use within JSON Using JSON.stringify() with any BigInt value will raise a TypeError as BigInt values aren't serialized in JSON by default. ...
...And 4 more matches
widget - Archive of obsolete content
ded, corresponding to the DOMContentLoaded event "end": load content scripts once all the content (DOM, JS, CSS, images) for the widget has been loaded, at the time the window.onload event fires This property is optional and defaults to "end". contentScriptOptions object Read-only value exposed to content scripts under self.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. Widget Represents a widget object. Methods destroy() Removes the widget from the add-on bar. postMessage(data) Sends a message to the widget's content scripts. Parameters data : value The message to send. The message can be any JSON-serializable value. on(type, listener) Registers an event listener with the ...
...DOM content itself has been loaded "ready": load content scripts once DOM content has been loaded, corresponding to the DOMContentLoaded event "end": load content scripts once all the content (DOM, JS, CSS, images) for the widget has been loaded, at the time the window.onload event fires contentScriptOptions Read-only value exposed to content scripts under self.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. port Object that allows you to: send events to the content script using the port.emit function receive events from the content script using the port.on function See the guide to communicating using port for details. Events attach This event is emitted when a browser window is opened and a new WidgetView object is crea...
...event. message If you listen to this event you can receive message events from content scripts associated with this widget. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the widget's message event. Arguments value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value. mouseover This event is emitted when the user moves the mouse over the widget. mouseout This event is emitted when the user moves the mouse away from the widget. WidgetView Represents a widget instance specific to one browser window. Anything you do to an instance of this object will only be applied to the instance attached to its browser window: widget instances attach...
...And 3 more matches
Fetching data from the server - Learn web development
whenever you want to update any part of the page, for example, to display a new set of products or load a new page, you've got to load the entire page again. This is extremely wasteful and results in a poor user experience, especially as pages get larger and more complex. Enter Ajax This led to the creation of technologies that allow web pages to request small chunks of data (such as HTML, XML, JSON, or plain text) and display them only when needed, helping to solve the problem described above. This is achieved by using APIs like XMLHttpRequest or -- more recently -- the Fetch API. These technologies allow web pages to directly handle making HTTP requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. Note: In the early day...
...ing HTTP requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. Note: In the early days, this general technique was known as Asynchronous JavaScript and XML (AJAX), because it tended to use XMLHttpRequest to request XML data. This is normally not the case these days (you'd be more likely to use XMLHttpRequest or Fetch to request JSON), but the result is still the same, and the term "Ajax" is still often used to describe the technique. The Ajax model involves using a web API as a proxy to more intelligently request data rather than just having the browser reload the entire page. Let's think about the significance of this: Go to one of your favorite information-rich sites, like Amazon, YouTube, CNN, etc., and load it. N...
...f complex code that deals with filtering the products by category and search terms, manipulating strings so the data displays correctly in the UI, etc. We won't discuss all of it in the article, but you can find extensive comments in the code (see can-script.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 j...
...And 3 more matches
Introducing a complete toolchain - Learn web development
), once they're in place they can be very powerful. If you're interested in using hooks, Husky is a greatly simplified route into using hooks. For VS Code, one useful extension is the Prettier Code Formatter by Esben Petersen, which lets VSCode automatically format code upon saving. This means that any file in the project we are working on gets formatted nicely, including HTML, CSS, JavaScript, JSON, markdown, and more. All the editor needs is "Format On Save" enabled. Like many tools made more recently Prettier comes with "sensible defaults". That means that you'll be able to use Prettier without having to configure anything (if you are happy with the defaults). This lets you get on with what's important: the creative work. Code linting tools Linting helps with code quality but also is a...
...tool for JavaScript linting is eslint. It's an extremely powerful and versatile tool but can be tricky to configure correctly and you could easily consume many hours trying to get a configuration just right! Out of the box, eslint is going to complain that it can't find the configuration file if you run it. The configuration file supports multiple formats but for this project we'll use .eslintrc.json (the leading period means the file is hidden by default). eslint is installed via npm, so as per discussions in Chapter 2, you have the choice to install this tool locally or globally. Using both is recommended: For projects you intend to share, you should always include eslint as a local dependency so that anyone making their own copy can follow the rules you've applied to the project. You ...
...nality working on the directory: git init This means that you'll now be able to start storing revisions to the folder's contents, saving it to a remote repository, etc. More on this later! Next, enter the following command to turn your directory into an npm package, with the advantages that we discussed in the previous article: npm init --force This will create a default package.json file that we can configure later on if desired. The --force flag causes the command to instantly create a default package.json file without asking you all the usual questions about what contents you want it to have (as we saw previously). We only need the defaults for now, so this saves us a bit of time. Getting the project code files At this point, we'll get hold of the project's code files...
...And 3 more matches
How to implement a custom autocomplete search component
result * * @param searchString - The string to search for * @param searchParam - An extra parameter * @param previousResult - A previous result to use for faster searchinig * @param listener - A listener to notify when the search is complete */ startSearch: function(searchString, searchParam, result, listener) { // This autocomplete source assumes the developer attached a JSON string // to the the "autocompletesearchparam" attribute or "searchParam" property // of the <textbox> element. The JSON is converted into an array and used // as the source of match data. Any values that match the search string // are moved into temporary arrays and passed to the AutoCompleteResult if (searchParam.length > 0) { var nativeJSON = Components.classes["@mozi...
...// to the the "autocompletesearchparam" attribute or "searchParam" property // of the <textbox> element. The JSON is converted into an array and used // as the source of match data. ...
...rchparam" attribute or "searchParam" property // of the <textbox> element. The JSON is converted into an array and used // as the source of match data. ...
...And 3 more matches
Using Performance Timeline - Web APIs
getEntriesByName() to get all "mark" entries named "Begin" p = performance.getEntriesByName("Begin", "mark"); for (var i=0; i < p.length; i++) { log ("Begin and Mark [" + i + "]"); print_perf_entry(p[i]); } } PerformanceEntry interface The PerformanceEntry interface encapsulates a single performance entry i.e. a single performance metric. This interface has four properties and a JSON serializer (toJSON(). The following example shows the use of these properties. function print_PerformanceEntry(ev) { var properties = ["name", "entryType", "startTime", "duration"]; // Create a few performance entries performance.mark("Start"); do_work(50000); performance.mark("Stop"); performance.measure("measure-1"); var p = performance.getEntries(); for (var i=0; i < p.lengt...
...ry[" + i + "]"); for (var j=0; j < properties.length; j++) { // check each property in window.performance var supported = properties[j] in p[i]; if (supported) { var pe = p[i]; log("... " + properties[j] + " = " + pe[properties[j]]); } else { log("... ...
... in p[i]; if (supported) { var pe = p[i]; log("... " + properties[j] + " = " + pe[properties[j]]); } else { log("... " + properties[j] + " = Not supported"); } } } } This interface also includes a toJSON() method that returns the serialization of the PerformanceEntry object. The following examples show the use of this method. ...
...And 3 more matches
Request.cache - Web APIs
Web › API › Request › cache
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. ...
...equest'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. ...
...("some.json", {cache: "reload"}) .then(function(response) { /* consume the response */ }); // Download a resource with cache busting when dealing with a // properly configured server that will send the correct ETag // and Date headers and properly handle If-Modified-Since and // If-None-Match request headers, therefore we can rely on the // validation to guarantee a fresh response. fetch("some.json", {cache: "no-cache"}) .then(function(response) { /* consume the response */ }); // Download a resource with economics in mind! Prefer a cached // albeit stale response to conserve as much bandwidth as possible. fetch("some.json", {cache: "force-cache"}) .then(function(response) { /* consume the response */ }); // Naive stale-while-revalidate client-level implementation. // Prefer a cached...
...And 3 more matches
JavaScript modules - JavaScript
See Node's ECMAScript Modules documentation for more details.Disabled From version 12.0.0: th...
...See Node's ECMAScript Modules documentation for more details.Disabled From version 12.0.0: this feature is behind the --experimental-modules runtime flag. ...
...See Node's ECMAScript Modules documentation for more details.Disabled From version 12.0.0: th...
...And 3 more matches
request - Archive of obsolete content
in mind that the same validation rules that apply to options in the constructor will apply during assignment. Thus, each can throw if given an invalid value. ...
... assignment. Thus, each can throw if given an invalid value. ...
... head() Make a HEAD request. post() Make a POST request. put() Make a PUT request. delete() Make a DELETE request. ...
...And 2 more matches
Localization - Archive of obsolete content
town_name>" To choose the first option, the .properties file can order the placeholders as follows: home_town_id= %2s is %1s's home town. This gives us the following output: info: London is Bob's home town. Using localized strings in add-on meta data This feature is new in jpm 1.0.6. ...
...on meta data This feature is new in jpm 1.0.6. Support for homepage was added in jpm 1.0.7 By including a "locales" structure in your add-on's "package.json" file, you can localize the title, description and homepage of your add-on. This structure holds objects referenced by the locale name containing at least one of title, description or homepage as a property. ...
... Preferences have mandatory title and optional description fields. These are strings which appear alongside the preference in the Add-ons Manager, to help explain to the user what the preference means. To provide the localized form of the preference title, include an entry in yo...
...And 2 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
t = document.createEvent("Events"); evt.initEvent("MyExtensionEvent", true, false); element.dispatchEvent(evt); } function ExtensionAnswer(EvtAnswer) { alert(element.getAttribute("attribute3") + " " + EvtAnswer.target.getAttribute("Part1")); } Basic example of similar idea, extension passes information via attributes and fires event on div in page, here. ...
...eEvent("Events"); evt.initEvent("MyExtensionEvent", true, false); element.dispatchEvent(evt); } function ExtensionAnswer(EvtAnswer) { alert(element.getAttribute("attribute3") + " " + EvtAnswer.target.getAttribute("Part1")); } Basic example of similar idea, extension passes information via attributes and fires event on div in page, here. ...
...tribute("Part1")); } Basic example of similar idea, extension passes information via attributes and fires event on div in page, here. ...
...And 2 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
ace for the session-management extension will look like. Under the Tool menu, the Session Store submenu contains two items--Save Session and Clear Sessions; in between them is a list of previously saved sessions that you can restore, most recent first. FIXME: Figure 12: Session-management extension interface: the menu As discussed in the part "The Session Store API", sessions are represented as JSON character strings. Sessions are stored in a subdirectory of the profile directory (called "sessionstore"), with each session stored as a text file in it (Figure 13). FIXME: Figure 13: Schematic of session saving and restorin Source file structure FIXME: Figure 14 shows the directory structure for this project Creating install manifest Create your work folder, and create an install manifest w...
...t for uninit method uninit: function() { this._dir = null; }, save method Listing 19 gives the code for the save method. In line 3, you see the block that prevents the bubbling that would result in this being called by the oncommand handler in the menupop element, which is the parent of the menuitem element. In lines 4-6, we use the nslSessionStore interface's getBrowserState method to get a JSON text-string representation of the states of all currently open browser windows. In lines 7-9, we create the target file's nslFile object by duplicating the _dir property. In line 10, we use the _writefile method (which we'll get to shortly) to write the JSON string representing the session to the file. Listing 19: Content for save method save: function(event) { event.stopPropagation(); var ...
....now() + ".js"; var file = this._dir.clone(); file.append(fileName); this._writeFile(file, state); }, restore method Listing 20 shows the event handler for the dynamically generated menu items, which were created using the createMenu method (which we'll get to shortly). Lines 3-6 get the file name from the special attribute fileName that was added by the createMenu method, and read in the JSON text string from that file using the _readFile method (which we'll get to shortly). Lines 7-9 use the nslSessionStore interface's setWindowState method to restore the session, using the current window as an origin point. Session restoration overwrites any currently open tabs. Listing 20: Content for restore method restore: function(event) { var fileName = event.target.getAttribute("fileName")...
...And 2 more matches
Connecting to Remote Content - Archive of obsolete content
<< PreviousNext >> Using XMLHttpRequest XMLHttpRequest is an API for transferring XML between a local script and a remote server via HTTP. It is an integral part of the modern web, and all major browsers support it. Besides XML, it can be used to retrieve data in other formats, for example JSON, HTML and plain text. In this section we'll look into the XML and JSON communication mechanisms. let url = "http://www.example.com/"; let request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createInstance(Components.interfaces.nsIXMLHttpRequest); request.onload = function(aEvent) { window.alert("Response Text: " + aEvent.target.responseText); }; request.onerror = function(aEvent) { window.alert("Error Status: " + aEvent.target.status); }; request.open("GET...
...nd user interface are blocked while waiting for a response to come back. Note: Requests can take a long time to process and you don't want users to be stuck waiting while a request is obtained and processed. Therefore, it is very important that XMLHttpRequest calls are always done asynchronously. Now let's look at the most common types of content you can use to communicate with remote servers. JSON content JSON is a very lightweight and simple data representation format, similar to the object representation used in JavaScript. Unlike JavaScript, the JSON format doesn't allow any kind of code that can be run, only data. JSON used to be risky in terms of security because the favored way of parsing it was to use the JavaScript eval function. Since eval executes any code contained in the stri...
... Assume we need to parse the following data: {"shops": [{"name": "Apple", "code": "A001"}, {"name": "Orange"}], "total": 100} When the onload callback function is called, the response text is converted into a JS object using the parse method. ...
...And 2 more matches
Code snippets - Archive of obsolete content
Components.utils.i...
...Components.utils.import("resource://services-syn...
...mponents.utils.import("resource://services-sync/util.js"); let r = new Resource(Weave.Service.storageURL + "meta/global"); let g = r.get(); let envelope = JSON.parse(g); let payload = JSON.parse(envelope.payload); payload.engines[ENGINE].syncID = Weave.Utils.makeGUID(); // Or any other GUID you like. payload.engines[ENGINE].version = 0; // Or any other version number you like. envelope.payload = JSON.stringify(payload); r.put(JSON.stringify(envelope)); Generate new keys // Clients always wipe the server when they generate new keys. Components.utils.import("resource://services-sync/main.js"); Weave.Service._freshStart(); // If you want to do it without wiping the server (which will cause corruption!): Weave.Service.generateNewSymmetricKeys(); Print out a list of large bookmark records //...
...And 2 more matches
Third-party APIs - Learn web development
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 has to be filled in before the form can be submitted (achieved using the required attribute), and the da...
..."[0-9]{8}"). See Form data validation for more details on how these work. Requesting data from the API Now we've constructed our URL, let's make a request to it. We'll do this using the Fetch API. Add the following code block inside the fetchResults() function, just above the closing curly brace: // Use fetch() to make the request to the API fetch(url).then(function(result) { return result.json(); }).then(function(json) { displayResults(json); }); Here we run the request by passing our url variable to fetch(), convert the response body to JSON using the json() function, then pass the resulting JSON to the displayResults() function so the data can be displayed in our UI. Displaying the data OK, let's look at how we'll display the data. Add the following function below your fetchResu...
...ults(json); }); Here we run the request by passing our url variable to fetch(), convert the response body to JSON using the json() function, then pass the resulting JSON to the displayResults() function so the data can be displayed in our UI. Displaying the data OK, let's look at how we'll display the data. Add the following function below your fetchResults() function. ...
...And 2 more matches
Communicating with frame scripts
The API is mostly symmetrical, with one major exception: frame scripts can send asynchronous or synchronous messages to chrome, but chrome can only send asynchronous messages to content. This is an intentional design decision made to prevent content code from making chrome code unresponsive. Where absolutely necessary, frame scripts can pass wrappers called Cross Process Object Wrappers (also known as CPOWs) to chrome, and chrome can use these wrappers to get synchronous access to content objects. ...
...; sendAsyncMessage() takes one mandatory parameter, which is the name of the message. All messages share the same namespace, so to avoid conflicts with other code, you'll need to ensure that the names you use are unique. If you're using the message manager in an add-on, a good way to do that is to prefix messages with your add-on's ID. After the name, you can pass detailed data as a string or a JSON-serializable object, and after that you can pass any objects it wants to pass to content as CPOWs. The example below sends a message named "my-e10s-extension-message", with a data payload containing details and tag properties, and exposes the event.target object as a CPOW: // frame script addEventListener("click", function (event) { sendAsyncMessage("my-addon@me.org:my-e10s-extension-message"...
...e); To receive messages from content, a chrome script needs to add a message listener using the message manager's addMessageListener() API. The message passed to the listener is an object containing the following properties: name String containing the message name. sync Boolean declaring whether the message was send synchronously or aynchronously. data The JSON object passed as the second parameter to sendAsyncMessage(). target The XUL <browser> element from which this message was sent. objects An object whose properties are any CPOWs exposed by the sender as the third argument to sendAsyncMessage() In the example below the listener just logs all the messages details: // chrome script messageManager.addMessageListener("my...
...And 2 more matches
Places Developer Guide
ookmarks in the toolbar and menu folders will be deleted. Note: The method importHTMLFromFileToFolder() method was removed in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11). Exporting: exportHTMLToFile (nsILocalFile aFile) - This exports all bookmarks in the toolbar, menu and unfiled bookmarks folders into the specified file. Backup/Restore The new bookmarks system uses the JSON format for storing backups of users' bookmarks. The APIs are available via the PlacesUtils API in the utils.js Javascript module. var Ci = Components.interfaces; var Cc = Components.classes; var Cu = Components.utils; // Import PlacesUtils Cu.import("resource://gre/modules/PlacesUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); // Create the backup file var jsonFile = Services.dirs...
...rs' bookmarks. The APIs are available via the PlacesUtils API in the utils.js Javascript module. ...
... available via the PlacesUtils API in the utils.js Javascript module. ...
...And 2 more matches
Observer Notifications
related to private browsing occur. Topic Data Description private-browsing enter Sent when private browsing mode is activated. private-browsing exit Sent when private browsing mode is deactivated. Bookmarks These topics indicate when actions related to bookmarks occur. Topic Data Description bookmarks-restore-begin json Sent just before bookmarks are restored from JSON. bookmarks-restore-begin html Sent just before bookmarks are restored from HTML. If bookmarks will be restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null otherwise. bookmarks-restore-begin html-initial ...
... of the folder. The subject is null otherwise. bookmarks-restore-begin html-initial Sent just before bookmarks are restored from HTML on initial import. If bookmarks are restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null otherwise. bookmarks-restore-success json Sent just after bookmarks are restored from JSON. bookmarks-restore-success html Sent just after bookmarks are restored from HTML. If bookmarks were restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null otherwise. bookmarks-restore-success html-initial S...
...of the folder. The subject is null otherwise. bookmarks-restore-success html-initial Sent just after bookmarks are restored from HTML on initial import. If bookmarks were restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null otherwise. bookmarks-restore-failed json Sent when bookmarks could not be sucessfully restored from JSON. bookmarks-restore-failed html Sent when bookmarks could not be successfully restored from HTML. If bookmarks were to have been restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null otherwise. boo...
...And 2 more matches
nsITelemetry
data consists of the following properties: min - Minimal bucket size max - Maximum bucket size histogram_type - HISTOGRAM_EXPONENTIAL or HISTOGRAM_LINEAR counts - An array representing the values of buckets in the histogram. ranges - An array with corresponding bucket sizes. sum - Sum of the counts array. static - true for histograms defined in Histograms.json, false for ones defined with newHistogram(). Read only. Constants Histogram Types Constant Value Description HISTOGRAM_EXPONENTIAL 0 Buckets increase exponentially. HISTOGRAM_LINEAR 1 Buckets increase linearly. HISTOGRAM_BOOLEAN 2 For storing 0/1 values. HISTOGRAM_FLAG 3 For storing a single value; its c...
... Dataset Types Constant Value Description DATASET_RELEASE_CHANNEL_OPTOUT 0 The basic dataset that is on-by-default on all channels. DATASET_RELEASE_CHANNEL_OPTIN 1 The extended dataset that is opt-in on release, opt-out on pre-release channels. Methods getHistogramById() Get an histogram by id for histograms registered in Histograms.json. jsval getHistogramById( in ACString id ); Parameters id Unique identifier from toolkit/components/telemetry/Histograms.json. Return value The returned jsval object has the following functions: add(value) - Adds an integer value to the appropriate bucket snapshot() - Returns a snapshot of the histogram with the same data fields as in histogramSnapshots. getKeyedHistogramById() ...
... Return value The returned jsval object has the following functions: add(key, [optional] value) - Adds an integer value to the appropriate bucket. ...
...And 2 more matches
Inspecting web app manifests - Firefox Developer Tools
You also need to make sure the JSON inside the file is of the correct format. You can test this using the Web Manifest Validator. Inspecting your manifest If your manifest is deployed successfully, you should end up with a display like the following on th...
... You also need to make sure the JSON inside the file is of the correct format. ...
... You also need to make sure the JSON inside the file is of the correct format. You can test this using the Web Manifest Validator. ...
...And 2 more matches
Web Authentication API - Web APIs
ote that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it MUST be generated on the server in order to ensure the security of the registration process. Browser Calls authenticatorMakeCredential() on Authenticator - Internally, the browser will validate the parameters and fill in any defaults, which become the AuthenticatorResponse.clientDataJSON. ...
...- Internally, the browser will validate the parameters and fill in any defaults, which become the AuthenticatorResponse.clientDataJSON. One of the most important parameters is the origin, which is recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with). Authenticator Creates New Key Pair and Attestation - Before doing anything, the authenticator will typically ask for some form of user verification. This could be entering a PIN, using a fingerpri...
...tation data are returned to the browser where they become the attestationObject. Browser Creates Final Data, Application sends response to Server - The create() Promise resolves to an PublicKeyCredential, which has a PublicKeyCredential.rawId that is the globally unique credential id along with a response that is the AuthenticatorAttestationResponse containing the AuthenticatorResponse.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). Server Validates and Finalizes Registration - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered...
...And 2 more matches
CSP: report-uri - HTTP
Though the report-to directive is intended to replace the deprecated report-uri directive, report-to isn't supported in most browsers yet. ...
...Policy: report-uri <uri>; Content-Security-Policy: report-uri <uri> <uri>; <uri> A URI where to POST the report to. Examples See Content-Security-Policy-Report-Only for more information and examples. Content-Security-Policy: default-src https:; report-uri /csp-violation-report-endpoint/ /csp-violation-report-endpoint/ could for example run a PHP something like the following that logs the JSON detailing the violation and, if the violation is the first one added to the log file, sends an email to an administrator: <?php // Start configure $log_file = dirname(__FILE__) . '/csp-violations.log'; $log_file_size_limit = 1000000; // bytes - once exceeded no further entries are added $email_address = 'admin@example.com'; $email_subject = 'Content-Security-Policy violation'; // End configurat...
...iolations.log'; $log_file_size_limit = 1000000; // bytes - once exceeded no further entries are added $email_address = 'admin@example.com'; $email_subject = 'Content-Security-Policy violation'; // End configuration $current_domain = preg_replace('/www\./i', '', $_SERVER['SERVER_NAME']); $email_subject = $email_subject . ' on ' . $current_domain; http_response_code(204); // HTTP 204 No Content $json_data = file_get_contents('php://input'); // We pretty print the JSON before adding it to the log file if ($json_data = json_decode($json_data)) { $json_data = json_encode($json_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); if (!file_exists($log_file)) { // Send an email $message = "The following Content-Security-Policy violation occurred on " . $current_domain . ":\n\n" .
...And 2 more matches
X-Content-Type-Options - HTTP
ded instead of being rendered when they are served with a MIME type other than text/html. Make sure to set both headers correctly. Site security testers usually expect this header to be set. Note: X-Content-Type-Options only apply request-blocking due to nosniff for request destinations of "script" and "style". However, it also enables Cross-Origin Read Blocking (CORB) protection for HTML, TXT, JSON and XML files (excluding SVG image/svg+xml). Header type Response header Forbidden header name no Syntax X-Content-Type-Options: nosniff Directives nosniff Blocks a request if the request destination is of type: "style" and the MIME type is not text/css, or "script" and the MIME type is not a JavaScript MIME type Enables Cross-Origin Read Blocki...
... Living Standard Initial definition ...
... Living Standard Initial definition ...
...And 2 more matches
Object.assign() - JavaScript
; const copy = Object.assign({}, obj); console.log(copy); // { a: 1 } Warning for Deep Clone For deep cloning, we need to use alternatives, because Object.assign() copies property values. If the source value is a reference to an object, it only copies the reference value. ...
...or Deep Clone For deep cloning, we need to use alternatives, because Object.assign() copies property values. If the source value is a reference to an object, it only copies the reference value. ...
...use Object.assign() copies property values. If the source value is a reference to an object, it only copies the reference value. ...
...And 2 more matches
Cross-domain Content Scripts - Archive of obsolete content
By default, content scripts don't have any cross-domain privileges. In particular, they can't: access content hosted in an iframe, if that content is served from a different domain make cross-domain XMLHttpRequests However, you can enable these features for specific domains by adding them to your add-on's package.json under the "cross-domain-content" key, which itself lives under the "permissions" key: "permissions": { "cross-domain-content": ["http://example.org/", "http://example.com/"] } The domains listed must include the scheme and fully qualified domain name, and these must exactly match the domains serving the content - so in the example above, the content script will not be allowed to access content served from https://example.com/. Wildcards are not allowed. This fea...
... Cross-domain XMLHttpRequest The following add-on creates a panel whose content is the summary weather forecast for Shetland. If you want to try it out, you'll need to register and get an API key. The "main.js": creates a panel whose content is suppli...
...orecast_panel.show(); } }); The "panel.html" just includes a <div> block for the forecast: <!DOCTYPE html> <!-- panel.html --> <html> <head></head> <body> <div id="forecast_summary"></div> </body> </html> The "panel-script.js" uses XMLHttpRequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=YOUR-API-KEY"; self.port.on("show", function () { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = function () { var jsonResponse = JSON.parse(request.responseText); var summary = getSummary(jsonResponse); var element = document.getElementById("forecast_summary"); element.textContent = summary; }; request.send(); }); function...
... var jsonResponse = JSON.parse(request.responseText); var summary = getSummary(jsonResponse); var element = document.getElementById("forecast_summary"); element.textContent = summary; }; request.send(); }); function getSummary(forecast) { return forecast.RegionalFcst.FcstPeriods.Period[0].Paragraph[0].$; } Finally, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://datapoint.metoffice.gov.uk"] } Content Permissions and unsafeWindow If you use "cross-domain-content", then JavaScript values in content scripts will not be available from pages. Suppose your content script includes a line like: // content-script.js: unsafeWindow.myCustomAPI = function () {}; If you have included the "cross-domain-conte...
port - Archive of obsolete content
attach the content script, such as page-mod or page-worker. For an overview of content scripts, see the main article. port Methods emit() The port.emit() function sends a message from one side to the other. It may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. The payload can be any value that is serializable to JSON. From the content script to the main add-on code: // content-script.js var myMessagePayload = "some data"; self.port.emit("myMessage", myMessagePayload); From the main add-on code to the content script: // main.js var myMessagePayload = "some data"; worker.port.emit("myMessage", myMessagePayload); on() The port.on() function registers a function as a listener for a particular message sent...
... is only logged the first time the button is clicked. Due to bug 816272 the page-mod's removeListener() function does not prevent the listener from receiving messages that are already queued. This means that if "main.js" sends the message twice in successive lines, and the listener stops listening as soon as it receives the first message, then the listener will still receive the second message. JSON-serializable values The payload for a message can be any JSON-serializable value. When messages are sent their payloads are automatically serialized, and when messages are received their payloads are automatically deserialized, so you don't need to worry about serialization. However, you do have to ensure that the payload can be serialized to JSON. This means that it needs to be a string, numbe...
...This means you can't send functions, and if the object contains methods they won't be encoded. You also can't include circular references. ...
...This means you can't send functions, and if the object contains methods they won't be encoded. You also can't include circular references. ...
Communicating using "port" - Archive of obsolete content
an element in the page warning sends a silly string back to the page-mod port.emit() The port.emit() function sends a message from the "main.js", or another add-on module, to a content script, or vice versa. It may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. The payload can be any value that is serializable to JSON. From the content script to the main add-on code: var myMessagePayload = "some data"; self.port.emit("myMessage", myMessagePayload); From the main add-on code (in this case a panel instance) to the content script: var myMessagePayload = "some data"; panel.port.emit("myMessage", myMessagePayload); port.on() The port.on() function registers a function as a listener for a specific named mess...
... message just once, then stop listening. The port object offers a shortcut to do this: the once() method. This example rewrites the "listener.js" content script in the port.removeListener() example so that it uses once(): function getFirstParagraph() { var paras = document.getElementsByTagName('p'); console.log(paras[0].textContent); } self.port.once("get-first-para", getFirstParagraph); JSON-Serializable Values The payload for an message can be any JSON-serializable value. When messages are sent their payloads are automatically serialized, and when messages are received their payloads are automatically deserialized, so you don't need to worry about serialization. However, you do have to ensure that the payload can be serialized to JSON. This means that it needs to be a string, numb...
...This means you can't send functions, and if the object contains methods they won't be encoded. ...
...This means you can't send functions, and if the object contains methods they won't be encoded. ...
page-worker - Archive of obsolete content
oaded, corresponding to the DOMContentLoaded event "end": load content scripts once all the content (DOM, JS, CSS, images) for the page has been loaded, at the time the window.onload event fires This property is optional and defaults to "end". contentScriptOptions object Read-only value exposed to content scripts under self.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. onMessage function Use this to add a listener to the page worker's message event. Page A Page object loads the page specified by its contentURL option and executes any content scripts that have been supplied to it in the contentScript and contentScriptFile options. The page is not displayed to...
... as the Page object is created and stays loaded until its destroy method is called or the add-on is unloaded. Methods destroy() Unloads the page worker. After you destroy a page worker, its memory is freed and you must create a new instance if you need to load another page. postMessage(message) Sends a message to the content scripts. Parameters message : value The message to send. Must be JSON-able. on(type, listener) Registers an event listener with the page worker. See Working with Events for help with events. Parameters type : string The type of event to listen for. listener : function The listener function that handles the event. removeListener(type, listener) Unregisters an event listener from the page worker. Parameters type : string The type of event for which listen...
...e DOM content itself has been loaded "ready": load content scripts once DOM content has been loaded, corresponding to the DOMContentLoaded event "end": load content scripts once all the content (DOM, JS, CSS, images) for the page has been loaded, at the time the window.onload event fires contentScriptOptions Read-only value exposed to content scripts under self.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. Events message If you listen to this event you can receive message events from content scripts associated with this page worker. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the page worker's message event. Arguments value : Listeners are passed a single argum...
...ssage If you listen to this event you can receive message events from content scripts associated with this page worker. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the page worker's message event. Arguments value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value error This event is emitted when an uncaught runtime error occurs in one of the page worker's content scripts. Arguments Error : Listeners are passed a single argument, the Error object. ...
panel - Archive of obsolete content
ded, corresponding to the DOMContentLoaded event "end": load content scripts once all the content (DOM, JS, CSS, images) for the panel has been loaded, at the time the window.onload event fires This property is optional and defaults to "end". contentScriptOptions object Read-only value exposed to content scripts under addon.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. contextMenu boolean New in Firefox 33 Whether to show a context menu when the user context-clicks in the panel. The context menu will be the same one that's displayed in web pages. Optional, defaults to false. onMessage function Include this to listen to the panel's m...
...nu and send the user's selection to the add-on. Methods destroy() Destroys the panel, unloading any content that was loaded in it. Once destroyed, the panel can no longer be used. If you just want to hide the panel and might show it later, use hide instead. postMessage(message) Sends a message to the content scripts. Parameters message : value The message to send. Must be stringifiable to JSON. show(options) Displays the panel. If the options argument is given, it will be shallow merged with the options provided in the constructor: the options passed in the show method takes precedence. Passing options here is useful for making temporary changes without touching the default values. Parameters options : object Optional options: Name Type width nu...
...DOM content itself has been loaded "ready": load content scripts once DOM content has been loaded, corresponding to the DOMContentLoaded event "end": load content scripts once all the content (DOM, JS, CSS, images) for the panel has been loaded, at the time the window.onload event fires contentScriptOptions Read-only value exposed to content scripts under addon.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. Events show This event is emitted when the panel is shown. hide This event is emitted when the panel is hidden. message If you listen to this event you can receive message events from content scripts associated with this panel. When a content script posts a message using self.postMessage(), the message is delivered to the ...
... hidden. message If you listen to this event you can receive message events from content scripts associated with this panel. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the panel's message event. Arguments value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value. error This event is emitted when an uncaught runtime error occurs in one of the panel's content scripts. Arguments Error : Listeners are passed a single argument, the Error object. ...
dev/panel - Archive of obsolete content
le, occupy "panels" in the toolbox. With the dev/panel module, you can create your own panels in the Toolbox: The panel gets a tab in the Toolbox toolbar which enables the user to open it: You specify the panel's content and behavior using HTML, CSS, and JavaScript. When the panel's created, the framework passes it a debuggee: this is a MessagePort object that you can use to exchange JSON messages with the browser that the developer tools are currently debugging. The messages follow the remote debugging protocol. For a simple walkthrough of using the dev/panel API to add a new tool, see Adding a panel to the toolbox. Basic usage Defining the panel constructor To add a new tool you first need to define a constructor that inherits from the Panel class, and in that constructor yo...
...So we've also provided a library called volcan.js...
...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. ...
...leSheets. Any additional parameters sent in the message become arguments to the method. If a message is expected to get a reply, then the method returns a promise which is fulfilled with the reply. If the message reply in the remote debugging protocol would contain an actor ID, then in volcan.js the object that fulfills the promise contains that actor instance. If the message reply contains some JSON object, then in volcan.js the object that fulfills the promise includes a corresponding JSON object. If an actor can send notifications, as in the request/reply/notify pattern, then the corresponding volcan.js object emits an event, which you can listen for using addEventListener. Any data sent with the notification is available to the event listener in the event.data property. ...
ui/frame - Archive of obsolete content
rigin); } }); var toolbar = Toolbar({ name: "ping-pong", title: "Ping pong", items: [frame] }); This does not have to be the message event: the other events Frame can emit: attach, load and ready, also provide access to source and origin. ...
..., title: "Ping pong", items: [frame] }); This does not have to be the message event: the other events Frame can emit: attach, load and ready, also provide access to source and origin. To receive such messages in the frame script, listen for the window's message event: window.addEventListener("message", handlePong, false); Sending JSON In all cases, you can send a string as a message or a JSON object. ...
...tems: [frame] }); This does not have to be the message event: the other events Frame can emit: attach, load and ready, also provide access to source and origin. To receive such messages in the frame script, listen for the window's message event: window.addEventListener("message", handlePong, false); Sending JSON In all cases, you can send a string as a message or a JSON object. ...
...", e.origin); } } Arguments event : This contains three 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. data, which represents the event's payload. ...
Supporting search suggestions in search plugins - Archive of obsolete content
er the search bar, which lets the user select a suggested search term. If the user continues to type, a new set of suggestions is requested from the search engine, and the displayed list is refreshed. ...
...earch plugin To support search suggestions, a search plugin needs to define an extra <Url> element with its type attribute set to "application/x-suggestions+json". (This means that a suggestion-supporting engine plugin will have two <Url> elements, the other one being the main text/html search URL.) For example, the Yahoo search plugin has this <Url> entry: <Url type="application/x-suggestions+json" template="http://ff.search.yahoo.com/gossip?output=fxjson&command={searchTerms}"/> If the user types "fir" into the search bar, then pauses, Firefox inserts "fir" in place of {searchTerms} and queries that URL: <Url type="application/x-suggestions+json" template="http://ff.search.yahoo.com/gossip?output=fxjson&command=fir"/> The results are used to construct the suggestion list box. See Cr...
...enSearch plugins for Firefox to learn more about how to implement a search plugin. Implementing search suggestion support on the server The majority of the work in handling search suggestions is actually implemented on the server side. If you're a web site designer, and want to support search suggestions, you need to implement support for returning the suggestions in JavaScript Object Notation (JSON) given a search term. When the browser wants to fetch possible matches for a search term, it then sends an HTTP GET request to the URL specified by the <Url> element. Your server should then decide upon the suggestions to offer using whatever means it sees fit, and return a JSON array of results: query string The first element in the array is the original query string. This allows Firefox t...
... plugin's XML description. Query URLs are not supported in Firefox, and are ignored. This enhancement request - the handling of a selected suggestion, namely calling of a full specified URL as proposed in the opensearch standard - is tracked in bug 386591. For example, if the search term is "fir", and you don't need to return descriptions or alternate query URLs, you might return the following JSON: ["fir", ["firefox", "first choice", "mozilla firefox"]] Note that in this example, only the query 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 metho...
jspage - Archive of obsolete content
t.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).toString(16)+(a.charCodeAt()%16).toString(16); },encode:function(b){switch($type(b)){case"string":return'"'+b.replace(/[\x00-\x1f\\"]/g,JSO...
...N.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).toString(16)+(a.charCodeAt()%16).toString(16); },encode:function(b){switch($type(b)){case"string":return'"'+b.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';case"array":return"["+String(b.map(JSON.encode).clean())+"]"; case"object":case"hash":var a=[];Hash.each(b,function(e,d){var c=JSON.encode(e);if(c){a.push(JSON.encode(d)+":"+c);}});return"{"+a+"}";case"number":case"boolean":return String(b); case false:return"null";}return null;},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.repla...
...});return"{"+a+"}";case"number":case"boolean":return String(b); case false:return"null";}return null;},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null; }return eval("("+string+")");}});Native.implement([Hash,Array,String,Number],{toJSON:function(){return JSON.encode(this);}});var Cookie=new Class({Implements:Options,options:{path:false,domain:false,duration:false,secure:false,document:document},initialize:function(b,a){this.key=b; this.setOptions(a);},write:function(b){b=encodeURIComponent(b);if(this.options.domain){b+="; domain="+this.options.domain;}if(this.options.path){b+="; path="+this.options.path; }if(this.options.duratio...
...ta:this,link:"cancel",update:this,method:"get"},a)); },get:function(a){if(a||!this.retrieve("load")){if(a||!this.retrieve("load:options")){this.set("load",a);}this.store("load",new Request.HTML(this.retrieve("load:options"))); }return this.retrieve("load");}};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Object.type,url:String.type}));return this; }});Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(a){this.parent(a);this.headers.extend({Accept:"application/json","X-Request":"JSON"}); },success:function(a){this.response.json=JSON.decode(a,this.options.secure);this.onSuccess(this.response.json,a);}}); ...
Server-side web frameworks - Learn web development
ules. Overview Server-side web frameworks (a.k.a. "web application frameworks") are software frameworks that make it easier to write, maintain and scale web applications. They provide tools and libraries that simplify common web development tasks, including routing URLs to appropriate handlers, interacting with databases, supporting sessions and user authorization, formatting output (e.g. HTML, JSON, XML), and improving security against web attacks. The next section provides a bit more detail about how web frameworks can ease web application development. We then explain some of the criteria you can use for choosing a web framework, and then list some of your options. What can a web framework do for you? Web frameworks provide tools and libraries to simplify common web development operatio...
...Rendering data Web frameworks often provide templating systems. These allow you to specify the structure of an output document, using placeholders for data that will be added when a page is generated. Templates are often used to create HTML, but can also create other types of document. Web frameworks often provide a mechanism to make it easy to generate other formats from stored data, including JSON and XML. For example, the Django template system allows you to specify variables using a "double-handlebars" syntax (e.g. {{ variable_name }}), which will be replaced by values passed in from the view function when a page is rendered. The template system also provides support for expressions (with syntax: {% expression %}), which allow templates to perform simple operations like iterating list ...
...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. Rails follows a very similar design philosophy to Django. Like Django it provides standard mechanisms for routing URLs, accessing data from a database, generating HTML from templates and formatting data as JSON or XML. It similarly encourages the use of design patterns like DRY ("dont repeat yourself" -- write code only once if at all possible), MVC (model-view-controller) and a number of others. There are of course many differences due to specific design decisions and the nature of the languages. Rails has been used for high profile sites, including: Basecamp, GitHub, Shopify, Airbnb, Twitch, SoundCl...
...mplates, content negotiation, session management, form validation, testing framework, static file server, CGI/PSGI detection, and first-class Unicode support. A full-stack HTTP and WebSocket client/server implementation with IPv6, TLS, SNI, IDNA, HTTP/SOCKS5 proxy, UNIX domain socket, Comet (long polling), keep-alive, connection pooling, timeout, cookie, multipart, and gzip compression support. JSON and HTML/XML parsers and generators with CSS selector support. Very clean, portable and object-oriented pure-Perl API with no hidden magic. Fresh code based upon years of experience, free and open-source. Spring Boot (Java) Spring Boot is one of a number of projects provided by Spring. It is a good starting point for doing server-side web development using Java. Although definitely not the ...
Getting started with React - Learn web development
art. 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 this: moz-todo-react +-- README.md +-- node_modules +-- package.json +-- package-lock.json +-- .gitignore +-- public | +-- favicon.ico | +-- index.html | +-- manifest.json +-- src +-- App.css +-- App.js +-- App.test.js +-- index.css +-- index.js +-- logo.svg +-- serviceWorker.js The src directory is where we'll spend most of our time, as it's where the source code for our application lives. The public directory contains files th...
...inside the <title> element in this file to reflect the title of your application. Accurate page titles are important for accessibility! The public directory will also be published when you build and deploy a production version 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. ...
... 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 single, obvious purpose. ...
...ports a logo from './logo.svg'. Note the use of ./ at the beginning of the path, and the .svg extension at the end -- these tell us that the file is local and that it is not a JavaScript file. Indeed, the logo.svg file lives in our source directory. We don't write a path or extension when importing the React module -- this is not a local file; instead, it is listed as a dependency in our package.json file. Be careful of this distinction as you work through this lesson! The third statement imports the CSS related to our App component. Note that there is no variable name and no from directive. This particular import syntax is not native to JavaScript module syntax -- it comes from Webpack, the tool create-react-app uses to bundle all our JavaScript files together and serve them to the browser.
Deploying our app - Learn web development
ild to happen automatically and the result of the dist directory to be deployed live on our website. This is where our code, GitHub, and Netlify need to be set up to talk to one another, so that each time we update our GitHub code repository, Netlify will automatically pick up the changes, run the build tasks, and finally release a new update. ...
... 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 property already has a command inside it, put a comma at the end of it. Keep the JSON valid. ...
...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 property already has a command inside it, put a comma at the end of it. Keep the JSON valid. You should now be able to run the following command in the root of your project directory to run the production build step (first quit the running process with Ctrl + C if you need to): npm run build This should give you an output like the following, showing you the production files that were created, how big they are, and how long they took to build: dist/src.99d8a31a.js...
...nclude a specific method for testing as part of their pipeline. Products like GitHub, GitLab, etc., all support running tests against individual commits. As this project is deploying to Netlify, and Netlify only asks about the build command, we will have to make the tests part of the build. If the test fails, the build fails, and Netlify won't deploy. Let's get started. Go to your package.json file and open it up. Find your scripts member, and update it so that it contains the following test and build commands: "scripts": { ... "test": "node tests/*.js", "build": "npm run test && parcel build src/index.html" } Now of course we need to add the test to our codebase; create a new directory in your root directory called tests: mkdir tests Inside the new direct...
Theme concepts
ted in a browser extension. If you have a lightweight theme it will be converted to this new theme format automatically before lightweight themes are deprecated. You do not need to port your theme. However, please feel free to update your themes to use any of the new features described here. Static themes Static themes are specified using the same resources as a browser extension: a manifest.json file to define the theme components with those components stored in the same folder as the manifest.json file or a sub folder. These resources are then packed in a zip for publication on addons.mozilla.org (AMO) or for self-distribution. For more information on self-distribution, visit Signing and distributing your add-on. You can also use the theme generator on AMO to create a static theme. Add...
...eme to complement an extension. You can, however, programmatically include a theme in an extension using the Theme API. See Dynamic themes. Defining a theme To create a theme (in this example a simple, single image theme): Create a folder in a suitable location on your computer. Add the theme image file to the folder: <mytheme> <your_header_image>.<type> Create a file called manifest.json in the folder and edit its content as follows: { "manifest_version": 2, "version": "1.0", "name": "<your_theme_name>", "theme": { "images": { "theme_frame": "<your_header_image>.<type>" }, "colors": { "frame": "#FFFFFF", "tab_background_text": "#000" } } } Where: "frame": is the heading area background color for your theme. "tab_backgroun...
...nsion. There are a couple of use cases for this option: To bundle a theme with a browser extension, as an added extra. Create a dynamic theme that changes under programmatic control. And, obviously, you can combine the two and bundle a programmatically controlled theme with your extension. Using the theme API is straightforward. First, request "theme" permission in the extension's manifest.json file. Next, you build a JSON object containing the same information you would use in a static theme's manifest.json, Finally, pass the JSON object in a theme.update() call. For example, the following code, from the dynamic theme example defines the content for the day and night elements of the dynamic theme: const themes = { 'day': { images: { theme_frame: 'sun.jpg', }, color...
...et open to developers. There is good compatibility between Firefox static themes and Chrome themes, providing the ability to port a single header image theme from Firefox to Chrome. However, noting that "frame": and "tab_background_text": only support RGB color array definition on Chrome. So, in the single image theme example (weta_fade) could be supported in Chrome using the following manifest.json file: { "manifest_version": 2, "version": "1.0", "name": "<your_theme_name>", "theme": { "images": { "theme_frame": "weta.png" }, "colors": { "frame": [ 173 , 176 , 159 ], "tab_background_text": [ 0 , 0 , 0 ] } } } Also, note that Chrome tiles the "theme_frame": image from the left of the header area. For more information, see the notes on Chrome c...
Statistics API
that file. When logging to a file is used in combination with multi-process firefox (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. ...
...mbination with multi-process firefox (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. ...
... 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. ...
...erence 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(observer, "garbage-collection-statistics", false); The toplevel JSON object contains these fields: timestamp: integer (microseconds) - Time at which the GC ended, measured from epoch. total_time: number (milliseconds) - The amount of wall time that this GC...
SpiderMonkey 1.8.5
s for creating other objects. Global objects must also have the JSCLASS_GLOBAL_FLAGS flag set. Merely setting JSCLASS_IS_GLOBAL is insufficient. ...
...he JSCLASS_GLOBAL_FLAGS flag set. Merely setting JSCLASS_IS_GLOBAL is insufficient. ...
...jectRoot JS_AddNamedStringRoot JS_AddNamedValueRoot JS_AddObjectRoot JS_AddStringRoot JS_AddValueRoot JS_AlreadyHasOwnPropertyById JS_AnchorPtr JS_BeginJSONParse (removed in future releases, replaced with JS_ParseJSON) JS_CompileFileHandleForPrincipalsVersion JS_CompileScriptForPrincipalsVersion JS_CompileUCFunctionForPrincipalsVersion JS_CompileUCScriptForPrincipalsVersion JS_ConsumeJSONText (removed in future releases, replaced with JS_ParseJSON) JS_DecompileScriptObject JS_DeepFreezeObject JS_DefineFunctionById JS_DefineOwnProperty JS_DefinePropertyById JS_DeletePropertyById JS_DeletePropertyById2 JS_DoubleIsInt32 JS_EncodeStringToBuffer JS_EnterCrossCompartmentCall JS_EvaluateScriptForPrincipalsVersion JS_EvaluateUCScriptForPrincipalsVersion JS_ExecuteRegExp JS_E...
...ct JS_DefineFunctionById JS_DefineOwnProperty JS_DefinePropertyById JS_DeletePropertyById JS_DeletePropertyById2 JS_DoubleIsInt32 JS_EncodeStringToBuffer JS_EnterCrossCompartmentCall JS_EvaluateScriptForPrincipalsVersion JS_EvaluateUCScriptForPrincipalsVersion JS_ExecuteRegExp JS_ExecuteRegExpNoStatics JS_ExecuteScriptVersion JS_FORGET_STRING_FLATNESS JS_FileEscapedString JS_FinishJSONParse (removed in future releases, replaced with JS_ParseJSON) JS_FlatStringEqualsAscii JS_FlattenString JS_FlushCaches JS_FreezeObject JS_GetCompartmentPrivate JS_GetEmptyString JS_GetFlatStringChars JS_GetGCParameter JS_GetGCParameterForThread JS_GetGlobalForScopeChain JS_GetInternedStringChars JS_GetInternedStringCharsAndLength JS_GetOwnPropertyDescriptor JS_GetPropertyAttrsGetter...
SpiderMonkey 1.8.7
s for creating other objects. Global objects must also have the JSCLASS_GLOBAL_FLAGS flag set. Merely setting JSCLASS_IS_GLOBAL is insufficient. ...
...he JSCLASS_GLOBAL_FLAGS flag set. Merely setting JSCLASS_IS_GLOBAL is insufficient. ...
...jectRoot JS_AddNamedStringRoot JS_AddNamedValueRoot JS_AddObjectRoot JS_AddStringRoot JS_AddValueRoot JS_AlreadyHasOwnPropertyById JS_AnchorPtr JS_BeginJSONParse (removed in future releases, replaced with JS_ParseJSON) JS_CompileFileHandleForPrincipalsVersion JS_CompileScriptForPrincipalsVersion JS_CompileUCFunctionForPrincipalsVersion JS_CompileUCScriptForPrincipalsVersion JS_ConsumeJSONText (removed in future releases, replaced with JS_ParseJSON) JS_DecompileScriptObject JS_DeepFreezeObject JS_DefineFunctionById JS_DefineOwnProperty JS_DefinePropertyById JS_DeletePropertyById JS_DeletePropertyById2 JS_DoubleIsInt32 JS_EncodeStringToBuffer JS_EnterCrossCompartmentCall JS_EvaluateScriptForPrincipalsVersion JS_EvaluateUCScriptForPrincipalsVersion JS_ExecuteRegExp JS_E...
...ct JS_DefineFunctionById JS_DefineOwnProperty JS_DefinePropertyById JS_DeletePropertyById JS_DeletePropertyById2 JS_DoubleIsInt32 JS_EncodeStringToBuffer JS_EnterCrossCompartmentCall JS_EvaluateScriptForPrincipalsVersion JS_EvaluateUCScriptForPrincipalsVersion JS_ExecuteRegExp JS_ExecuteRegExpNoStatics JS_ExecuteScriptVersion JS_FORGET_STRING_FLATNESS JS_FileEscapedString JS_FinishJSONParse (removed in future releases, replaced with JS_ParseJSON) JS_FlatStringEqualsAscii JS_FlattenString JS_FlushCaches JS_FreezeObject JS_GetCompartmentPrivate JS_GetEmptyString JS_GetFlatStringChars JS_GetGCParameter JS_GetGCParameterForThread JS_GetGlobalForScopeChain JS_GetInternedStringChars JS_GetInternedStringCharsAndLength JS_GetOwnPropertyDescriptor JS_GetPropertyAttrsGetter...
TPS Tests
In particular, it will...
...In particular, it will set preferences from the "preferences" property, and so you can set the "identity.fxaccounts.autoconfig.uri" preference to point to any FxA server you want. For example, a (partial) tps config for testing against stage might look like: { // ... ...
...in this example, the foobar@restmail.net account must be registered on stage, otherwise authentication will fail (and the whole test will fail as well. You can sign up for an FxA account on stage or dev by creating an FxA account after adding the identity.fxaccounts.autoconfig.uri preference (with the appropriate value) to about:config. Additionally, note that the config file must parse as valid JSON, and so you can't have comments in it (sorry, I know this is annoying). One alternative is to put underscores before the "disabled" preferences, e.g. "_identity.fxaccounts.autoconfig.uri": "...". Writing TPS tests Each TPS test is run as a series of "phases". A phase runs in some firefox profile, and contains some set of actions to perform or check on that profile. Phases have an N to M relatio...
...get to the next one, so try to stick to the convention established in the other tests. Yes, this is cludgey, but it's effective enough and nobody has changed it. Phase Declarations These map the phases to profiles. Both python and JavaScript read them in. They must look like: var phases = { "phase1": "profile1", "phase2": "profile2", "phase3": "profile1" }; Between { and } it must be strict JSON. e.g. quoted keys, no trailing parentheses, etc. The python testrunner will be parsing it with an unforgiving call to json.loads, so anything other than strict JSON will fail. You can use as many profiles or phases as you need, but every phase you define later must be declared here, or it will not be run by the python test runner. Any phases declared here but not implemented later will cause th...
Redis Tips
ries of commands sent all at once across the wire. They are executed sequentially as a single atomic operation. Here's a stupid node script to show how this works: #!/usr/bin/env node var r = require('redis').createClient(); r.multi() .set("foo", 42) .set("bar", "ice cream") .set("baz", 6.28) .get("foo") .get("bar") .get("baz") .exec(function(err, resultList) { console.log(JSON.stringify(resultList, null, 2)); r.end(); // terminate the redis connection; node can quit }); When run, this prints: [ "OK", "OK", "OK", "42", "ice cream", "6.28" ] The result list includes one value per each command executed. Awesome. Note that if one of your commands crashes, the others still all execute! (Try this by breaking one of the set statements by leaving out...
...ed Event Logs It's a common pattern to use numerical timestamps for ranking members in a ZSET. I'll show this in the node console, to illustrate how the optional parameters are done. > var r = require('redis').createClient(); // and I'll define these utility functions just for this example > function now() { return (new Date()).getTime() / 1000 } > function print(err, results) { console.log(JSON.stringify(results, null, 2)) } Whenever someone logs into my site, I record them in my 'last-login' zset. I'll simulate some logins like so: > r.zadd('last-login', now(), 'lloyd'); > r.zadd('last-login', now(), 'jparsons'); > r.zadd('last-login', now(), 'zarter'); > r.zadd('last-login', now(), 'lloyd'); // he logged in again! w00t! Here's what the zset contains now: > r.zrange('last-login...
... encounter articles on the web trying to scare you away from using lots of small zsets due to their memory consumption. If they were written before Redis 2.4 was released, they are out-of-date and useless. I recommend instead reading about redis's memory optimizations for small zsets: http://oldblog.antirez.com/post/everything-about-redis-24.html. My Least Favorite Flavor Storing huge globs of JSON. How can I hate this? I love both redis and JSON; how can I not want to bring them together? It's so tempting to do so! And it's so easy! It's just a stringify() and a SET away. In some cases, stashing JSON or passing it over queues and pubsub channels could be the right thing to do. I think logging data is a good candidate for this. But before you start cramming huge messes of stringi...
...How can I hate this? I love both redis and JSON; how can I not want to bring them together? It's so tempting to do so! And it's so easy! It's just a stringify() and a SET away. In some cases, stashing JSON or passing it over queues and pubsub channels could be the right thing to do. I think logging data is a good candidate for this. But before you start cramming huge messes of stringified JSON in your db, check in with your gut and ask yourself: Does the structure of the JSON matter for my queries? How much space could this consume over time? Do I want a structured document db and/or sql on the side? If the structure matters, consider using redis hashes or flattening your data across your keyspace. Or consider storing the JSON data in MongoDB and manipulating pointers and commo...
nsIScriptableIO
024 bytes long. aPermissions The permissions to use on a newly created file, if applicable. Typically you will use an actual octal permissions value for this parameter. By default, the value 0664 is used. Return value Returns an nsIOutputStream object to use for writing the stream. Exceptions thrown NS_ERROR_INVALID_ARG aBase was null. ...
...plicable. Typically you will use an actual octal permissions value for this parameter. By default, the value 0664 is used. Return value Returns an nsIOutputStream object to use for writing the stream. Exceptions thrown NS_ERROR_INVALID_ARG aBase was null. ...
...ject to use for writing the stream. Exceptions thrown NS_ERROR_INVALID_ARG aBase was null. ...
...riting to a file var json = "{ name: 'bob', age: 37}"; var file = IO.getFile("Profile", null); file.append("myobject.json"); if (!file.exists()) file.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0600); var stream = IO.newOutputStream(file, "text write create truncate"); stream.writeString(json); stream.close(); Example: Reading from a file var file = IO.getFile("Profile", null); file.append("localstore.json"); if (file.exists()) { var stream = IO.newInputStream(file, "text"); var json = stream.readLine(); stream.close(); } See also nsIFile, nsIInputStream, nsIOutputStream ...
Network request details - Firefox Developer Tools
formatting, or as plain, unformatted text. Note that the keys in the response header are all in lowercase, while the request headers keys are not. HTTP/2 requires that all headers be lowercase; response headers are shown as they are received from the server. ...
... requires that all headers be lowercase; response headers are shown as they are received from the server. (There may be some exceptions, such as X-Firefox-Spdy, which is added by Firefox.) You can copy some or all of the response header in JSON format by using the context menu: If you select Copy, a single key word, value pair is copied. ...
...eceived from the server. (There may be some exceptions, such as X-Firefox-Spdy, which is added by Firefox.) You can copy some or all of the response header in JSON format by using the context menu: If you select Copy, a single key word, value pair is copied. ...
...ie 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 If the response is cached (i.e. a 304), the Cache tab displays details about that cached resource. These detail...
PaymentAddress - Web APIs
solete properties The following properties are obsolete and should no longer be used, but may still be present in some browser versions. PaymentAddress.languageCode Read only A DOMString indicating the language code of the address. This identifies the language in which the address is given, and is intended to aid in localization of the display of the address. Methods PaymentAddress.toJSON() A standard serializer that returns a JSON representation of the PaymentAddress object's properties. Examples In the following example, the PaymentRequest() constructor is used to create a new payment request, which takes three objects as parameters -- one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bou...
... amount: { currency: "USD", value: "0.00" }, selected: true, }, ], }; const options = { requestShipping: true }; async function doPaymentRequest() { const request = 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. ...
...cy: "USD", value: "0.00" }, selected: true, }, ], }; const options = { requestShipping: true }; async function doPaymentRequest() { const request = 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. ...
...ons = { requestShipping: true }; async function doPaymentRequest() { const request = 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. ...
PaymentRequest.shippingOption - Web APIs
we can't ship to your address.` }; } } Specifications Specification Status Comment Payment Request APIThe definition of ...
...we can't ship to your address.` }; } } Specifications Specification Status Comment Payment Request APIThe definition of 'shippingOption' in that specific...
... Candidate Recommendation ...
... Candidate Recommendation Initial definition. Browser Compatibility The compatibilit...
RTCSessionDescription - Web APIs
lback This special type with an empty session description is used to roll back to the previous stable state. Methods The RTCSessionDescription doesn't inherit any methods. RTCSessionDescription() This constructor returns a new RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. ...
...ial type with an empty session description is used to roll back to the previous stable state. Methods The RTCSessionDescription doesn't inherit any methods. RTCSessionDescription() This constructor returns a new RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. ...
... The RTCSessionDescription doesn't inherit any methods. RTCSessionDescription() This constructor returns a new RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. RTCSessionDescription.toJSON() Returns a JSON description of the object. The values of both properties, type and sdp, are contained in the generated JSON. ...
...RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. RTCSessionDescription.toJSON() Returns a JSON description of the object. The values of both properties, type and sdp, are contained in the generated JSON. ...
SubtleCrypto.exportKey() - Web APIs
in an encrypted format: to encrypt keys when exporting them use the SubtleCrypto.wrapKey() API instead. Syntax const result = crypto.subtle.exportKey(format, key); Parameters format is a string value describing the data format in which the key should be exported. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. jwk: JSON Web Key format. key is the CryptoKey to export. Return value result is a Promise. If format was jwk, then the promise fulfills with a JSON object containing the key. Otherwise the promise fulfills with an ArrayBuffer containing the key. Exceptions The promise is rejected when one of the following exceptions is encountered: InvalidAccessError Raised when trying to...
...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.t...
...ng-term security modulusLength: 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. ...
...rt 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 event listener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "ECDSA", namedCurve: "P-384" }, true, ["sign", "verify"] ).then((keyPair) => { const exportButton = document.querySelector(".jwk"); exportButton.addEventListener("click", () => { exportCryptoKey(keyPair.p...
Getting Started - Developer guides
This article guides you through the AJAX basics and gives you some simple hands-on examples to get you started. What's AJAX? AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX's most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. The two major features of AJAX allow you to do the following: Make requests to the server without reloading the page Receive and work with data from the server Step 1 - How to make an HTTP request In order to make an HTTP request to the server wit...
...n interact with the page while the server response has yet to arrive. This is the first A in AJAX. The parameter to the send() method can be any data you want to send to the server if POST-ing the request. Form data should be sent in a format that the server can parse, like a query string: "name=value&anothername="+encodeURIComponent(myVar)+"&so=on" or other formats, like multipart/form-data, JSON, XML, and so on. Note that if you want to POST data, you may have to set the MIME type of the request. For example, use the following before calling send() for form data sent as a query string: httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); Step 2 - Handling the server response When you sent the request, you provided the name of a JavaScript function to ha...
...$name . "!"; $array = ['userName' => $name, 'computedString' => $computedString]; echo json_encode($ar...
...response = JSON.parse(httpRequest.responseText); alert(response.computedString); } else { alert('There was a problem with the request.'); } } } The test.php file should contain the following: $name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name'; $computedString = "Hi, " . $name . "!"; $array = ['userName' => $name, 'computedString' => $computedString]; echo json_encode($array); For more on DOM methods, be sure to check out Document Object Model (DOM). Simple timed XHR example Another simple example follows -- here we are loading a text file via XHR, the structure of which is assumed to be like this: TIME: 312.05 TIME: 312.07 TIME: 312.10 TIME: 312.12 TIME: 312.14 TIME: 312.15 Once the text file is loaded, we split() the items into an array at each n...
Trailing commas - JavaScript
y, you can simply add a new line without modifying the previously last line if that line already uses a trailing comma. This makes version-control diffs cleaner and editing code might be less troublesome. JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ECMAScript 5) and most recently (ECMAScript 2017) to function parameters. JSON, however, disallows trailing commas. Syntax , Examples Trailing commas in literals Arrays JavaScript ignores trailing commas in arrays: var arr = [ 1, 2, 3, ]; arr; // [1, 2, 3] arr.length; // 3 If more than one trailing comma is used, an elision (or hole) is produced. An array with holes is called sparse (a dense array has no holes). When iterating arrays for example with Array.pr...
...o allowed on the left-hand side when using destructuring assignment: // array destructuring with trailing comma [a, b,] = [1, 2]; // object destructuring with trailing comma var o = { p: 42, q: true, }; var {p, q,} = o; Again, when using a rest element, a SyntaxError will be thrown: var [a, ...b,] = [1, 2, 3]; // SyntaxError: rest element may not have a trailing comma Trailing commas in JSON Trailing commas in objects were only introduced in ECMAScript 5. As JSON is based on JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON. Both lines will throw a SyntaxError: JSON.parse('[1, 2, 3, 4, ]'); JSON.parse('{"foo" : 1, }'); // SyntaxError JSON.parse: unexpected character // at line 1 column 14 of the JSON data Omit the trailing commas to parse the JSON correct...
...iling commas in objects were only introduced in ECMAScript 5. As JSON is based on JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON. ...
...only introduced in ECMAScript 5. As JSON is based on JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON. ...
Web app manifests
ts are part of a collection of web technologies called progressive web apps (PWAs), which are websites that can be installed to a device's homescreen without an app store. Unlike regular web apps with simple homescreen links or bookmarks, PWAs can be downloaded in advance and can work offline, as well as use regular Web APIs. The web app manifest provides information about a web application in a JSON text file, necessary for the web app to be downloaded and be presented to the user similarly to a native app (e.g., be installed on the homescreen of a device, providing users with quicker access and a richer experience). PWA manifests include its name, author, icon(s), version, description, and list of all the necessary resources (among other things). Can PWA manifest contain comments? It is a...
...text file, necessary for the web app to be downloaded and be presented to the user similarly to a native app (e.g., be installed on the homescreen of a device, providing users with quicker access and a richer experience). PWA manifests include its name, author, icon(s), version, description, and list of all the necessary resources (among other things). Can PWA manifest contain comments? It is a JSON-formatted file, with one exception: it is allowed to contain "//"-style comments. Members Web manifests can contain the following keys. Click each one for more information about it: background_colorcategoriesdescriptiondirdisplayiarc_rating_idiconslangnameorientationprefer_related_applicationsrelated_applicationsscopescreenshotsserviceworkershort_nameshortcutsstart_urltheme_color Example man...
... Note: If the manifest requires credentials to fetch - the crossorigin attribute must be set to use-credentials, even if the manifest file is in the same origin as the current page. Splash screens In Chrome 47 and later, a splash screen is displayed for sites launched from a ...
... in your HTML pages using a <link> element in the <head> of a document: <link rel="manifest" href="/manifest.webmanifest"> Note: The .webmanifest extension is specified in the Media type registration section of the specification (the response of the manifest file should return Content-Type: application/manifest+json). Browsers generally support manifests with other appropriate extensions like .json (Content-Type: application/json). Note: If the manifest requires credentials to fetch - the crossorigin attribute must be set to use-credentials, even if the manifest file is in the same origin as the current page. Splash screens In Chrome 47 and later, a splash screen is displayed for sites launched from a homescreen. This splashscreen is auto-generated from properties in the web app manif...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
ich means all the notifications sent to the user will be visible to them, and the second one is the applicationServerKey, which contains our successfully acquired and converted VAPID key. ...
... contains our successfully acquired and converted VAPID key. return registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: convertedVapidKey }); Now let's move to the subscription part -- the app first sends the subscription details as JSON to the server using Fetch. ...
...lly acquired and converted VAPID key. return registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: convertedVapidKey }); Now let's move to the subscription part -- the app first sends the subscription details as JSON to the server using Fetch. ...
...is defined: document.getElementById('doIt').onclick = function() { const payload = document.getElementById('notification-payload').value; const delay = document.getElementById('notification-delay').value; const ttl = document.getElementById('notification-ttl').value; fetch('./sendNotification', { method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ subscription: subscription, payload: payload, delay: delay, ttl: ttl, }), }); }; When the button is clicked, fetch asks the server to send the notification with the given parameters: payload is the text that to be shown in the notification, delay defines a delay in seconds until the notificatio...
Interacting with page scripts - Archive of obsolete content
gnedContentScriptObject.greeting); }, false); </script> </body> </html> If you run the example, clicking "I will work" displays the value of "greeting" in an alert. Clicking "I will not work" fails, and the following message is logged: Permission denied to access property 'greeting' Expose functions to page scripts The structured clone algorithm is a bit more powerful than simple JSON serialization, but not much: in particular, functions aren't cloned. This means that you can't expose a function to a page script using cloneInto(), and if you clone an object into the page script scope, its methods will not be available to the page script. To expose a function defined in a content script to a page script so the page script can call it, use exportFunction(). Here's an example. ...
...stener("click", function() { alert(window.foo.greetme("page script")); }, false); </script> </body> </html> Reverting to the old behavior You can switch Firefox back to the old behavior in which content scripts could expose objects and functions to page scripts using unsafeWindow. To do this, add an option called "unsafe-content-script" under the "permissions" key in package.json, and set it to true. "permissions": { "unsafe-content-script": true } This is only a temporary migration aid, and will be removed eventually. Communicating with page scripts There are two different ways a content script can communicate with a page script: using the DOM postMessage() API using custom DOM events Using the DOM postMessage API Note that before Firefox 31 code in cont...
...nt("addon-message", true, true, { hello: 'world' }); document.documentElement.dispatchEvent(event); } </script> <button onclick="sendMessage()">Send Message</button> </body> </html> Finally, the content script "listen.js" listens for the new event and retrieves the payload from its detail attribute: window.addEventListener("addon-message", function(event) { console.log(JSON.stringify(event.detail)); }, false); ...
context-menu - Archive of obsolete content
ta: "item2" }), cm.Item({ label: "Item 3", data: "item3" }) ] }); Communicating With the Add-on Often you will need to collect some kind of information in the click listener and perform an action unrelated to content. To communicate to the menu item associated with the content script, the content script can call the postMessage function attached to the global self object, passing it some JSON-able data. The menu item's "message" event listener will be called with that data. var cm = require("sdk/context-menu"); cm.Item({ label: "Edit Image", context: cm.SelectorContext("img"), contentScript: 'self.on("click", function (node, data) {' + ' self.postMessage(node.src);' + '});', onMessage: function (imgSrc) { openImageEditor(imgSrc); } });...
... message If you listen to this event you can receive message events from content scripts associated with this menu item. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the menu item's message event. Arguments value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value. Menu A labeled menu item that expands into a submenu. Methods addItem(item) Appends a menu item to the end of the menu. If the item is already contained in another menu or in the top-level context menu, it's automatically removed first. If the item is already contained in this menu it will just be moved to the end of the menu. Parameters item : Item,Menu,Separator The ...
... message If you listen to this event you can receive message events from content scripts associated with this menu item. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the menu item's message event. Arguments value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value. Separator A menu separator. Separators can be contained only in Menus, not in the top-level context menu. Methods destroy() Permanently removes the separator from its parent menu and frees its resources. The separator must not be used afterward. If you need to remove the separator from its parent menu but use it afterward, call removeItem() on the parent menu instead. Pr...
page-mod - Archive of obsolete content
This means you can't send functions, and if the object contains methods they won't be usable. You also can't pass cyclic values. Name: contentStyleFile Type: string,array Use this option to load one or more stylesheets into the tar...
...This means you can't send functions, and if the object contains methods they won't be usable. You also can't pass cyclic values. Name: contentStyleFile Type: string,array Use this option to load one or more stylesheets into the targeted documents as user stylesheets. Each stylesheet is supplied a...
...This means you can't send functions, and if the object contains methods they won't be usable. You also can't pass cyclic values. ...
self - Archive of obsolete content
to content scripts, which is used by a content script to communicate with the add-on code. 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). While not generally of use to add-on code directly, it can be used by internal API code to index local storage and other resources that are associated with a particular add-on. name This property contains the add-on's short name. It comes from the name property in the main package's package.json file. version This property ...
...f use to add-on code directly, it can be used by internal API code to index local storage and other resources that are associated with a particular add-on. name This property contains the add-on's short name. It comes from the name property in the main package's package.json file. version This property contains the add-on's version string. It comes from the version property set in the package.json file in the main package. loadReason This property contains of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade isPrivateBrowsingSupported This property indicates whether or not the add-on supports private browsing. It comes from the private-browsing key in the add-on's package.json file. data The data object is used to access da...
...dd-on was loaded: install enable startup upgrade downgrade isPrivateBrowsingSupported This property indicates whether or not the add-on supports private browsing. It comes from the private-browsing key in the add-on's package.json file. data The data object is used to access data that was bundled with the add-on. This data lives in the add-on's data/ directory, immediately below the package.json file. All files in this directory will be copied into the XPI and made available through the data object. The Package Specification article explains the package.json file. Methods data.load(name) The data.load() method returns the contents of an embedded data file, as a string. It is most useful for data that will be modified or parsed in some way, such as JSON, XML, plain text, or perhaps an...
simple-prefs - Archive of obsolete content
s, and users can configure these preferences in the Add-ons Manager. This gives users a consistent way to access and modify preferences across different add-ons. This API is for your add-on's preferences. If you need to get and set the general browser preferences, use preferences/service. Usage Defining and initializing preferences To define preferences and give them initial values, add a new JSON array called preferences to your package.json file, and give it one entry for each preference: { "fullName": "Example Add-on", ... "preferences": [{ "name": "somePreference", "title": "Some preference title", "description": "Some short description for the preference", "type": "string", "value": "this is the default string value" }, { ...
... }, { "value": "C", "label": "Chaotic" } ] } control Displays a button. When the user clicks the button, the function listening to the on() function for this preference is called. This type requires a mandatory attribute called "label" which is provided as a string. It is used to label the button. In "package.json": { "type": "control", "label": "Click me!", "name": "sayHello", "title": "Say Hello" } In "main.js": var sp = require("sdk/simple-prefs"); sp.on("sayHello", function() { console.log("hello"); }); Localization Using the SDK's localization system, you can provide translated forms of the title and description attributes. See the localization tutorial for...
...rence'] The ability to change the default preferences branch is new in Add-on SDK 1.15. The branch of the preferences tree under which simple-prefs are stored is, by default, the add-on ID. Sometimes you might need to use a different branch, especially if you are porting an add-on to the SDK. You can change the sub-branch of extensions using the preferences-branch key in your add-on's package.json file. Globals Functions on(prefName, listener) Registers an event listener that will be called when a preference is changed. The event listener may take an optional parameter that specifies the name of the property which changed. Preference change events are triggered for every character typed by the user. They are also triggered once during add-on initialization. Example: function onPr...
core/promise - Archive of obsolete content
of url asynchronously then(parse). // parse content from the url then(extractQuery). ...
...parse content from the url then(extractQuery). ...
... // extract SQL query then(readDBAsync); // exectue extracted query against DB Nested chaining Flat chaining is not always an option though, as in some cases you may want to capture intermediate values of the chain: var result = readAsync(url).then(function(source) { var json = parse(source); return readDBAsync(extractQuery(json)).then(function(data) { return writeAsync(json.url, data); }); }); In general, nesting is useful for computing values from more than one promise: function eventualAdd(a, b) { return a.then(function (a) { return b.then(function (b) { return a + b; }); }); } var c = eventualAdd(aAsync(), bAsync()); Error handling One sometimes-unintuitive aspect of promises is that if you throw an exception in the value handler, it will...
Index - Archive of obsolete content
137 jpm Add-on SDK, JPM jpm is a command-line tool that enables you to test, run, and package add-ons. 138 jpm-mobile ADB, Add-ons, JPM, Mobile, Testing, travis-ci The Node-based replacement for cfx --force-mobile. Enables you to run and test add-ons for Firefox Mobile (aka Fennec). 139 jpmignore JPM No summary! 140 package.json CommonJS, JPM, SDK, add-on, package.json The package.json file contains manifest data for your add-on, providing not only descriptive information about the add-on for presentation in the Add-ons Manager, but other metadata required of add-ons. 141 Tutorials Add-on SDK No summary! 142 Add a Context Menu Item Add-on SDK, Firefox, Guide No summary!
...hat it would get full access to the browser (cookies, history etc) and to user's files. These issues can easily be avoided by making use of the existing security mechanisms in the Mozilla codebase. The following article explains these security mechanisms, ideally an extension that needs to display web content (which is always potentially dangerous) will use all of them. 231 Downloading JSON and JavaScript in extensions AJAX, Add-ons, Extensions, JSON, XMLHttpRequest A common practice found in many extensions is using XMLHttpRequest (or some other mechanism) to download JavaScript or JSON (they are different) from a remote website. Once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into JavaScript objects. This pr...
...ummary! 3284 Inner-browsing extending the browser navigation paradigm This article is the version from 2003 with slight modifications (no images and no links to samples). It's here for reference. 3285 Install.js Add-ons, Extensions, XPInstall_API_reference See also this article from XulPlanet's Main Tutorial. 3286 JXON AJAX, DOM, Document, JSON, JXON, Object, Object-Oriented, XML, XMLHttpRequest, XPath 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 appear on the web. There are some cases in which the whole content of an XML document must be read from the JavaScript...
Index - Learn web development
I, Article, Beginner, Canvas, CodingScripting, Graphics, JavaScript, Learn, WebGL At this point, you should have a useful idea of the basics of graphics programming using Canvas and WebGL and what you can do with these APIs, as well as a good idea of where to go for further information. Have fun! 59 Fetching data from the server API, Article, Beginner, CodingScripting, Fetch, JSON, JavaScript, Learn, Promises, Server, XHR, XML, XMLHttpRequest, data, request This article shows how to start working with both XHR and Fetch to fetch data from the server. 60 Introduction to web APIs 3rd party, API, Article, Beginner, Browser, CodingScripting, Learn, Object, WebAPI, client-side At this point, you should have a good idea of what APIs are, how they work,...
...dingScripting, Constructor, Create, JavaScript, Learn, OOJS, OOP, Object, Object-Oriented, instance, l10n:priority This article has provided a simplified view of object-oriented theory -- this isn't the whole story, but it gives you an idea of what we are dealing with here. In addition, we have started to look at different ways of generating object instances. 71 Test your skills: JSON Beginner, Example, JSON, JavaScript This aim of this skill test is to assess whether you've understood our Working with JSON article. 72 Test your skills: Object basics Beginner, JavaScript, Learn, Objects, test your skills This aim of this skill test is to assess whether you've understood our JavaScript object basics article. 73 Test your skills: Object-...
... assess whether you've understood our JavaScript object basics article. 73 Test your skills: Object-oriented JavaScript Beginner, JavaScript, Learn, OOJS, Objects, test your skills The aim of this skill test is to assess whether you've understood our Object-oriented JavaScript for beginners, Object prototypes, and Inheritance in JavaScript articles. 74 Working with JSON Article, Beginner, CodingScripting, Guide, JSON, JSON API, JSON Arrays, JSON parsing, JSON structure, JavaScript, Learn, Objects, Tutorial, l10n:priority In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article, we'll begin looking at object-oriented JavaScript. ...
Introducing JavaScript objects - Learn web development
ype chains work, and look at how the prototype property can be used to add methods to existing constructors. Inheritance in JavaScript With most of the gory details of OOJS now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. In addition, we present some advice on when and where you might use OOJS. Working with JSON data JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax, which is commonly used for representing and transmitting data on web sites (i.e. sending some data from the server to the client, so it can be displayed on a web page). You'll come across it quite often, so in this article, we give you all you need to work wi...
... Object building practice In previous articles we looked at all the essential JavaScript object theory and syntax details, giving you a solid base to start from. ...
...andard text-based format for representing structured data based on JavaScript object syntax, which is commonly used for representing and transmitting data on web sites (i.e. sending some data from the server to the client, so it can be displayed on a web page). You'll come across it quite often, so in this article, we give you all you need to work with JSON using JavaScript, including parsing the JSON so you can access data items within it and writing your own JSON. Object building practice In previous articles we looked at all the essential JavaScript object theory and syntax details, giving you a solid base to start from. In this article we dive into a practical exercise, giving you some more practice in building custom JavaScript objects, which produce something fun and colorful -- some c...
Getting started with Svelte - Learn web development
te 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. ...
...ild 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. ...
... structure: moz-todo-svelte +-- readme.md +-- package.json +-- package-lock.json +-- rollup.config.js +-- .gitignore +-- node_modules +-- public | +-- favicon.ico | +-- index.html | +-- global.css | +-- build | +-- bundle.css | +-- bundle.css.map | +-- bundle.js | +-- bundle.js.map +-- src +-- App.svelte +-- main.js The contents are as follows: package.json and package-lock.json: Contains information about the project that Node.js/npm uses to keep it organized. 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. node_modules: This is where node saves the proje...
Working with Svelte stores - Learn web development
tring to object when saving, and vice versa when we are loading the value from local storage. Create a new file called localStore.js, in your src directory. ...
... value from local storage. Create a new file called localStore.js, in your src directory. ...
...methods: subscribe(), set(), and update(). When we create a new localStore, we'll have to specify the key of the web storage and an initial value. We then check if the value exists in web storage and, if not, we create it. We use the localStorage.getItem(key) and localStorage.setItem(key, value) methods to read and write information to web storage, and the toString() and toObj() (which uses JSON.parse()) helper functions to convert the values. Next, we convert the string content received from the web storage to an object, and save that object in our store. Finally, every time we update the contents of the store, we also update the web storage, with the value converted to a string. Notice that we only had to redefine the set() method, adding the operation to save the value to ...
Dict.jsm
of key/value pairs with which to initialize the dictionary: var someObj = {}; var newDict = new Dict({key1: "foo", key2: someObj}); Note that values may be any JavaScript object type. Note: You can actually specify non-strings as keys; these are converted to strings before being used, so they're documented here as if they were a string parameter. In Firefox 19 and above, you may also pass a JSON String to initialize the dictionary: var someJSON = '{key1: "foo", key2: {}}'; var newDict = new Dict(someJSON); Note: Any String you pass will be assumed to be JSON. Method overview Dict copy(); boolean del(String aKey); Object get(String aKey, [optional] Object aDefault); boolean has(String aKey); Array listitems(); Array listkeys(); ...
... items Iterator Returns an iterator over all of the items in the dictionary; each item is returned as a pair (a two-element array) with the first element being the key and the second being the value. ...
.... Note: The order in which items are returned is arbitrary. Array listvalues(); Parameters None. Return value An array of the values in the dictionary. set() Sets the value for a given key, adding a new key to the dictionary if necessary. void set( String aKey, Object aValue ); Parameters aKey The key whose value is to be set. aValue The value to assign to the given key. toJSON() Returns a JSON String representation of the dictionary. String toJSON(); Parameters None. Return value A JSON String representation of the dictionary's key/value pairs. This will be "{}" for an empty dictionary. toString() Returns a string representation of the dictionary. String toString(); Parameters None. Return value A string representation of the dictionary's key/value pairs...
DMD
orts should be anonymized; and minimize is a boolean that indicates if memory usage should be minimized first. (Linux only) You can send signal 34 to the firefox process, e.g. with the following command. $ killall -34 firefox Each one of these steps triggers all the memory reporters and then DMD analyzes the reports, printing commentary like this: DMD[5222] opened /tmp/dmd-1414556492-5222.json.gz for writing DMD[5222] Dump 1 { DMD[5222] Constructing the heap block list... DMD[5222] Constructing the stack trace table... DMD[5222] Constructing the stack frame table... DMD[5222] } In an e10s-enabled build, you'll see separate output for each process. This step can take 10 or more seconds and may make Firefox freeze temporarily. If you see the "opened" line, it tells you where the...
...be sure to replace org.mozilla.fennec_$USERNAME with the app identifier as appropriate). ...
...existing memory-report dumping hook: adb shell am broadcast -a org.mozilla.gecko.MEMORY_DUMP In logcat, you should see output similar to this: I/DMD (20731): opened /storage/emulated/0/Download/memory-reports/dmd-default-20731.json.gz for writing ... I/GeckoConsole(20731): nsIMemoryInfoDumper dumped reports to /storage/emulated/0/Download/memory-reports/unified-memory-report-default-20731.json.gz The path is where the memory reports and DMD reports get dumped to. You can pull them like so: adb pull /sdcard/Download/memory-reports/dmd-default-20731.json.gz adb pull /sdcard/Download/memory-reports/unified-memory-report-default-20731.json.gz Processing the output DMD outputs one gzipped JSON file per process that contains a description of that process's heap. You can analyze these f...
Hacking Tips
e Baseline compiler, and the interpreter. In addition it provides a clean way to analyze if instructions are inferred as being monomorphic or polymorphic in addition to the number of time each category of type has been observed. Using the TraceLogger (JS shell / browser) Create graphs showing time spent in which engine and which function like this. Whenever running a testcase the file "tl-data.json" and several "tl-*" files get created in the "/tmp" directory. (Per proces a "tl-data-*PID*.json" file and per thread a "tl-tree.*PID*.*ID*.tl", "tl-event.*PID*.*ID*.tl" and "tl-dict.*PID*.*ID*.json" file). These files contain all information to create a tracelogger graph. On https://github.com/h4writer/tracelogger you can find the instructions to create the graph (Tools V2 > 1. Creating a tracel...
...his will remove entries that took only a minor time (=entries that will only show up with les than 1px). This can be done with the reduce.py script in https://github.com/haytjes/tracelogger/tree/master/tools_v2. You need to download "engine.js", "reduce.py", "reduce.js", "reduce-tree.js" and "reduce-corrections.js". Running this tool is a matter of running "python reduce.py JS_SHELL /tmp/tl-data.json tl-reduced". Where JS_SHELL is a real shell. Using callgrind (JS shell) As SpiderMonkey just-in-time compiler are rewriting the executed program, valgrind should be informed from the command line by adding --smc-check=all-non-file. $ valgrind --tool=callgrind --callgrind-out-file=bench.clg \ --smc-check=all-non-file --vex-iropt-register-updates=allregs-at-mem-access ./js ./run.js The ou...
...nMonkey spew is extremely verbose (not as much as the INFER spew), but you can filter it to focus on the list of compiled scripts or channels, IonMonkey spew channels can be selected with the IONFLAGS environment variable, and compilation spew can be filtered with IONFILTER. IONFLAGS contains the names of each channel separated by commas. The logs channel produces 2 files in /tmp/, one (/tmp/ion.json) made to be used with iongraph (made by Sean Stangl) and another one (/tmp/ion.cfg) made to be used with c1visualizer. These tools will show the MIR & LIR steps done by IonMonkey during the compilation. If you would like to use iongraph, you must install Graphviz. Compilation logs and spew can be filtered with the IONFILTER environment variable which contains locations as output in other spew ch...
JSProtoKey
aScript JSProto_Null A Dummy key for invalid prototype. ...
... JSProto_Null A Dummy key for invalid prototype. ...
...key for invalid prototype. ...
The Publicity Stream API
posted. onerror is an error callback that will be invoked if the publicity fails. Possible error codes include: denied - if the user refuses to publicize the activity permissionDenied - if the publicizing site is not allowed to post to the publicity stream networkError - if the publicity server is unreachable activityParseError - if the activity contains syntax errors (not proper JSON) invalidActivity - if the activity contains semantic errors (i.e. missing required properties) Finally, the publicizeActivity() function will throw an exception if required arguments are missing, or if unsupported arguments are present. getPublicityStream( onsuccess: <function>, { [ onerror: <function> ], [ for_apps: <list> ], [ since: <Date> ], [ before: <Date> ], [ count: <int> ])...
...g called from an origin which hosts a web store. It is not recommended that applications consume the publicity stream in any way (please use your own server for any in-app social aspects). It is suggested that the list be processed and condensed into an attractive, cohesive format for users (eg., multiple tweets show as 'Adam tweeted 4 times'). onsuccess will be called with a single argument: a json list of the current user's socially relevant app activity in the FIXME: deadLinkActivity Streams open specification. onerror is an error callback that will be invoked if the installation fails. Possible error codes include: denied - if the user does not log in correctly permissionDenied - if the site is not allowed to access the publicity stream networkError - if the publicity serve...
... relevant app activity in the FIXME: deadLinkActivity Streams open specification. onerror is an error callback that will be invoked if the installation fails. Possible error codes include: denied - if the user does not log in correctly permissionDenied - if the site is not allowed to access the publicity stream networkError - if the publicity server is unreachable for_apps is a json list of apps that this store has (each represented as its origin URL), so that stream events not relating to applications in a given presentation context can be excluded from the return value. If null or an empty list is passed, events for all apps are returned. since The timestamp of the earliest event you want returned. If not specified, will default to the beginning of the stream. before T...
Components.utils.evalInSandbox
Use To use evalInSandbox(), you must first create a sandbox object using its constructor, Components.utils.Sandbox. ...
... Use To use evalInSandbox(), you must first create a sandbox object using its constructor, Components.utils.Sandbox. ...
... Use To use evalInSandbox(), you must first create a sandbox object using its constructor, Components.utils.Sandbox. ...
Components.utils.import
s from mozIJSSubScriptLoader: The behavior when importing/loading the same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object. Components.utils.import evaluates the code of each module only once, in its own scope. ...
...he same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object. Components.utils.import evaluates the code of each module only once, in its own scope. ...
...lobal object. Components.utils.import evaluates the code of each module only once, in its own scope. For example: var scope1 = {}, scope2 = {}; Components.utils.import("resource://gre/modules/JSON.jsm", scope1); Components.utils.import("resource://gre/modules/JSON.jsm", scope2); assert(scope2.XPCOMUtils === scope1.XPCOMUtils); ...returns true, whereas: var someURL = "resource://gre/modules/JSON.jsm"; var obj1 = {}, obj2 = {}; var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getService(Components.interfaces.mozIJSSubScriptLoader); loader.loadSubScript(someURL, obj1); loader.loadSubScript(someURL, obj2); assert(obj2 === obj1); ...returns false. This means Components.utils.import is better suited for efficient sharing of code (and data?) b...
Source map errors - Firefox Developer Tools
Source maps are JSON files providing a way to associate transformed sources, as seen by the browser, with their original sources, as written by the developer. You can sometimes encounter problems working with source maps. This page explains the most common problems and how to fix them. Note: If you're new to source maps, you can learn more about them in How to use a source map. General source map error reporting If you do see a problem, a message will appear in the webconsole. This message will show an error message, the resource URL, and the source map URL: Here, the resource URL tells us that bundle.js mentions a source map, and the source map URL tells us where to find the source map data (in this case, relative to the resource). ...
...e map error reporting If you do see a problem, a message will appear in the webconsole. This message will show an error message, the resource URL, and the source map URL: Here, the resource URL tells us that bundle.js mentions a source map, and the source map URL tells us where to find the source map data (in this case, relative to the resource). The error tells us that the source map is not JSON data -- so we're serving the wrong file. There are a few common ways that source maps can go wrong; they are detailed in the following sections. Source map missing or inaccessible The source map resource can be missing or inaccessible. The fix here is to make sure the file is being served and is accessible to the browser Invalid source map The source map data can be invalid -- either simp...
...so we're serving the wrong file. There are a few common ways that source maps can go wrong; they are detailed in the following sections. Source map missing or inaccessible The source map resource can be missing or inaccessible. The fix here is to make sure the file is being served and is accessible to the browser Invalid source map The source map data can be invalid -- either simply not a JSON file at all, or with an incorrect structure. Typical error messages here are: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Error: "version" is a required argument Original source missing An original source may be missing. You may encounter this when trying to open one of the original sources in the debugger. The message looks a little different in th...
FileSystemDirectoryEntry.getDirectory() - Web APIs
TH_EXISTS_ERR. true true Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. [1] When create is false, the value of exclusive is irrelevant and ignored. Example In this example, a function is presented whose job it is to locate within a user's app data directory a JSON file containing a user dictionary for a specified language, then load that dictionary. let dictionary = null; function loadDictionaryForLanguage(appDataDirEntry, lang) { dictionary = null; appDataDirEntry.getDirectory("Dictionaries", {}, function(dirEntry) { dirEntry.getFile(lang + "-dict.json", {}, function(fileEntry) { fileEntry.file(function(dictFile)) { let reader = n...
...The success callback for this takes the resulting directory entry object and calls get...
...a directory. The success callback for this takes the resulting directory entry object and calls getFile() to get a FileSystemFileEntry object representing the dictionary file; the success callback for this, in turn, creates a new FileReader and uses it to load the contents of the file. When that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into JSON.parse() to be reconstituted into a JavaScript object. Specifications Specification Status Comment File and Directory Entries APIThe definition of 'getDirectory()' in that specification. Draft Initial specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, pleas...
FileSystemDirectoryEntry.getFile() - Web APIs
TH_EXISTS_ERR. true true Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. [1] When create is false, the value of exclusive is irrelevant and ignored. Example In this example, a function is presented whose job it is to locate within a user's app data directory a JSON file containing a user dictionary for a specified language, then load that dictionary. let dictionary = null; function loadDictionaryForLanguage(appDataDirEntry, lang) { dictionary = null; appDataDirEntry.getDirectory("Dictionaries", {}, function(dirEntry) { dirEntry.getFile(lang + "-dict.json", {}, function(fileEntry) { fileEntry.file(function(dictFile)) { let reader = n...
...The success callback for this takes the resulting directory entry object and calls get...
...a directory. The success callback for this takes the resulting directory entry object and calls getFile() to get a FileSystemFileEntry object representing the dictionary file; the success callback for this, in turn, creates a new FileReader and uses it to load the contents of the file. When that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into JSON.parse() to be reconstituted into a JavaScript object. Specifications Specification Status Comment File and Directory Entries APIThe definition of 'getFile()' in that specification. Draft Initial specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please che...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
ossible overhead involved with multiple calls to handle the same kind of work. The snippet below creates a function that batches multiple messages into an array, using a microtask to send them as a single object when the context exits. const messageQueue = []; let sendMessage = message => { messageQueue.push(message); if (messageQueue.length === 1) { queueMicrotask(() => { const json = JSON.stringify(messageQueue); messageQueue.length = 0; fetch("url-of-receiver", json); }); } }; When sendMessage() gets called, the specified message is first pushed onto the message queue array. Then things get interesting. If the message we just added to the array is the first one, we enqueue a microtask that will send a batch. The microtask will execute, as always, when ...
...tion path reaches the top level, just before running callbacks. That means that any further calls to sendMessage() made in the interim will push their messages onto the message queue, but because of the array length check before adding a microtask, no new microtask is enqueued. When the microtask runs, then, it has an array of potentially many messages waiting for it. It starts by encoding it as JSON using the JSON.stringify() method. After that, the array's contents aren't needed anymore, so we empty the messageQueue array. Finally, we use the fetch() method to send the JSON string to the server. This lets every call to sendMessage() made during the same iteration of the event loop add their messages to the same fetch() operation, without potentially having other tasks such as timeouts or t...
...ontents aren't needed anymore, so we empty the messageQueue array. Finally, we use the fetch() method to send the JSON string to the server. This lets every call to sendMessage() made during the same iteration of the event loop add their messages to the same fetch() operation, without potentially having other tasks such as timeouts or the like delay the transmission. The server will receive the JSON string, then will presumably decode it and process the messages it finds in the resulting array. Examples Simple microtask example In this simple example, we see that enqueueing a microtask causes the microtask's callback to run after the body of this top-level script is done running. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document...
Capabilities, constraints, and settings - Web APIs
ox which we use to display the current configuration of the track's configurable properties. This display is updated by the function getCurrentSettings(), which gets the current settings for the audio and video tracks and inserts the corresponding code into the tracks' settings display boxes by setting their value. function getCurrentSettings() { if (videoTrack) { videoSettingsText.value = JSON.stringify(videoTrack.getSettings(), null, 2); } if (audioTrack) { audioSettingsText.value = JSON.stringify(audioTrack.getSettings(), null, 2); } } This gets called after the stream first starts up, as well as any time we've applied updated constraints, as you'll see below. Building the track constraint set objects The buildConstraints() function builds the MediaTrackConstraints obje...
... This gets called after the stream first starts up, as well as any time we've applied updated constraints, as you'll see below. Building the track constraint set objects The buildConstraints() function builds the MediaTrackConstraints objects for the audio and video tracks using the code in the two tracks' constraint set edit boxes. function buildConstraints() { try { videoConstraints = JSON.parse(videoConstraintEditor.value); audioConstraints = JSON.parse(audioConstraintEditor.value); } catch(error) { handleError(error); } } This uses JSON.parse() to parse the code in each editor into an object. If either call to JSON.parse() throws an exception, handleError() is called to output the error message to the log. Configuring and starting the stream The startVideo() metho...
...error occurs applying either set of constraints, handleError() is used to output a message into the log. document.getElementById("applyButton").addEventListener("click", function() { if (!videoTrack && !audioTrack) { startVideo(); } else { buildConstraints(); if (videoTrack) { videoTrack.applyConstraints(videoConstraints).then(function() { videoSettingsText.value = JSON.stringify(videoTrack.getSettings(), null, 2); }).catch(handleError); } if (audioTrack) { audioTrack.applyConstraints(audioConstraints).then(function() { audioSettingsText.value = JSON.stringify(audioTrack.getSettings(), null, 2); }).catch(handleError); } } }, false); Handling the stop button Then we set up the handler for the stop button. document.getE...
Metadata.modificationTime - Web APIs
have been modified if the metadata or the contents of the referenced file (or directory, or whatever other kind of file system entry might exist on the platform in use) has changed. Syntax var modificationTime = Metadata.modificationTime; Value A Date timestamp indicating when the file system entry was last changed. Example This example tries to get a particular working file at tmp/workfile.json. ...
...ntry was last changed. Example This example tries to get a particular working file at tmp/workfile.json. Once that file has been found, its metadata is obtained and the file's modification timestamp year is compared to the current year. If it was last modified in a year at least five prior to the current year, the file is removed and a new one is created. ...
...ed in a year at least five prior to the current year, the file is removed and a new one is created. workingDirectory.getFile("tmp/workfile.json", { create: true }, function(fileEntry) { fileEntry.getMetadata(function(metadata) { if ((new Date().getFullYear() - metadata.modificationTime.getFullYear()) >= 5) { fileEntry.remove(function() { workingDirectory.getFile("tmp/workfile.json", { create: true }, function(newEntry) { fileEntry = newEntry; }); }); } }); }, handleError); This API has no official W3C or WHATWG specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull req...
RTCDataChannel.protocol - Web APIs
annel property protocol returns a DOMString containing the name of the subprotocol in use. If no protocol was specified when the data channel was created, then this property's value is "" (the empty string). The permitted values of this property are defined by the Web site or app using the data channel. The ability for each channel to have a defined subprotocol lets your app, for example, use JSON objects as messages on one channel while another channel is plaintext and another is raw binary or even some other format. Syntax var subProtocol = aDataChannel.protocol; Value A string identifying the app-defined subprotocol being used for exchanging data on the channel. If none has been established, this is an empty string (""). Example var pc = new RTCPeerConnection(); var dc = pc.creat...
...hannel is plaintext and another is raw binary or even some other format. Syntax var subProtocol = aDataChannel.protocol; Value A string identifying the app-defined subprotocol being used for exchanging data on the channel. If none has been established, this is an empty string (""). ...
...aChannel.protocol; Value A string identifying the app-defined subprotocol being used for exchanging data on the channel. If none has been established, this is an empty string (""). Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel", { protocol: "json" }); function handleChannelMessage(dataChannel, msg) { switch(dataChannel.protocol) { case "json": /* process JSON data */ break; case "raw": /* process raw binary data */ break; } } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.protocol' in that specification. Candidate Recommendation Initial specification. ...
Request - Web APIs
Web › API › Request
ject. Request implements Body, so it also has the following methods available to it: Body.arrayBuffer() Returns a promise that resolves with an ArrayBuffer representation of the request body. Body.blob() Returns a promise that resolves with a Blob representation of the request body. Body.formData() Returns a promise that resolves with a FormData representation of the request body. Body.json() Returns a promise that resolves with a JSON representation of the request body. Body.text() Returns a promise that resolves with an USVString (text) representation of the request body. Note: The Body functions can be run only once; subsequent calls will resolve with empty strings/ArrayBuffers. Examples In the following snippet, we create a new request using the Request() constructor (f...
... You could then fetch this api request by passing the Request object in as a parameter to a WindowOrWorkerGlobalScope.fetch() call, for example and get the response: fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new Error('Something went wrong on api server!'...
...ormData, URLSearchParams, USVString or ReadableStream type, so for adding a JSON object to the payload you need to stringify that object. You could then fetch this api request by passing the Request object in as a parameter to a WindowOrWorkerGlobalScope.fetch() call, for example and get the response: fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new Error('Something went wrong on api server!'); } }) .then(response => { console.debug(response); // ... }).catch(error => { console.error(error); }); Specifications Specification Status Comment FetchThe definition of 'Request' in that specification. Living Standard Initial definition ...
Using server-sent events - Web APIs
ta; eventList.appendChild(newElement); } This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML. You can also listen for events with addEventListener(): evtSource.addEventListener("ping", function(event) { const newElement = document.createElement("li"); const time = JSON.parse(event.data).time; newElement.innerHTML = "ping at " + time; eventList.appendChild(newElement); }); This code is similar, except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the JSON in the data field and outputs that information. When not used over HTTP/2, SSE suffers from a limitation to the maximum numb...
...ATE_ISO8601); echo 'data: {"time": "' . $curDate . '"}'; echo "\n\n"; // Send a simple message at random intervals. $counter--; if (!$counter) { echo 'data: This is a message at time ' . $curDate . "\n\n"; $counter = rand(1, 10); } ob_end_flush(); flush(); sleep(1); } The code above generates an event every second, with the event type "ping". Each event's data is a JSON object containing the ISO 8601 timestamp corresponding to the time at which the event was generated. At random intervals, a simple message (with no event type) is sent. Note: You can find a full example that uses the code shown in this article on GitHub -- see Simple SSE demo using PHP. Error handling When problems occur (such as a network timeout or issues pertaining to access control), an ...
...th the value "some text". The third message contains a data field with the value "another message\nwith two lines". Note the newline special character in the value. : this is a test stream data: some text data: another message data: with two lines Named events This example sends named events. Each has an event name specified by the event field, and a data field whose value is an appropriate JSON string with the data needed for the client to act on the event. The data field could, of course, have any string data; it doesn't have to be JSON. event: userconnect data: {"username": "bobby", "time": "02:33:48"} event: usermessage data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."} event: userdisconnect data: {"username": "bobby", "time": "02:34:23"} event: usermessage d...
Using Service Workers - Web APIs
e); Note: You can find a lot more out about promises by reading Jake Archibald's excellent JavaScript Promises: there and back again. Service workers demo To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called sw-test, which is a simple Star wars Lego image gallery. It uses a promise-powered function to read image data from a JSON object and load the images using Ajax, before displaying the images in a line down the page. We've kept things static and simple for now. It also registers, installs, and activates a service worker, and when more of the spec is supported by browsers it will cache all the files required so it will work offline! You can see the source code on GitHub, and view the example live. The one bit we...
...so it will work offline! You can see the source code on GitHub, and view the example live. The one bit we'll call out here is the promise (see app.js lines 22-47), which is a modified version of what you read about above, in the Promises test demo. It is different in the following ways: In the original, we only passed in a URL to an image we wanted to load. ...
... In the original, we only passed in a URL to an image we wanted to load. In this version, we pass in a JSON fragment containing all the data for a single image (see what they look like in image-list.js). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. ...
Using Web Workers - Web APIs
nd result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning. ...
...er. example.html: (the main page): var myWorker = new Worker('my_task.js'); myWorker.onmessage = function(oEvent) { console.log('Worker said : ' + oEvent.data); }; myWorker.postMessage('ali'); my_task.js (the worker): postMessage("I\'m working before postMessage(\'ali\')."); onmessage = function(oEvent) { postMessage('Hi ' + oEvent.data); }; The structured cloning algorithm can accept JSON and a few things that JSON can't -- like circular references. Passing data examples Example #1: Advanced passing JSON Data and creating a switching system If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together. First, we create a QueryableWorker class that takes the url o...
... example.html (the main page): <!doctype html> <html> <head> <meta charset="UTF-8" /> <title>MDN Example - Queryable worker</title> <script type="text/javascript"> /* QueryableWorker instances methods: * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. ...
Content-Location - HTTP
ontent-Location is associated with the data returned. This distinction may seem abstract without examples. Header type Entity header Forbidden header name no Syntax Content-Location: <url> Directives <url> A relative (to the request URL) or absolute URL. Examples Requesting data from a server in different formats Let's say a site's API can return data in JSON, XML, or CSV formats. If the URL for a particular document is at https://example.com/documents/foo, the site could return different URLs for Content-Location depending on the request's Accept header: Request header Response header Accept: application/json, text/json Content-Location: /documents/foo.json Accept: application/xml, text/xml Content-Location: /...
... Then the client could remember that the JSON version is available at that particular URL, skipping content negotation the next time it requests that document. The server could also consider other content negotiation headers, such as Accept-Language. ...
...ept: application/xml, text/xml Content-Location: /documents/foo.xml Accept: text/plain, text/* Content-Location: /documents/foo.txt These URLs are examples -- the site could serve the different filetypes with any URL patterns it wishes, such as a query string parameter: /documents/foo?format=json, /documents/foo?format=xml, and so on. Then the client could remember that the JSON version is available at that particular URL, skipping content negotation the next time it requests that document. The server could also consider other content negotiation headers, such as Accept-Language. Pointing to a new document (HTTP 201 Created) Say you're creating a new blog post through a site's API: PUT /new/post Host: example.com Content-Type: text/markdown # My first blog post! I ...
HTTP Index - HTTP
Web › HTTP › Index
n HTTP request is called a "resource", whose nature isn't defined further; it can be a document, a photo, or anything else. Each resource is identified by a Uniform Resource Identifier (URI) used throughout HTTP for identifying 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 Incomplete 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 documen...
...ntent-Security-Policy Report-To HTTP response header field instructs the user agent to store reporting endpoints for an origin. 95 CSP: report-uri CSP, Directive, HTTP, Reference, Security The deprecated HTTP Content-Security-Policy (CSP) report-uri directive instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. 96 CSP: require-sri-for CSP, Directive, HTTP, Reference, Security, Subresource Integrity, require-sri-for The HTTP Content-Security-Policy require-sri-for directive instructs the client to require the use of Subresource Integrity for scripts or styles on the page. 97 CSP: sandbox CSP, Content-Secur...
... worker-src directive specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts. 107 Content-Security-Policy-Report-Only CSP, HTTP, HTTPS, Reference, Security, header The HTTP Content-Security-Policy-Report-Only response header allows web developers to experiment with policies by monitoring (but not enforcing) their effects. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. 108 Content-Type Content-Type, Entity header, HTTP, Reference, header The Content-Type entity header is used to indicate the media type of the resource. 109 Cookie Cookies, HTTP, Reference, header, request The Cookie HTTP request header contains stored HTTP cookies previously sent by the server...
Object initializer - JavaScript
rs) {} } // Computed property names (ES2015) let prop = 'foo' let o = { [prop]: 'hey', ['b' + 'ar']: 'there' } Description An object initializer is an expression that describes the initialization of an Object. Objects consist of properties, which are used to describe an object. Values of object properties can either contain primitive data types or other objects. ...
...ey', ['b' + 'ar']: 'there' } Description An object initializer is an expression that describes the initialization of an Object. Objects consist of properties, which are used to describe an object. Values of object properties can either contain primitive data types or other objects. Object literal notation vs JSON The object literal notation is not the same as the JavaScript Object Notation (JSON). Although they look similar, there are differences between them: JSON permits only property definition using "property": value syntax. The property name must be double-quoted, and the definition cannot be a shorthand. In JSON the values can only be strings, numbers, arrays, true, false, null, or another (JSON) object. A function value (see "Methods" above) can not be assigned to a value in...
.... Although they look similar, there are differences between them: JSON permits only property definition using "property": value syntax. The property name must be double-quoted, and the definition cannot be a shorthand. In JSON the values can only be strings, numbers, arrays, true, false, null, or another (JSON) object. A function value (see "Methods" above) can not be assigned to a value in JSON. Objects like Date will be a string after JSON.parse(). JSON.parse() will reject computed property names and an error will be thrown. Examples Creating objects An empty object with no properties can be created like this: let object = {} However, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. You...
import - JavaScript
port keyword may be called as a function. When used this way, it returns a promise. import('/modules/my-module.js') .then((module) => { // Do something with the module. }); This form also supports the await keyword. ...
...sed this way, it returns a promise. import('/modules/my-module.js') .then((module) => { // Do something with the module. }); This form also supports the await keyword. let module = await import('/modules/my-module.js'); Examples Standard Import The code below shows how to import from a secondary module to assist in processing an AJAX JSON request. ...
....js'); Examples Standard Import The code below shows how to import from a secondary module to assist in processing an AJAX JSON request. The module: file.js function getJSON(url, callback) { let xhr = new XMLHttpRequest(); xhr.onload = function () { callback(this.responseText) }; xhr.open('GET', url, true); xhr.send(); } export function getUsefulContents(url, callback) { getJSON(url, data => callback(JSON.parse(data))); } The main program: main.js import { getUsefulContents } from '/modules/file.js'; getUsefulContents('http://www.example.com', data => { doSomethingUseful(data); }); Dynamic Import This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not ...
OpenSearch description format
ption> <InputEncoding>[UTF-8]</InputEncoding> <Image width="16" height="16" type="image/x-icon">[https://example.com/favicon.ico]</Image> <Url type="text/html" template="[searchURL]"> <Param name="[key name]" value="{searchTerms}"/> <!-- other Params if you need them... --> <Param name="[other key name]" value="[parameter value]"/> </Url> <Url type="application/x-suggestions+json" template="[suggestionURL]"/> <moz:SearchForm>[https://example.com/search]</moz:SearchForm> </OpenSearchDescription> ShortName A short name for the search engine. It must be 16 or fewer characters of plain text, with no HTML or other markup. Description A brief description of the search engine. It must be 1024 or fewer characters of plain text, with no HTML or other markup. InputEncoding...
... For icons loaded remotely (that is, from https:// URIs as opposed to data: URIs), Firefox will reject icons larger than 10 kilobytes. Url Describes the URL or URLs to use for the search. The template attribute indicates the base URL for the search query. Firefox supports three URL types: type="text/html" specifies the URL for the actual search query. type="application/x-suggestions+json" specifies the URL for fetching search suggestions. In Firefox 63 onwards, type="application/json" is accepted as an alias of this. type="application/x-moz-keywordsearch" specifies the URL used when a keyword search is entered in the location bar. This is supported only in Firefox. For these URL types, you can use {searchTerms} to substitute the search terms entered by the user in the searc...
...dsearch" specifies the URL used when a keyword search is entered in the location bar. This is supported only in Firefox. For these URL types, you can use {searchTerms} to substitute the search terms entered by the user in the search bar or location bar. Other supported dynamic search parameters are described in OpenSearch 1.1 parameters. For search suggestions, the application/x-suggestions+json URL template is used to fetch a suggestion list in JSON format. For details on how to implement search suggestion support on a server, see Supporting search suggestions in search plugins. Param The parameters that must be passed in along with the search query as key/value pairs. When specifying values, you can use {searchTerms} to insert the search terms entered by the user in the search bar.
Compiling from Rust to WebAssembly - WebAssembly
o wherever you keep your personal projects, and type this: $ cargo new --lib hello-wasm Created library `hello-wasm` project This creates a new library in a subdirectory named hello-wasm with everything you need to get going: +-- Cargo.toml +-- src +-- lib.rs First, we have Cargo.toml; this is the file that we use to configure our build. If you've used Gemfile from Bundler or package.json from npm, this is likely to be familiar; Cargo works in a similar manner to both of them. Next, Cargo has generated some Rust code for us in src/lib.rs: #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } We won't use this test code at all, so go ahead and delete it. Let's write some Rust Let's put this code into src/lib.rs instead: use wasm_bindge...
...check out this blog post on Mozilla Hacks. In short, wasm-pack build: Compiles your Rust code to WebAssembly. Runs wasm-bindgen on that WebAssembly, generating a JavaScript file that wraps up that WebAssembly file into a module npm can understand. Creates a pkg directory and move that JavaScript file and your WebAssembly code into it. Reads your Cargo.toml and produces an equivalent package.json. Copies your README.md (if you have one) into the package. The end result? You have an npm package inside of the pkg directory. A digression about code size If you check out the generated WebAssembly code size, it may be a few hundred kilobytes. We haven't instructed Rust to optimize for size at all, and doing so cuts down on the size a lot. This is beyond the scope of this tutorial, but if ...
...ebsite that uses our new package. Many people use npm packages through various bundler tools, and we'll be using one of them, webpack, in this tutorial. It's only a little bit complex, and shows a realistic use-case. Let's move back out of the pkg directory, and make a new directory, site, to try this out in: $ cd ../.. $ mkdir site $ cd site $ npm link hello-wasm Create a new file, package.json, and put the following code in it: { "scripts": { "serve": "webpack-dev-server" }, "dependencies": { "hello-wasm": "^0.1.0" }, "devDependencies": { "webpack": "^4.25.1", "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.10" } } Note that you need to fill in your own username, after the @, in the dependencies section. Next, we need to configure Webpack. Create...
self - Archive of obsolete content
precated messaging API For an overview of content scripts, see the main article. Note that the self object in content scripts is completely different from the self module, which provides an API for an add-on to access its data files and ID. self Properties options Content-scripting APIs such as tab.attach(), page-mod, and page-worker let you pass read-only data to the content script as a JSON object via the contentScriptOptions option. If you do this, the data is available to the content script in the options property of self: // main.js const tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", onReady: function(tab) { tab.attach({ contentScriptFile: "./content-script.js", contentScriptOptions: { a: "blah" } }); } }); // content-scri...
...n add-on code. This is an older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses postMessage. postMessage() Send a message from a content script to a listener in the main add-on code: self.postMessage(contentScriptMessage); This takes a single parameter, the message payload, which may be any JSON-serializable value. on() Start listening to messages from the main add-on code: self.on("message", function(addonMessage) { // Handle the message }); This takes two parameters: the name of the event, and the handler function. The handler function is passed the message payload. once() Exactly like on(), but stop listening after the first message is received. removeListener() Remove a lis...
Content Scripts - Archive of obsolete content
stylesheets and images may not have finished loading. "end": load the scripts after all content (DOM, JS, CSS, images) for the page has been loaded, at the time the window.onload event fires. The default value is "end". Note that tab.attach() doesn't accept contentScriptWhen, because it's generally called after the page has loaded. Passing configuration options The contentScriptOptions is a JSON object that is exposed to content scripts as a read-only value under the self.options property: // main.js var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { tab.attach({ contentScript: 'window.alert(self.options.message);', contentScriptOptions: {"message" : "hello world"} }); }); Any kind of jsonable value (object, array, string, etc.) can be used here. Access...
...patchEvent(event);' + '});' }); Cross-domain content scripts By default, content scripts don't have any cross-domain privileges. In particular, they can't access content hosted in an iframe, if that content is served from a different domain, or make cross-domain XMLHttpRequests. However, you can enable these features for specific domains by adding them to your add-on's package.json under the "cross-domain-content" key, which itself lives under the "permissions" key. See the article on cross-domain content scripts. ...
Content Processes - Archive of obsolete content
s out that from a security point of view there are several important advantages to thinking about content and add-on code as living in different processes. Many add-ons have to interact with content. The problem with the multiprocess model is that add-ons and content are now in different processes, and scripts in one process cannot interact directly with scripts in another. We can, however, pass JSON messages between scripts in different processes. The solution we've come up with is to introduce the notion of content scripts. A content script is a script that is injected into a content process by the main script running in the add-on process. Content scripts differ from scripts that are loaded by the page itself in that they are provided with a messaging API that can be used to send messages ...
...with is to introduce the notion of content scripts. A content script is a script that is injected into a content process by the main script running in the add-on process. Content scripts differ from scripts that are loaded by the page itself in that they are provided with a messaging API that can be used to send messages back to the add-on script. Event Emitters The messaging API we use to send JSON messages between scripts in different processes is based on the use of event emitters. An event emitter maintains a list of callbacks (or listeners) for one or more named events. Each event emitter has several methods: the method on is used to add a listener for an event. Conversely, the method removeListener is used to remove a listener for an event. The method once is a helper function which ad...
XUL Migration Guide - Archive of obsolete content
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 limitations on what you can do in this manifest file: for example, you can't register overlays, resource: URIs, or components. However, you can register a chrome: URI, with a skin and locale, and this means you can include XUL windows in an SDK-based add-on. You can keep the "chrome.manifest" file in your add-on's root directory and create a directory there called "chrome". In that d...
...ode that manipulates the browser chrome, and code that interacts with web pages all runs in the same context. But the SDK makes a distinction between: add-on scripts, which can use the SDK APIs, but are not able to interact with web pages content scripts, which can access web pages, but do not have access to the SDK's APIs Content scripts and add-on scripts communicate by sending each other JSON messages: in fact, the ability to communicate with the add-on scripts is the only extra privilege a content script is granted over a normal remote web page script. A XUL-based add-on will need to be reorganized to respect this distinction. The main reason for this design is security: it reduces the risk that a malicious web page will be able to access privileged APIs. There's much more informa...
console/traceback - Archive of obsolete content
The stack is represented as an array in which the most recent stack frame is the last element; each element thus represents a stack frame and has the following keys: filename The name of the file that the stack frame takes place in. lineNo The line number is being executed at the stack frame. funcName The name of the function being executed at the stack frame, or null if the function is anonymous or the stack frame is being executed in a top-level script or module. See nsIException for more information. ...
...e function being executed at the stack frame, or null if the function is anonymous or the stack frame is being executed in a top-level script or module. See nsIException for more information. Globals Functions fromException(exception) Attempts to extract the traceback from exception. Parameters exception : exception exception where exception is an nsIException. Returns traceback : JSON representation of the traceback or null if not found. get() Returns JSON : Returns the JSON representation of the stack at the point that this function is called. format(tbOrException) Given a JSON representation of the stack or an exception instance, returns a formatted plain text representation of it, similar to Python's formatted stack tracebacks. If no argument is provided, the stack at ...
content/symbiont - Archive of obsolete content
oaded, corresponding to the DOMContentLoaded event "end": load content scripts once all the content (DOM, JS, CSS, images) for the page has been loaded, at the time the window.onload event fires This property is optional and defaults to "end". contentScriptOptions object Read-only value exposed to content scripts under self.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. allow object Permissions for the content, with the following keys: script boolean Whether or not to execute script in the content. Defaults to true. Optional. Optional. Symbiont Symbiont is composed from the Worker trait, therefore instances of Symbiont and their descend...
...Optional. contentURL The URL of the content loaded. allow Permissions for the content, with a single boolean key called script which defaults to true and indicates whether or not to execute scripts in the content. ...
content/worker - Archive of obsolete content
s. Worker Worker is composed from the EventEmitter trait, therefore instances of Worker and their descendants expose all the public properties exposed by EventEmitter along with additional public properties that are listed below. Methods postMessage(data) Asynchronously emits "message" events in the enclosed worker, where content script was loaded. Parameters data : number,string,JSON The data to send. Must be stringifiable to JSON. destroy() Destroy the worker by removing the content script from the page and removing all registered listeners. A detach event is fired just before removal. Properties port Object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url The UR...
... If this worker is attached to a content document, returns the related tab. Events message This event allows the content worker to receive messages from its associated content scripts. Calling the self.postMessage() function from a content script will asynchronously emit the message event on the corresponding worker. Arguments value : The event listener is passed the message, which must be a JSON-serializable value. error This event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. Arguments Error : The event listener is passed a single argument which is an Error object. detach This event is emitted when the document associated with this worker is unloaded or the worker's destroy() method is called. Note that you can't...
jpmignore - Archive of obsolete content
y jpm xpi. Using .jpmignore to allow files Everything in your add-on directory will be included in the xpi file you make with jpm xpi. If your project folder contains a lot of files that aren't necessary for the xpi to run, like documentation, jshint, etc., you can use .jpmignore as a whitelist instead of a blacklist. ...
...r example: .* * !/data/** !/lib/** !/locale/** !/node_modules/** !/package.json !/icon.png !/icon64.png !/COPYING !/bootstrap.js !/install.rdf This would include all editor backup files and similar in the whitelisted subdirectories, to avoid that you can append another blacklist after the whitelist. ...
Getting Started (jpm) - Archive of obsolete content
e you've done that, you'll be looking at a command prompt. Install Firefox Developer Version for testing your add-on. Initializing an empty add-on In the command prompt, create a new directory. Navigate to it, type jpm init, and hit enter: 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 ...
...This file was created for you in the previous step. ...
Using third-party modules (jpm) - Archive of obsolete content
r example, "my-menuitem", navigate to it, type "jpm init" and accept all the defaults: mkdir my-menuitem cd my-menuitem jpm init Install the menuitem package from npm: npm install menuitem --save This will install the package in the current directory, under a directory called "node_modules". ...
... --save argument instructs npm to add this package to the dependencies key in the add-on's package.json file. You'll now see a new directory in "my-menuitem" called "node_modules". It will contain a single directory "addon-pathfinder", and the modules included in this package will be somewhere in that directory: my-menuitem index.js node_modules menuitem package.json test We're interested in using the "menuitem" module, which is at "addon-pathfinder/lib/ui/menuitem". Open "index.js" and replace it with this: var menuitems = require("menuitem"); var menuitem = menuitems.Menuitem({ id: "clickme", menuid: "menu_ToolsPopup", label: "Click Me!", onCommand: function() { console.log("clicked"); }, insertbefore: "menu_pageInfo" }); Now ru...
How to convert an overlay extension to restartless - Archive of obsolete content
e("chrome://myAddon/content/filename.ext",dataType,function(data) { /* do stuff with data */ }); Note: When using XMLHttpRequest to access a file:// URL the request.status is not properly set to 200 to indicate success. In such cases, request.readyState == 4, request.status == 0 and request.response will evaluate to true. If your file is text, use "text" as your data type. If you're getting JSON this way make sure to explicitly set the type as "text" if you intend to parse it yourself. Even though it says that the default type is "text", Firefox will attempt to autodetect and fail, resulting in an error message in the console. This doesn't seem to break anything, but it is easily avoidable by being explicit with the type. MDN says you can set the type to "json" instead, if you prefer to ...
... you intend to parse it yourself. Even though it says that the default type is "text", Firefox will attempt to autodetect and fail, resulting in an error message in the console. This doesn't seem to break anything, but it is easily avoidable by being explicit with the type. MDN says you can set the type to "json" instead, if you prefer to have it parse things for you. If your file is not text or JSON, then you're going to want to read binary data. The new way to do this is to use JavaScript typed arrays. Specify "arraybuffer" as your data type to get one from your XMLHttpRequest. To access that data you're going to need a data view to look at your typed array with. Data that's homogeneous might get away with using something like Uint32Array or one of the other standard typed array views, but ...
Appendix D: Loading Scripts - Archive of obsolete content
{ bar, foo } = module("my-module"); DOM Workers: Worker and ChromeWorker DOM Workers can be used to load scripts into their own global contexts which run in their own threads. In order to ensure thread safety, these contexts are extremely limited, can't be passed JavaScript objects, and have no access to the DOM. All communication between these contexts and outer contexts is marshalled through JSON encoding and decoding. ChromeWorkers also have access to ctypes and a limited number of thread safe XPCOM classes, but are otherwise limited to simple computation based on data passed via messages and XMLHttpRequests. Advantages Asynchronous: Workers execute asynchronously in their own threads, which means that they have limited risk of interfering with the main thread. They may safely perfor...
...ve computation which would normally need to be broken up into multiple callbacks. Safety: As workers have no access to objects which might cause a crash or deadlock when executed re-entrantly or by spinning the event loop, there are significant safety advantages over other methods of asynchronous execution. Disadvantages Limited scoping: As data from the main thread may only be accessed via JSON message passing, there are significant difficulties in performing many operations in Worker scopes. DOM Access: As there is no DOM access in Worker scopes, XMLHttpRequests may not easily be used with XML or HTML sources, and should instead only be used with JSON or other text-based sources. Debugging: JSD knows nothing about Workers and no JavaScript debuggers work on them. ...
Index of archived content - Archive of obsolete content
il/deprecate util/list util/match-pattern util/object util/uuid window/utils Release notes Tools cfx cfx to jpm console jpm jpm-mobile jpmignore package.json Tutorials Add a Context Menu Item Add a Menu Item to Firefox Adding a Button to the Toolbar Annotator Creating annotations Displaying annotations Implementing the widget Overview ...
... Common Pitfalls Communication between HTML and your extension Creating custom Firefox extensions with the Mozilla build system Custom about: URLs Default Preferences Deploying a Plugin as an Extension Developing add-ons Displaying web content in an extension without security issues Downloading JSON and JavaScript in extensions Enhanced Extension Installation Extension Etiquette Extension Library Extension Packaging Extension Samples Extension Theming Guidelines Extension Versioning, Update and Compatibility Extensions support in SeaMonkey 2 Firefox addons developer guide Hiding browser chrome...
New in JavaScript 1.8.5 - Archive of obsolete content
Object.freeze() Freezes an object: other code can't delete or change any properties. bug 492844 Object.isFrozen() Determines if an object was frozen. bug 492844 Array.isArray() Checks if a variable is an array. bug 510537 Date.prototype.toJSON() Returns a JSON format string for a Date object. Function.prototype.bind() Creates a new function that, when called, itself calls this function in the context provided (with a given sequence of arguments). bug 429507 New ECMAScript5 features get and set operators now allo...
...ate strings. Global objects made read only: The NaN, Infinity, and undefined global objects have been made read only, per the ECMAScript 5 specification. obj.__parent__ and obj.__count__ become obsolete. Some information about why: SpiderMonkey change du jour: the special __parent__ property has been removed bug 551529 & bug 552560. Trailing commas no longer accepted in JSON.parse(). ...
WAI-ARIA basics - Learn web development
hat updates without the entire page reloading via a mechanism like XMLHttpRequest, Fetch, or DOM APIs. These are sometimes referred to as live regions. Let's look at a quick example -- see aria-no-live.html (also see it running live). In this example we have a simple random quote box: <section> <h1>Random quote</h1> <blockquote> <p></p> </blockquote> </section> Our JavaScript loads a JSON file via XMLHttpRequest containing a series of random quotes and their authors. Once that is done, we start up a setInterval() loop that loads a new random quote into the quote box every 10 seconds: let intervalID = window.setInterval(showQuote, 10000); This works OK, but it is not good for accessibility -- the content update is not detected by screenreaders, so their users would not know what ...
...s to an element causes screenreaders to read out the content that is updated. How urgently the content is read out depends on the attribute value: off: The default. Updates should not be announced. polite: Updates should be announced only if the user is idle. assertive: Updates should be announced to the user as soon as possible. We'd like you to take a copy of aria-no-live.html and quotes.json, and update your <section> tag as follows: <section aria-live="assertive"> This will cause a screenreader to read out the content as it is updated. Note: Most browsers will throw a security exception if you try to do an XMLHttpRequest call from a file:// URL, e.g. if you just load the file by loading it directly into the browser (via double clicking, etc.). To get it to run, you will need to ...
Sending forms through JavaScript - Learn web development
parts of the UI that require changes. Sending arbitrary data asynchronously is generally called AJAX, which stands for "Asynchronous JavaScript And XML". How is it different? The XMLHttpRequest (XHR) DOM object can build HTTP requests, send them, and retrieve their results. Historically, XMLHttpRequest was designed to fetch and send XML as an exchange format, which has since been superceded by JSON. But neither XML nor JSON fit into form data request encoding. Form data (application/x-www-form-urlencoded) is made of URL-encoded lists of key/value pairs. For transmitting binary data, the HTTP request is reshaped into multipart/form-data. Note: The Fetch API is often used in place of XHR these days -- it is a modern, updated version of XHR, which works in a similar fashion but has some adva...
...rm-data. Note: The Fetch API is often used in place of XHR these days -- it is a modern, updated version of XHR, which works in a similar fashion but has some advantages. Most of the XHR code you'll see in this article could be swapped out for Fetch. If you control the front-end (the code that's executed in the browser) and the back-end (the code which is executed on the server), you can send JSON/XML and process them however you want. But if you want to use a third party service, you need to send the data in the format the services require. So how should we send such data? The different techniques you'll require are done below. Sending form data There are 3 ways to send form data: Building an XMLHttpRequest manually. Using a standalone FormData object. Using FormData bound to a <...
Introducing asynchronous JavaScript - Learn web development
oading the resource (using the onload event handler) before it passes it to the callback. Callbacks are versatile -- not only do they allow you to control the order in which functions are run and what data is passed between them, they also allow you to pass data to different functions depending on circumstance. So you could have different actions to run on the response downloaded, such as processJSON(), displayText(), etc. Note that not all callbacks are async -- some run synchronously. An example is when we use Array.prototype.forEach() to loop through the items in an array (see it live, and the source): const gods = ['Apollo', 'Artemis', 'Ares', 'Zeus']; gods.forEach(function (eachName, index){ console.log(index + '. ' + eachName); }); In this example we loop through an array of Greek...
...e to the array name and index values. However, it doesn't wait for anything -- it runs immediately. Promises Promises are the new style of async code that you'll see used in modern Web APIs. A good example is the fetch() API, which is basically like a modern, more efficient version of XMLHttpRequest. Let's look at a quick example, from our Fetching data from the server article: fetch('products.json').then(function(response) { return response.json(); }).then(function(json) { products = json; initialize(); }).catch(function(err) { console.log('Fetch problem: ' + err.message); }); Note: You can find the finished version on GitHub (see the source here, and also see it running live). Here we see fetch() taking a single parameter -- the URL of a resource you want to fetch from the net...
Introduction to web APIs - Learn web development
n HTTP request to the server to retrieve a new resource of some kind) has a number of events available on them, for example, the load event is fired when a response has been successfully returned containing the requested resource, and it is now available. The following code provides a simple example of how this would be used: let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new XMLHttpRequest(); request.open('GET', requestURL); request.responseType = 'json'; request.send(); request.onload = function() { const superHeroes = request.response; populateHeader(superHeroes); showHeroes(superHeroes); } Note: You can see this code in action in our ajax.html example (see it live also). The first five lines specify the location of t...
...Header(superHeroes); showHeroes(superHeroes); } Note: You can see this code in action in our ajax.html example (see it live also). The first five lines specify the location of the resource we want to fetch, create a new instance of a request object using the XMLHttpRequest() constructor, open an HTTP GET request to retrieve the specified resource, specify that the response should be sent in JSON format, then send the request. The onload handler function then specifies what we do with the response. We know the response will be successfully returned and available after the load event has fired (unless an error occurred), so we save the response containing the returned JSON in the superHeroes variable, then pass it to two different functions for further processing. They have additional se...
Solve common problems in your JavaScript code - Learn web development
ect must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. ...
...es, and how do you use them? Objects How do you create an object? What is dot notation? What is bracket notation? How do you get and set the methods and properties of an object? What is this, in the context of an object? What is object-oriented programming? What are constructors and instances, and how do you create them? What different ways are there to create objects in JavaScript? JSON How do you structure JSON data, and read it from JavaScript? How can you load a JSON file into a page? How do you convert a JSON object to a text string, and back again? Events What are event handlers and how do you use them? What are inline event handlers? What does the addEventListener() function do, and how do you use it? Which mechanism should I use to add event code to my web ...
Getting started with Vue - Learn web development
d. Next you are asked to configure what kind of automated linting we want. Select "Lint on save". This will check for errors when we save a file inside the project. Hit Enter to continue. Now, you will select how we want your config files to be managed. "In dedicated config files" will put your config settings for things like ESLint into their own, dedicated files. The other option, "In package.json", will put all of your config settings into the app's package.json file. Select "In dedicated config files" and push Enter. Finally, you are asked if you want to save this as a preset for future options. This is entirely up to you. If you like these settings over the existing presets and want to use them again, type y , otherwise type n. The CLI will now begin scaffolding out your project, and...
...he contents can be processed by Webpack at build time. For example, <style lang="scss"> will allow you to use SCSS syntax in your styling information. Running the app locally The Vue CLI comes with a built-in development server. This allows you to run your app locally so you can test it easily without needing to configure a server yourself. The CLI adds a serve command to the project's package.json file as an npm script, so you can easily run it. In your terminal, try running npm run serve (or yarn serve if you prefer yarn). Your terminal should output something like the following: INFO Starting development server... 98% after emitting CopyPlugin DONE Compiled successfully in 18121ms App running at: - Local: <http://localhost:8080/> - Network: <http://192.168.1.9:8080/> No...
HTMLIFrameElement.getStructuredData()
n production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getStructuredData() method of the HTMLIFrameElement interface retrieves any structured microdata (and hCard and hCalendar microformat data) contained in the HTML loaded in the browser <iframe> and returns it as JSON. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getStructuredData(); Returns A DOMRequest to handle the getStructuredData() request's success and error cases. If the request is successful, the request.result is a JSON object representation of all microdata contained on the page loaded in the browser. Parameters None. Examples var browser = document.querySelector('iframe'); ...
... Specification Not part of any specification. ...
Browser API
, and dispatchEvent(). HTMLIFrameElement.sendMouseEvent() Sends a MouseEvent to the <iframe>'s content. Utility methods Last, there are some utility methods, useful for apps that host a browser <iframe>. HTMLIFrameElement.getStructuredData() Retrieves any structured microdata (and hCard and hCalendar microformat data) contained in the HTML loaded in the browser <iframe> and returns it as JSON. Browser API methods removed in Firefox 65 In Firefox 65, several of the Mozilla Browser API methods were removed in an effort to cut down on DOMRequest usage in the browser, and remove the parts of the Browser API that are no longer needed (it is used only by the Firefox DevTools at this point). See bug 1503070 for more details. The methods removed in Firefox 65 are: HTMLIFrameElement.add...
...ive to the caret position will be highlighted. HTMLIFrameElement.findNext() Highlights the next or previous instance of a search result after a findAll() search has been carried out. HTMLIFrameElement.getContentDimensions() Retrieves the X and Y dimensions of the content window. HTMLIFrameElement.getManifest() Retrieves the manifest of an app loaded in the browser <iframe> and returns it as JSON. HTMLIFrameElement.getScreenshot() Takes a screenshot of the browser <iframe>'s content. This is particularly useful to get thumbnails of tabs in a tabbed browser app. HTMLIFrameElement.purgeHistory() Clears all the resources (cookies, localStorage, cache, etc.) associated with the browser <iframe>. HTMLIFrameElement.sendTouchEvent() Sends a TouchEvent to the <iframe>'s content. Note that t...
Profiling with the Firefox Profiler
have to set this environment values by --es option of am command to launch Firefox. This example is for Firefox Nightly (package name is org.mozilla.fennec_aurora), and you have to allow storage access on permission settings before launching it. adb shell am start -n org.mozilla.fennec_aurora/.App \ --es env0 MOZ_PROFILER_STARTUP=1 \ --es env1 MOZ_PROFILER_SHUTDOWN=/sdcard/Download/profiler.json Then, if you select Quit menu, you can collect profiling data to MOZ_PROFILER_SHUTDOWN file. Profiling JS benchmark (xpcshell) To profile the script run.js with IonMonkey (-I), type inference (-n) and JaegerMonkey (-m). Thgis requires the following command: $ xpcshell -m -I -n -e ' const Ci = Components.interfaces; const Cc = Components.classes; var profiler = Cc["@mozilla.org/tool...
...ts.interfaces; const Cc = Components.classes; var profiler = Cc["@mozilla.org/tools/profiler;1"].getService(Ci.nsIProfiler); profiler.StartProfiler( 10000000 /* = profiler memory */, 1 /* = sample rate: 100us with patch, 1ms without */, ["stackwalk", "js"], 2 /* = features, and number of features. */ ); ' -f ./run.js -e ' var profileObj = profiler.getProfileData(); print(JSON.stringify(profileObj)); ' | tail -n 1 > run.cleo The xpcshell output all benchmark information and on its last line it output the result of the profiling, you can filter it with tail -n 1 and redirect it to a file to prevent printing it in your shell. The expected size of the output is around 100 of MB. To add symbols to your build, you need to call ./scripts/profile-symbolicate.py availabl...
about:memory
of interest (e.g. once Firefox's memory usage has gotten high) open a new tab and type "about:memory" into the address bar and hit "Enter". If you are using a communication channel where files can be sent, such as Bugzilla or email, click on the "Measure and save..." button. This will open a file dialog that lets you save the memory reports to a file of your choosing. (The filename will have a .json.gz suffix.) You can then attach or upload the file appropriately. The recipients will be able to view the contents of this file within about:memory in their own Firefox instance. If you are using a communication channel where only text can be sent, such as a comment thread on a website, click on the "Measure..." button. This will cause a tree-like structure to be generated text within about:memo...
...ge. Loading memory reports from file The easiest way to load memory reports from file is to use the "Load..." button. You can also use the "Load and diff..." button to get the difference between two memory report files. Single memory report files can also be loaded automatically when about:memory is loaded by appending a file query string, for example: about:memory?file=/home/username/reports.json.gz This is most useful when loading memory reports files obtained from a Firefox OS device. Memory reports are saved to file as gzipped JSON. These files can be loaded as is, but they can also be loaded after unzipping. Interpreting memory reports Almost everything you see in about:memory has an explanatory tool-tip. Hover over any button to see a description of what it does. Hover over any ...
L20n HTML Bindings
n a repository with L20n optimized for production use: one file (~110KB) one file, minified (~35KB) It's recommended to include the l20n.js file as the last script in the head element. <head> ... <script src="l20n.js"></script> </head> Create Manifest Use a localization manifest to define available languages and their resource files. <link rel="localization" href="../locales/manifest.json"> An example of the manifest file (all keys are required): { "locales": [ "en-US", "pl"], "default_locale": "en-US", "resources": [ "../locales/{{locale}}/strings.l20n", "/shared/{{locale}}/date.l20n"? ] } Make HTML Elements Localizable Use the data-l10n-id attribute on an HTML element to mark it as localizable. <p data-l10n-id="about"></p> Notice that you don't have to p...
...calized, the document element will fire a DocumentLocalized event, which you can listen to: document.addEventListener('DocumentLocalized', function() { // the DOM has been localized and the user sees it in their language YourApp.init(); }); Exposing Context Data You can expose important bits of data to the localization context in form of context data. <script type="application/l10n-data+json"> { "newNotifications": 3, "user": { "name": "Jane", "gender": "feminine" } } </script> This data will be available context-wide to all localized strings. For instance, a string could use the information about the user's gender to provide two variants of the translation, like in the example below. See L20n by Example to learn more about L20n's syntax. <invited[$user.gender] { f...
SpiderMonkey Build Documentation
elp debug memory leaks and other memory-related problems. See JS_SetGCZeal() for details. ...
...s one of the above-created build directories): /bin/sh ../configure.in --help Generating a Compilation Database Some tools (like IDEs, static analyzers and refactoring tools) consume a file called compile_commands.json which contains a description of all the pieces required to build a piece of software so that tools don't have to also understand a build system. To generate a compile_commands.json with the SpiderMonkey configure script, enable the CompileDB backend, like this: /bin/sh ../configure.in <options> --enable-build-backends=CompileDB,RecursiveMake (RecursiveMake is there as you'd likely also want to be able to build!) Windows Builds Since version 28, threadsafe builds are the default, and should work out of the box on all POSIX platforms. Hence, the following instructions s...
Creating JavaScript jstest reftests
e for ECMAScript implementations. Before using Test262, SpiderMonkey had a fair number of internal tests of conformance to ECMAScript, and many of those tests remain in the js/src/non262 directory as regressions. test262 tests Test262 is the implementation conformance test suite for the latest drafts of ECMAScript Language Specification, as well as Internationalization API Specification and The JSON Data Interchange Format. It is maintained by TC39, the ECMAScript Standard's technical committee. Mozilla manually imports these tests into the js/src/tests/test262 directory. You should contribute directly to Test262 in the following scenarios: You are writing tests for the implementation of a new feature or feature proposal for ECMAScript. If tests for the new feature proposal do not...
...directly to Test262 in the following scenarios: You are writing tests for the implementation of a new feature or feature proposal for ECMAScript. If tests for the new feature proposal do not yet exist in Test262 (they might!), contributing to Test262 will allow all other JavaScript implementors to use your tests as well. You would like to contribute tests of an ECMAScript, Intl or JSON feature insufficiently covered by Test262. At the time of this writing, Mozilla imports Test262 tests in to the directory js/src/tests/test262. When importing Test262, the test file's in-file metadata is translated from Test262 format to a format readibly by the jstest harness. If you are contributing directly to Test262, you must submit the tests in the Test262 format, which you can see in th...
Web Replay
s are used for when messages may be sent between the middleman and child process, ensuring that the middleman process cannot send a message at a time when the child process may be rewinding. Debugger integration When debugging a normal content process, the devtools JS debugger runs quite a bit of JS code in the content process, communicating with the chrome process primarily through streams of JSON data. When debugging a child content process, this JS code runs in the middleman process. When the code creates a Debugger object, that Debugger provides information about the child process rather than the current (middleman) process. While the Debugger can indicate it is for a child process, the interface should be as transparent as possible to the devtools JS code; the Debugger can still cre...
...replaying process pauses. Inspecting a replaying process Access to JS objects in the replaying process is currently only done through the JS Debugger interface -- Debugger.Object, Debugger.Frame.eval, and so forth. This interface overlays a separate implementation from the C++ Debugger, implemented in devtools/server/actors/replay/debugger.js. This communicates with the replaying process via JSON and is fairly easy to extend for new features (such as web console support). Appendix: Impacts on Gecko development Web Replay is designed to minimize the places where other parts of Gecko need to know about it or interact with it. There are, however, areas where Gecko development is impacted by Replay. This section describes the main areas where ongoing development can break Replay and cause...
nsIDOMWindowUtils
long getPCCountScriptCount(); Parameters None. getPCCountScriptSummary() Returns a summary of the profile information for a script. This should be used after a call to stopPCCountProfiling(). AString getPCCountScriptSummary(in long aScript); Parameters aScript Index of the profiled script to get the profile summary for. Should be less than getPCCountScriptCount(). Return value A JSON string summarizing the information profiled about the script. This includes counts for how often and in what ways the script executed. The structure of the JSON is unspecified and may vary between versions of Firefox. getPCCountScriptContents() Returns detailed information about the profile information for a script. This should be used after a call to stopPCCountProfiling(). AString getPC...
...vary between versions of Firefox. getPCCountScriptContents() Returns detailed information about the profile information for a script. This should be used after a call to stopPCCountProfiling(). AString getPCCountScriptContents(in long script); Parameters aScript Index of the profiled script to get the profile contents for. Should be less than getPCCountScriptCount(). Return value A JSON string with all profile information accumulated for the script. This includes the text of the script and details about its internal representation in SpiderMonkey, and counts for how often and in what ways each operation in the script executed. The structure of the JSON is unspecified and may vary between versions of Firefox. getScrollXY() Returns the scroll position of the window's currently...
nsIFrameMessageManager
ved in Firefox 17. You should use nsIMessageListenerManager or nsIMessageSender instead. Method overview void addMessageListener(in AString aMessage, in nsIFrameMessageListener aListener, [optional] in boolean listenWhenClosed); void removeMessageListener(in AString aMessage, in nsIFrameMessageListener aListener); void sendAsyncMessage(in AString aMessage, in AString json); Methods addMessageListener() Adds a message listener to the local frame. This listener will receive messages sent from the remote frame. void addMessageListener( in AString aMessage, in nsIFrameMessageListener aListener [optional in boolean listenWhenClosed ); Parameters aMessage The name of the message for which to add a listener. aListener An object implementing nsIFra...
...er(). void removeMessageListener( in AString aMessage, in nsIFrameMessageListener aListener ); Parameters aMessage The name of the message for which to remove a listener. aListener An object implementing nsIFrameMessageListener to stop receiving messages. sendAsyncMessage() Asynchronously sends a message to the listeners. void sendAsyncMessage( in AString aMessage, in AString json ); Parameters aMessage The name of the message to send to the listeners. json Optional A JSON object containing data to be delivered to the listeners. See also Content process event handling nsIFrameMessageListener nsISyncMessageSender ...
nsIJetpack
riant createHandle(); void destroy(); Methods sendMessage() This method asynchronously sends a message to the Jetpack process. void sendMessage( in AString aMessageName, [optional] in jsval v1, Optional [optional] in jsval v2, Optional ... ); Parameters aMessageName The name of the message to send. v1, v2, ... Optional JavaScript values to send with the message; they must be either JSON-serializable types or handles. registerReceiver() This registers a callback to be triggered whenever the Jetpack process sends a particular message. Note: Multiple callbacks may be registered for the same message; they will all be triggered. void registerReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageName The name of the message from the Jetpack process on whic...
...e callbacks may be registered for the same message; they will all be triggered. void registerReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageName The name of the message from the Jetpack process on which the callback is triggered. aReceiver A JavaScript function. The first argument passed to it is the name of the message, and all arguments following it are either JSON-serializable types or handles. If the message was sent synchronously from the Jetpack process via callMessage(), then the return value of this function is passed back to the Jetpack process. unregisterReceiver() This unregisters a callback previously registered with registerReceiver() void unregisterReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageName The name o...
nsIMessageListener
s the XUL <browser> element for the frame from which the message was sent. name The message name. This is the first argument passed into the message-sending function. sync True if the message was sent using sendSyncMessage, false otherwise. data A structured clone of the message payload: the second argument passed into the message-sending function. json Same as data. Deprecated. objects An object whose properties are any cross process object wrappers exposed by the sender as the third argument to the message-sending function. principal Principal for the window app. Each listener is invoked with its own copy of the message parameter. When the listener is called, 'this' value is the target of the message. If the...
...properties are any cross process object wrappers exposed by the sender as the third argument to the message-sending function. principal Principal for the window app. Each listener is invoked with its own copy of the message parameter. When the listener is called, 'this' value is the target of the message. If the message is synchronous, the possible return value is returned as JSON (will be changed to use structured clones). When there are multiple listeners to synchronous messages, each listener's return value is sent back as an element in an array. undefined return values show up as undefined values in the array. ...
Index - Firefox Developer Tools
The Eyedropper tool enables you to select colors in the current page. It works like a magnifying glass over the page, enabling you to select with pixel precision. Underneath the magnifying glass it shows the color value for the current pixel using whichever scheme you've selected in Settings > Inspector > Default color unit: 34 Index Tools Found 158 pages: 35 JSON viewer Firefox includes a JSON viewer. If you open a JSON file in the browser, or view a remote URL with the Content-Type set to application/json, it is parsed and given syntax highlighting. Arrays and objects are shown collapsed, and you can expand them using the "+" icons. 36 Measure a portion of the page Design, DevTools, Developer, Firefox, Layout, Measure, Measuring...
...ebugging, Tools, breakpoint, events Starting with Firefox 69, debugging an application that includes event handlers is simplified because the debugger now includes the ability to automatically break when the code hits an event handler. This article explains how to use it. 137 Source map errors Debugger, Debugging, Dev Tools, Reference, Source maps, Tools Source maps are JSON files providing a way to associate transformed sources, as seen by the browser, with their original sources, as written by the developer. You can sometimes encounter problems working with source maps. This page explains the most common problems and how to fix them. 138 UI Tour This article is a quick tour of the main sections of the JavaScript Debugger's user interface. The...
about:debugging (before Firefox 68) - Firefox Developer Tools
changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. If you change files that stay loaded the whole time, like background scripts, then you can pick up changes you've made by disabling and then re-enabling the add-on in the about:addons page. If you change files that are only parsed at install time, like the manifest.json file, you'll need to restart Firefox, then load the add-on again. Note that before Firefox 48, loading the add-on again by pressing "Load Temporary Add-on" without restarting Firefox does not work. Firefox 48 onwards From Firefox 48 onwards: as before: if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and ...
...aded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. there's a better way to handle the other cases: click the "Reload" button next to the "Debug" button. This does what it says: reloading any persistent scripts, 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 curre...
AuthenticatorAssertionResponse.signature - Web APIs
This signature will be sent to the server for control, as part of the response. It provides the proof that an authenticator does possess the private key which was used for the credential's generation. ...
... available in an <iframe> for example. Syntax signature = authenticatorAssertionResponse.signature Value An ArrayBuffer object which the signature of the authenticator (using its private key) for both AuthenticatorAssertionResponse.authenticatorData and a SHA-256 hash given by the client for its data (the challenge, the origin, etc. and available from AuthenticatorAssertionResponse.clientDataJSON). Examples var options = { challenge: new Uint8Array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionPKCred) { var signature = assertionPKCred.response.signature; // Send response and client extensions to the server so that it can // go on with the authentication...
AuthenticatorAssertionResponse - Web APIs
ontainer.get() when a PublicKeyCredential is passed, and provides proof to a service that it has a key pair and that the authentication request is valid and approved. This interface inherites from AuthenticatorResponse. Note: This interface is restricted to top-level contexts. Use from within an <iframe> element will not have any effect. Properties AuthenticatorAssertionResponse.clientDataJSON Secure contextRead only The client data for the authentication, such as origin and challenge. The clientDataJSON property is inherited from the AuthenticatorResponse. AuthenticatorAssertionResponse.authenticatorData Secure contextRead only An ArrayBuffer containing information from the authenticator such as the Relying Party ID Hash (rpIdHash), a signature counter, test of user presence and ...
...fer containing information from the authenticator such as the Relying Party ID Hash (rpIdHash), a signature counter, test of user presence and user verification flags, and any extensions processed by the authenticator. AuthenticatorAssertionResponse.signature Secure contextRead only An assertion signature over AuthenticatorAssertionResponse.authenticatorData and AuthenticatorResponse.clientDataJSON. The assertion signature is created with the private key of keypair that was created during the navigator.credentials.create() call and verified using the public key of that same keypair. AuthenticatorAssertionResponse.userHandle Secure contextRead only An ArrayBuffer containing an opaque user identifier. Methods None. Examples var options = { challenge: new Uint8Array([/* bytes sent fr...
CacheStorage - Web APIs
ery/myLittleVader.jpg'); }); } })); }); This snippet shows how the API can be used outside of a service worker context, and uses the await operator for much more readable code. // Try to get data from the cache, but fall back to fetching it live. ...
...tCachedData( cacheName, url ); await deleteOldCaches( cacheName ); return cachedData; } // Get data from the cache. async function getCachedData( cacheName, url ) { const cacheStorage = await caches.open( cacheName ); const cachedResponse = await cacheStorage.match( url ); if ( ! cachedResponse || ! cachedResponse.ok ) { return false; } return await cachedResponse.json(); } // Delete any old caches to respect user's disk space. async function deleteOldCaches( currentCache ) { const keys = await caches.keys(); for ( const key of keys ) { const isOurCache = 'myapp-' === key.substr( 0, 6 ); if ( currentCache === key || ! isOurCache ) { continue; } caches.delete( key ); } } try { const data = await getData(); con...
DOMPointInit.w - Web APIs
Web › API › DOMPointInit › w
Syntax var DOMPointInit = { w: wPerspective }; DOMPointInit.w = wPerspective; var wPerspective = DOMPointInit.w; Value A double-precision floating-point value indicating the point's w perspective value. This value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be NaN or +-Infinity). ...
...(that is, its value may be NaN or +-Infinity). There are two methods which use DOMPointInit: The static function DOMPointReadOnly.fromPoint() takes an object that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint(). The DOMPointReadOnly.toJSON() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as DOMPoint.toJSON(). This value is assumed to be 1 by default if not included in the DOMPointInit object passed into fromPoint(). Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'w' in...
DOMPointInit.y - Web APIs
Web › API › DOMPointInit › y
In general, the value of y increases to the right and decreases to the left, becoming negative to the left of the origin. This may change if transforms have been applied causing the axes' orientation to change. Syntax var DOMPointInit = { y: yPos }; DOMPointInit.y = yPos; var yPos = DOMPointInit.y; Value A double-precision floating-point value indicating the point's y-coordinate. ...
...nt(), the value is assumed to be 0 by default. There are two methods which use DOMPointInit: The static function DOMPointReadOnly.fromPoint() takes an object that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint(). The DOMPointReadOnly.toJSON() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as DOMPoint.toJSON(). Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'y' in that specification. Candidate Recommendation Initial definition ...
DOMPointInit.z - Web APIs
Web › API › DOMPointInit › z
Typically, a z value of 0 represents the plane of the screen. As the value increases, the point moves outward from the screen toward the user. As the value decreases, the point moves farther from the user, with negative values being behind the screen, receding into the distance. Of course, if transforms have been applied, the axes may have changed orientation. ...
...(that is, its value may be NaN or +-Infinity). There are two methods which use DOMPointInit: The static function DOMPointReadOnly.fromPoint() takes an object that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint(). The DOMPointReadOnly.toJSON() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as DOMPoint.toJSON(). If this property is missing when the DOMPointInit object is passed into fromPoint(), the value is assumed to be 0 by default. Specifications Specification Status Comment Geometry Interfaces Module Level 1The def...
FileSystemEntry.fullPath - Web APIs
the file represented by the entry. This can also be thought of as a path which is relative to the root directory, with a "/" prepended to it to make it absolute. Syntax var fullPath = FileSystemEntry.fullPath; Value A USVString indicating the entry's full path. ...
...directory, with a "/" prepended to it to make it absolute. Syntax var fullPath = FileSystemEntry.fullPath; Value A USVString indicating the entry's full path. Example This example shows a function which is called with a file system; it then gets a FileSystemFileEntry for a file named data.json and returns its full path. function gotFileSystem(fs) { let path = ""; fs.root.getFile("data.json", { create: true, exclusive: true }, function(entry) { path = fullPath; }, handleError(error)); return path; } Obviously, this is somewhat contrived, since we know that the file's full path is "/data.json", having just looked it up ourselves, but the concept holds up for scenarios in which you don't know it. Specifications Specification Status Comment File...
Working with the History API - Web APIs
relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL. Note: In Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) through Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the passed object is serialized using JSON. Starting in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed. In a sense, calling pushState() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document. But pushState() has...
...this doesn't prevent the creation of a new entry in the global browser history. replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action. Note: In Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) through Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the passed object is serialized using JSON. Starting in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed. Example of replaceState() method Suppose http://mozilla.org/foo.html executes the following JavaScript: let stateObj = { foo: "bar" } history.pushState(stateObj, "page 2", "bar.html") The explanation...
PaymentRequest.PaymentRequest() - Web APIs
ons of the spec, this was a sequence of identifiers for payment methods that the merchant website accepts. Starting with more recent browsers, this parameter is more generic than credit cards, it is a single DOMString, and the meaning of the data parameter changes with the supportedMethods. For example, the basic card payment method is selected by specifying the string basic-card here. data A JSON-serializable object that provides optional information that might be needed by the supported payment methods. This has to conform to the type expected by the payment handler indicated by supportedMethods. For basic credit card services, this structure should match the BasicCardRequest dictionary. details Provides information about the requested transaction. This parameter contains the follo...
...ifiers for specific payment methods; for example, adjusting the total amount based on the payment method. This parameter contains the following fields: additionalDisplayItems An array of items to be appended to the details.displayItems property. This property is commonly used to add a discount or surcharge line item indicating the different amount in details.modifiers.total. data A JSON-serializable object that provides optional information that might be needed by the supported payment methods. This has to conform to the structure defined in the BasicCardRequest dictionary. total A total amount for the payment request that overrides value in details.total. This is typically used when details.modifiers.additionalItems adds a discount or a surchase to the request. ...
Performance - Web APIs
nce entry buffer between two specified marks (known as the start mark and end mark, respectively). Performance.now() Returns a DOMHighResTimeStamp representing the number of milliseconds elapsed since a reference instant. Performance.setResourceTimingBufferSize() Sets the browser's resource timing buffer size to the specified number of "resource" type performance entry objects. Performance.toJSON() Is a jsonizer returning a json object representing the Performance object. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. resourcetimingbufferfull Fired when the browser's resource timing buffer is full. Also available via the onresourcetimingbufferfull property. Specifications Specific...
...ng an event listener to the oneventname property of this interface. resourcetimingbufferfull Fired when the browser's resource timing buffer is full. Also available via the onresourcetimingbufferfull property. Specifications Specification Status Comment High Resolution Time Level 2The definition of 'Performance' in that specification. Recommendation Defines toJson() method. High Resolution TimeThe definition of 'Performance' in that specification. Recommendation Defines now() method. Performance Timeline Level 2The definition of 'Performance extensions' in that specification. Candidate Recommendation Changes getEntries() interface. Performance TimelineThe definition of 'Performance extensions' in that specification. ...
PerformanceEntry.duration - Web APIs
performance.mark("Begin"); do_work(50000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.getEntries(); for (var i=0; i < p.length; i++) { log("Entry[" + i + "]"); check_PerformanceEntry(p[i]); } } function check_PerformanceEntry(obj) { var properties = ["name", "entryType", "startTime", "duration"]; var methods = ["toJSON"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in obj; if (supported) log("..." + properties[i] + " = " + obj[properties[i]]); else log("..." + properties[i] + " = Not supported"); } for (var i=0; i < methods.length; i++) { // check each method var supported = typeof obj[methods[i]] == "function"; ...
... Candidate Recommendation Performance TimelineThe definition of 'duration' in that specification. Recommendation Initial definition. ...
PerformanceEntry.name - Web APIs
performance.mark("Begin"); do_work(50000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.getEntries(); for (var i=0; i < p.length; i++) { log("Entry[" + i + "]"); check_PerformanceEntry(p[i]); } } function check_PerformanceEntry(obj) { var properties = ["name", "entryType", "startTime", "duration"]; var methods = ["toJSON"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in obj; if (supported) log("..." + properties[i] + " = " + obj[properties[i]]); else log("..." + properties[i] + " = Not supported"); } for (var i=0; i < methods.length; i++) { // check each method var supported = typeof obj[methods[i]] == "function"; ...
... Candidate Recommendation Performance TimelineThe definition of 'name' in that specification. Recommendation Initial definition. ...
PerformanceEntry.startTime - Web APIs
performance.mark("Begin"); do_work(50000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.getEntries(); for (var i=0; i < p.length; i++) { log("Entry[" + i + "]"); check_PerformanceEntry(p[i]); } } function check_PerformanceEntry(obj) { var properties = ["name", "entryType", "startTime", "duration"]; var methods = ["toJSON"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in obj; if (supported) log("..." + properties[i] + " = " + obj[properties[i]]); else log("..." + properties[i] + " = Not supported"); } for (var i=0; i < methods.length; i++) { // check each method var supported = typeof obj[methods[i]] == "function"; ...
... Candidate Recommendation Performance TimelineThe definition of 'startTime' in that specification. Recommendation Initial definition...
PerformanceEntry - Web APIs
tring representing the type of performance metric such as, for example, "mark". See property page for valid values. PerformanceEntry.startTime Read only A DOMHighResTimeStamp representing the starting time for the performance metric. PerformanceEntry.duration Read only A DOMHighResTimeStamp representing the time value of the duration of the performance event. Methods PerformanceEntry.toJSON() Returns a JSON representation of the PerformanceEntry object. Example The following example checks all PerformanceEntry properties to see if the browser supports them and if so, write their values to the console. function print_PerformanceEntries() { // Use getEntries() to get a list of all performance entries var p = performance.getEntries(); for (var i=0; i < p.length; i++) { c...
... User Timing Recommendation Adds the PerformanceMark and PerformanceMeasure interfaces as well as the mark and measure values for entryType. Frame Timing Draft Adds the PerformanceFrameTiming interface and the frame value for entryType. Performance Timeline Level 2The definition of 'PerformanceEntry' in that specification. Candidate Recommendation Added toJSON() serializer method. Performance TimelineThe definition of 'PerformanceEntry' in that specification. Recommendation Initial definition. ...
PerformanceEventTiming - Web APIs
manceEventTiming.processingStart Returns the time at which event dispatch started. PerformanceEventTiming.processingEnd Returns the time at which the event dispatch ended. PerformanceEventTiming.cancelable Returns the associated event's cancelable attribute. PerformanceEventTiming.target Returns the associated event's last target, if it is not removed. Methods PerformanceEventTiming.toJSON() Converts the PerformanceEventTiming object to JSON. Examples The following example shows how to use the API for all events: const observer = new PerformanceObserver(function(list) { const perfEntries = list.getEntries().forEach(entry => { // Full duration const inputDuration = entry.duration; // Input delay (before processing event) const inputDelay = en...
...s code runs. let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; document.addEventListener('visibilitychange', (event) => { firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp); }, {once: true}); // Sends the passed data to an analytics endpoint. This code // uses `/analytics`; you can replace it with your own URL. function sendToAnalytics(data) { const body = JSON.stringify(data); // Use `navigator.sendBeacon()` if available, falling back to `fetch()`. (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) || fetch('/analytics', {body, method: 'POST', keepalive: true}); } // Use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option. // https://bugs.webkit.org/sho...
PushMessageData - Web APIs
e times. Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the PushMessageData interface. Properties None. Methods PushMessageData.arrayBuffer() Extracts the data as an ArrayBuffer object. PushMessageData.blob() Extracts the data as a Blob object. ...
...ough the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the PushMessageData interface. Properties None. Methods PushMessageData.arrayBuffer() Extracts the data as an ArrayBuffer object. PushMessageData.blob() Extracts the data as a Blob object. PushMessageData.json() Extracts the data as a JSON object. PushMessageData.text() Extracts the data as a plain text string. Examples self.addEventListener('push', function(event) { var obj = event.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { fireNotification(obj, event); port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); Spe...
RTCDataChannel.send() - Web APIs
R (End of Record) flag to indicate when a received message is the last piece of a multi-part object sent using send(). For more information about message size restrictions, see Understanding message size limits in Using WebRTC data channels. ...
... Example In this example, a routine called sendMessage() is created; it accepts an object as input and sends to the remote peer, over the RTCDataChannel, a JSON string with the specified object and a time stamp. var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("BackChannel"); function sendMessage(msg) { let obj = { "message": msg, "timestamp": new Date() } dc.send(JSON.stringify(obj)); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.send()' in that specification. Candidate Recommendation Initial specification. ...
RTCIceCandidateInit.candidate - Web APIs
ring; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" Example When a new ICE candidate is received by your signaling code from the remote peer, you need to construct the RTCIceCandidate object that encapsulates it. This is done in the event handler for the icecandidate event. ...
... type = "host" Example When a new ICE candidate is received by your signaling code from the remote peer, you need to construct the RTCIceCandidate object that encapsulates it. This is done in the event handler for the icecandidate event. ...
RTCPeerConnection.addIceCandidate() - Web APIs
e candidate string are invalid or could not be parsed. Attempting to add the candidate fails for any reason. Examples This code snippet shows how to signal ICE candidates across an arbitrary signaling channel. ...
...signaling channel. ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription. self.addEventListener("pushsubscriptionchange", event => { event.waitUntil(swRegistration.pushManager.subscribe(event.oldSubscription.options) .then(subscription => { return fetch("register", { method: "post", headers: { "Content-type": "application/json" }, body: JSON.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); When a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. When the returned promise is resolved, we receive the new subscription. This is delivered to the app server using...
... You can also use the onpushsubscriptionchange event handler property to set up the event handler: self.onpushsubscriptionchange = event => { event.waitUntil(swRegistration.pushManager.subscribe(event.oldSubscription.options) .then(subscription => { /* ... ...
SubtleCrypto.wrapKey() - Web APIs
ncrypt, unwrapKey is composed of import + decrypt. Syntax const result = crypto.subtle.wrapKey( format, key, wrappingKey, wrapAlgo ); Parameters format is a string describing the data format in which the key will be exported before it is encrypted. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. jwk: JSON Web Key format. key is the CryptoKey to wrap. wrappingkey is the CryptoKey used to encrypt the exported key. The key must have the wrapKey usage set. wrapAlgo is an object specifying the algorithm to be used to encrypt the exported key, and any required extra parameters: To use RSA-OAEP, pass an RsaOaepParams object. To use AES-CTR, pass an AesCtrParams object. To use AES-CBC,...
...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 yo...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
ll WebGL to normalize the values to [0, 1]. For example, the following vertex: { "position": [1.0, 2.0, 1.5], "normal": [1.0, 0.0, 0.0], "texCoord": [0.5, 0.25] } Will be stored in the array buffer as follows: 00 00 80 3F 00 00 00 40 00 00 0C 3F 7F 00 00 00 7F FF 3F FF Creating the array buffer First, we dynamically create the array buffer from JSON data using a DataView. Note the use of true because WebGL expects our data to be in little-endian. //load geometry with fetch() and Response.json() const response = await fetch('assets/geometry.json'); const vertices = await response.json(); //Create array buffer const buffer = new ArrayBuffer(20 * vertices.length); //Fill array buffer const dv = new DataView(buffer); for (let i = 0; i < vertic...
...with Node.js. Then we could load the binary file and interpret it as an array buffer: const response = await fetch('assets/geometry.bin'); const buffer = await response.arrayBuffer(); Consume array buffer with WebGL First, we create a new Vertex Buffer Object (VBO) and supply it with our array buffer: //Bind array buffer to a Vertex Buffer O...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
If the incoming message has a description, it's either an offer or an answer sent by the other peer. If, on the other hand, the message has a candidate, it's an ICE candidate received from the remote peer as part of trickle ICE. The candidate is destined to be delivered to the local ICE layer by passing it into addIceCan...
...re handling an offer or an answer since rollback will be performed automaticaly as needed. At that point, if the received message is an offer, we use setLocalDescription() to create and set an appropriate local description, then we send it to the remote peer over the signaling server. On receiving an ICE candidate On the other hand, if the received message is an ICE candidate--indicated by the JSON object containing a candidate member--we deliver it to the local ICE layer by calling the RTCPeerConnection method addIceCandidate(). Errors are, as before, ignored if we have just discarded an offer. Explicit restartIce() method added The techniques previously used to trigger an ICE restart while handling the eventnegotiationneeded have significant flaws. These flaws have made it difficult to ...
Inputs and input sources - Web APIs
es that have been removed from the XR system. Identifying the input's profile Each input source has a profiles property, which contains a live list of the WebXR input profiles which apply to the input source, in order of specificity from most-specific to least. In order to do anything meaningful involving scanning of profiles beyond basic identification of features, you may need to import the JSON profile database from the WebXR Input Profiles Registry. See Input profiles for more specific details on working with input profiles. Choosing the primary controller In order to avoid having problems introduced by multiple controllers trying to inadvertently manipulate the UI at the same time, your app may need to have a "primary" controller. Not only would this controller then take the respon...
... a list of input profile names that correspond to a set of information describing that input source and how it can be used. Those names are found in the input source's profiles property, and the official registry of these profile strings is maintained in the WebXR Input Profiles Registry on GitHub. For example, the generic-trigger-squeeze-touchpad profile name can be used to locate the following JSON profile data by locating the profileId field that has the value generic-trigger-squeeze-touchpad. { "profileId": "generic-trigger-squeeze-touchpad", "fallbackProfileIds": [], "layouts" : { "left-right-none" : { "selectComponentId": "xr-standard-trigger", "components": { "xr-standard-trigger": { "type": "trigger" }, "xr-s...
Attestation and Assertion - Web APIs
nto the authenticator during manufacturing time and is specific to a device model. That is, all "Samsung Galaxy S8" phones, manufactured at a specific time or particular manufacturing run, have the same attestation certificate. The attestation is returned through the WebAuthn API as the AuthenticatorAttestationResponse. The attestation format contains two basic ArrayBuffers: clientDataJSON - An ArrayBuffer that contains a JSON representation of what the browser saw when being asked to authenticate. attestationObject - Cryptographic attestation that a newly generated keypair was created by that authenticator. Contains authenticator data and an attestation statement. The authenticator data contains an attestedCredentialData field. The attestedCredentialData field contains the c...
...henticator signs over it with a key pair previously registered to that service. This creates an assertion. Unlike the attestation, the format of the assertion is always the same regardless of the device being used. The assertion is returned through the WebAuthn API as the AuthenticatorAssertionResponse. The assertion format is fairly simple as it contains four basic ArrayBuffers: clientDataJSON - The same as in attestation. An ArrayBuffer that contains a JSON representation of what the browser saw when being asked to authenticate. authenticatorData - data created and/or used by the authenticator signature - a signature over the clientDataJSON and authenticatorData that can be verified with the public key that was created during registration. userHandle - Optional. (Nul...
Window: popstate event - Web APIs
ts in their URLs, send the hashchange event to the window. As you can see, the popstate event is nearly the last thing done in the process of navigating pages in this way. ...
...http://example.com/example.html?page=1, state: {"page":1}" history.back(); // Logs "location: http://example.com/example.html, state: null" history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}" The same example using the onpopstate event handler property: window.onpopstate = function(event) { console.log("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // Logs "location: http://example.com/example.html, state: null" history.go(2); // Logs "location: ht...
Window: storage event - Web APIs
has been modified in the context of another document. Bubbles No Cancelable No Interface StorageEvent Event handler property onstorage Examples Log the sampleList item to the console when the storage event fires: window.addEventListener('storage', () => { // When local storage changes, dump the list to // the console. ...
...n the storage event fires: window.addEventListener('storage', () => { // When local storage changes, dump the list to // the console. console.log(JSON.parse(window.localStorage.getItem('sampleList'))); }); The same action can be achieved using the onstorage event handler property: window.onstorage = () => { // When local storage changes, dump the list to // the console. console.log(JSON.parse(window.localStorage.getItem('sampleList'))); }; Specifications Specification Status HTML Living StandardThe definition of 'storage' in that specification. Living Standard ...
Sending and Receiving Binary Data - Web APIs
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. ...
... Receiving binary data using JavaScript typed 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 = "arraybuffe...
Ajax - Developer guides
Web › Guide › AJAX
er, including HTML or XHTML, CSS, JavaScript, DOM, XML, XSLT, and most importantly the XMLHttpRequest object. When these technologies are combined in the Ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions. Although X in Ajax stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in the Ajax model. Documentation Getting Started This article guides you through the Ajax basics and gives you two simple hands-on examples to get you started. Using the XMLHttpRequest API The XMLHttpRequest API is the core of...
...so: Using server-sent events. Pure-Ajax navigation example This article provides a working (minimalist) example of a pure-Ajax website composed only of three pages. Sending and Receiving Binary Data 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 article will show some Ajax I/O techniques. XML The Extensible Markup Language (XML) is a W3C-recommended general-purpose markup language for creating special-purpose markup languages. It is a simplified subset of SGML, capable of describing many diff...
Index - Developer guides
Web › Guide › Index
Found 43 pages: # Page Tags and summary 1 Developer guides API, Guide, Landing, Web These articles provide how-to information to help make use of specific web technologies and APIs. 2 Ajax AJAX, DOM, JSON, JavaScript, References, XMLHttpRequest Asynchronous JavaScript and XML, while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together 3 Community AJAX If you know of useful mailing lists, newsgroups, forums, or other communities related to AJAX, please link to them here. 4 Getting Started AJAX, API, Advanced, JavaScript, WebMechanics, XMLHttpRequest This article guides you through the AJAX...
...it work quickly and efficiently. This lets it work effectively both for users of powerful desktop systems as well as for handheld devices with less power. There are several tools available to check the performance of a website or blog. The most notable tools are listed below. 37 Parsing and serializing XML AJAX, Add-ons, DOM, DOM Parsing, Document, Extensions, Guide, HTMLDocument, JSON, Parsing, Parsing XML, Serializing, Serializing XML, XML, XMLDocument, XMLHttpRequest In this article, we'll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy. 38 Printing DOM, Guide, NeedsContent, NeedsRelocation, printing There may be times in which your web site or application would like to improve the user'...
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
Content categories Metadata content, Flow content, Phrasing content. Permitted content Dynamic script such as text/javascript. Tag omission None, both the starting and ending tag are mandatory. ...
...le-marked fallback scripts for non-supporting browsers. <script type="module" src="main.js"></script> <script nomodule src="fallback.js"></script> Embedding data in HTML You can also use the <script> element to embed data in HTML with server-side rendering by specifying a valid non-JavaScript MIME type in the type attribute. <!-- Generated by the server --> <script id="data" type="application/json">{"userId":1234,"userName":"John Doe","memberSince":"2000-01-01T00:00:00.000Z"}</script> <!-- Static --> <script> const userInfo = JSON.parse(document.getElementById("data").text); console.log("User information: %o", userInfo); </script> Specifications Specification Status Comments HTML Living StandardThe definition of '<script>' in that specification. Livin...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
later on. This example is trivial, as the browser probably discovers the <link rel="stylesheet"> and <script> elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. For example: Resources that are pointed to from inside CSS, like fonts or images. Resources that JavaScript can request, like JSON, imported scripts, or web workers. Larger images and video files. preload has other advantages too. Using as to specify the type of content to be preloaded allows the browser to: Prioritize resource loading more accurately. Store in the cache for future requests, reusing the resource if appropriate. Apply the correct content security policy to the resource. Set the correct Accept request...
...at types of content can be preloaded? Many different content types can be preloaded. The possible as attribute values are: audio: Audio file, as typically used in <audio>. document: An HTML document intended to be embedded by a <frame> or <iframe>. embed: A resource to be embedded inside an <embed> element. fetch: Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer or JSON file. font: Font file. image: Image file. object: A resource to be embedded inside an <object> element. script: JavaScript file. style: CSS stylesheet. track: WebVTT file. worker: A JavaScript web worker or shared worker. video: Video file, as typically used in <video>. Note: There's more detail about these values and the web features they expect to be consumed by in the Preload spec -...
Accept-Patch - HTTP
re 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. ...
...ng problems. ...
Content-Security-Policy-Report-Only - HTTP
For more information, see also this article on Content Security Policy (CSP). Header type Response header Forbidden header name no This header is not supported inside a <meta> element. ...
...nt-Security-Policy header. Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-endpoint/ If you still want to receive reporting, but also want to enforce a policy, use the Content-Security-Policy header with the report-uri directive. Content-Security-Policy: default-src https:; report-uri /csp-violation-report-endpoint/ Violation report syntax The report JSON object contains the following data: blocked-uri The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port. disposition Either "enforce" or "report" depending on whether the Content-Security-Policy header or the Content-...
Index - HTTP
Web › HTTP › Headers › Index
single r as this was a typo in the original spec) for links away from a page. This API is deprecated and removed from browsers. 44 CSP: report-uri CSP, Directive, HTTP, Reference, Security The deprecated HTTP Content-Security-Policy (CSP) report-uri directive instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. 45 CSP: require-sri-for CSP, Directive, HTTP, Reference, Security The HTTP Content-Security-Policy require-sri-for directive instructs the client to require the use of Subresource Integrity for scripts or styles on the page. 46 CSP: sandbox CSP, Directive, HTTP, Security The HTTP Content-Securi...
...To HTTP response header field instructs the user agent to store reporting endpoints for an origin. 52 Content-Security-Policy-Report-Only CSP, HTTP, HTTPS, Reference, Security, header The HTTP Content-Security-Policy-Report-Only response header allows web developers to experiment with policies by monitoring (but not enforcing) their effects. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. 53 Content-Type Content-Type, HTTP, Reference, Request header, header The Content-Type entity header is used to indicate the media type of the resource. 54 Cookie Cookies, HTTP, Reference, header, request The Cookie HTTP request header contains stored HTTP cookies previously sent by the server ...
Network Error Logging - HTTP
s a mechanism that can be configured via the NEL HTTP response header. This experimental header allows web sites and applications to opt-in to receive reports about failed (and, if desired, successful) network fetches from supporting browsers. Reports are sent to a reporting group defined within a Report-To header. Usage Web applications opt in to this behaviour with the NEL header, which is a JSON-encoded object: NEL: { "report_to": "nel", "max_age": 31556952 } An origin considered secure by the browser is required. The following object keys can be specified in the NEL header: report_to The reporting API group to send network error reports to (see below). max_age Specifies the lifetime of the policy, in seconds (in a similar way to e.g. HSTS policies are time-restricte...
...plies to all subdomains under the origin that the policy header is set. The reporting group should also be set to include subdomains, if this option is to be enabled. success_fraction Floating point value between 0 and 1 which specifies the proportion of successful network requests to report. Defaults to 0, so that no successful network requests will be reported if the key is not present in the JSON payload. failure_fraction Floating point value between 0 and 1 which specifies the proportion of failed network requests to report. Defaults to 1, so that all failed network requests will be reported if the key is not present in the JSON payload. The reporting group referenced above is defined in the usual manner within the Report-To header, for example: Report-To: { "group": "nel", ...
TypeError: "x" is not a constructor - JavaScript
The JavaScript exception "is not a constructor" occurs when there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. Message TypeError: Object doesn't support this action (Edge) TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: JSON is not a constructor TypeError: Symbol is not a constructor TypeError: Reflect is not a constructor TypeError: Intl is not a constructor TypeError: Atomics is not a constructor Error type TypeError What went wrong? There was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. See constructor or the new operator for more information on what a constructor is. There are many global objects, like String or ...
... a constructor, but that object or variable is not a constructor. See constructor or the new operator for more information on what a constructor is. There are many global objects, like String or Array, which are constructable using new. However, some global objects are not and their properties and methods are static. The following JavaScript standard built-in objects are not a constructor: Math, JSON, Symbol, Reflect, Intl, Atomics. Generator functions cannot be used as constructors either. Examples Invalid cases var Car = 1; new Car(); // TypeError: Car is not a constructor new Math(); // TypeError: Math is not a constructor new Symbol(); // TypeError: Symbol is not a constructor function* f() {}; var obj = new f; // TypeError: f is not a constructor A car constructor Suppose you w...
Array.prototype.filter() - JavaScript
let arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: NaN }, { id: 'undefined' } ] let invalidEntries = 0 function filterByID(item) { if (Number.isFinite(item.id) && item.id !== 0) { return true } invalidEntries++ ret...
... let arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: NaN }, { id: 'undefined' } ] let invalidEntries = 0 function filterByID(item) { if (Number.isFinite(item.id) && item.id !== 0) { return true } invalidEntries++ return false; } let arrByID = arr.filter(filterByID) console.log...
Add to Home screen - Progressive web apps (PWAs)
ern web technologies (A2HS included) will work only on secure contexts. To have a manifest file with the correct fields filled in, linked from the HTML head. To have an appropriate icon available for displaying on the Home screen. Chrome additionally requires the app to have a service worker registered (e.g., so it can function when offline). Manifest The web manifest is written in standard JSON format and should be placed somewhere inside your app directory (in the root is probably best) with the name somefilename.webmanifest (we've chosen manifest.webmanifest). It contains multiple fields that define certain information about the web app and how it should behave. Note: The .webmanifest extension is specified in the Media type registration section of the specification, but generally b...
... root is probably best) with the name somefilename.webmanifest (we've chosen manifest.webmanifest). It contains multiple fields that define certain information about the web app and how it should behave. Note: The .webmanifest extension is specified in the Media type registration section of the specification, but generally browsers will support manifests with other appropriate extensions, e.g. .json. The fields needed for A2HS are as follows: background_color: Specifies a background color to be used in some app contexts. The most relevant one to A2HS is the splash screen displayed when the app icon on the Home screen is tapped and it first starts to load (this currently appears only when apps have been added to the Home screen by Chrome). display: Specifies how the app should be displa...
How to make PWAs installable - Progressive web apps (PWAs)
ly by Chrome for Android currently) Currently, only the Chromium-based browsers such as Chrome, Edge, and Samsung Internet require the service worker. If developing your app using Firefox, be aware that you will need a service worker to be compatible with Chromium-based browsers. The manifest file The key element is a web manifest file, which lists all the information about the website in a JSON format. It usually resides in the root folder of a web app. It contains useful information, such as the app's title, paths to different-sized icons that can be used to represent the app on an OS (such as an icon on the home screen, an entry in the Start menu, or an icon on the desktop), and a background color to use in loading or splash screens. This information is needed for the browser to pres...
... such as the home screen of a mobile device. The js13kpwa.webmanifest file of the js13kPWA web app is included in the <head> block of the index.html file using the following line of code: <link rel="manifest" href="js13kpwa.webmanifest"> There are a few common kinds of manifest file that have been used in the past: manifest.webapp was popular in Firefox OS app manifests, and many use manifest.json for web manifests as the contents are organized in a JSON structure. However, the .webmanifest file format is explicitly mentioned in the W3C manifest specification, so that's what we'll use here. The content of the file looks like this: { "name": "js13kGames Progressive Web App", "short_name": "js13kPWA", "description": "Progressive Web App that lists games submitted to the A-Frame cate...
Communicating With Other Scripts - Archive of obsolete content
nt("addon-message", true, true, { hello: 'world' }); document.documentElement.dispatchEvent(event); } </script> <button onclick="sendMessage()">Send Message</button> </body> </html> Finally, the content script "listen.js" listens for the new event and retrieves the payload from its detail attribute: window.addEventListener("addon-message", function(event) { console.log(JSON.stringify(event.detail)); }, false); ...
Loading Content Scripts - Archive of obsolete content
oint the DOMContentLoaded event fires. At this point, content scripts are able to interact with the DOM content, but externally-referenced stylesheets and images may not have finished loading. "end" loads the scripts after all content (DOM, JS, CSS, images) for the page has been loaded, at the time the window.onload event fires. The default value is "end". The contentScriptOptions is a json that is exposed to content scripts as a read only value under self.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. ...
Communicating using "postMessage" - Archive of obsolete content
ule does not support port, so to send messages from a content script to the add-on via a context menu object, you must use message events. Handling Message Events in the Content Script To send a message from a content script, you use the postMessage function of the global self object: self.postMessage(contentScriptMessage); This takes a single parameter, the message payload, which may be any JSON-serializable value. To receive a message from the add-on script, use self's on function: self.on("message", function(addonMessage) { // Handle the message }); Like all event-registration functions, this takes two parameters: the name of the event, and the handler function. The handler function is passed the message payload. Handling Message Events in the Add-on Script To send a message to...
Program ID - Archive of obsolete content
-on for distribution using jpm xpi, it will become the ID field in the add-on's Install Manifest. The ID is used for a variety of purposes. For example: addons.mozilla.org uses it to distinguish between new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on. When you create an XPI with jpm xpi: if the package.json does not include an id field, then the ID written into the install.rdf is the value of the name field prepended with "@". if the package.json does include an id field, and it contains "@", then this is written into the install.rdf as the add-on ID. if the package.json does include an id field, and it does not contain "@", then jpm xpi raises an error and the XPI will not be built. ...
Two Types of Scripts - Archive of obsolete content
directory under your add-on's root. To learn all about content scripts read the Working with Content Scripts guide. API Access for Add-on Code and Content Scripts The table below summarizes the APIs that are available to each type of script. API Add-on code Content script The global objects defined in the core JavaScript language, such as Math, Array, and JSON. See the reference at MDN. ? ? The require() and exports globals defined by version 1.0 of the CommonJS Module Specification. You use require() to import functionality from another module, and exports to export functionality from your module. If require() is available, then so are the modules supplied in the SDK. ? ? The console global supplied by the SDK. ...
l10n - Archive of obsolete content
Localize strings appearing in the add-on's JavaScript code. Usage To learn how to use this module to write localizable code, read the Localization tutorial. Note that you can't currently use localize strings appearing in content scripts or HTML files, but you can share the localized strings you want by assigning it's values to a JSON serializable object. Globals Functions get(identifier, count, placeholder1...n) This function takes a string parameter which it uses as an identifier to look up and return a localized string in the locale currently set for Firefox. Localized strings are supplied by the add-on developer in .properties files stored in the add-ons "locale" directory. The gettext tools uses "_" for the name of the function that retrieves localized strings. For compatibili...
private-browsing - Archive of obsolete content
an individual browser window. The user enters private browsing by opening a new private browser window. When they do this, any existing non-private windows are kept open, so the user will typically have both private and non-private windows open at the same time. ...
url - Archive of obsolete content
internally. var urls = require("sdk/url"); console.log(urls.getTLD("http://www.bbc.co.uk/")); // "co.uk" console.log(urls.getTLD("https://developer.mozilla.org/")); // "org" Parameters url : string The URL, as a string. Returns string : The top-level domain for the URL. URL Methods toString() Returns a string representation of the URL. Returns string : The URL as a string. toJSON() Returns a string representation of the URL. Returns string : The URL as a string. Properties scheme The name of the protocol in the URL, without the trailing ':'. Compare with protocol. For example: var url = require("sdk/url").URL("https://developer.mozilla.org/Add-ons?example=true&visible=yes#top"); console.log(url.scheme); // https userPass The username:password part of the URL, nu...
content/loader - Archive of obsolete content
Optional. contentURL The URL of the content loaded. allow Permissions for the content, with the following keys: ...
core/heritage - Archive of obsolete content
nts all own properties of all given objects. If two or more argument objects have own properties with the same name, the property is overridden, with precedence from right to left, implying, that properties of the object on the left are overridden by a same named property of the object on the right. var { mix } = require('sdk/core/heritage'); var object = mix({ a: 1, b: 1 }, { b: 2 }, { c: 3 }); JSON.stringify(object) // => { "a": 1, "b": 2, "c": 3 } obscure Module exports obscure utility function that is useful for defining non-enumerable properties. Function takes an object and returns a new one in return that inherits from the same object as given one and implements all own properties of given object but as non-enumerable ones: var { obscure } = require('api-utils/heritage');...
core/namespace - Archive of obsolete content
element, contentScript } = options; let widget = Object.create(Widget.prototype); View.call(widget, options.element); sandboxes(widget).sandbox = Cu.Sandbox(element.ownerDocument.defaultView); // ... } Widget.prototype = Object.create(View.prototype); Widget.prototype.postMessage = function postMessage(message) { let { sandbox } = sandboxes(this); sandbox.postMessage(JSON.stringify(JSON.parse(message))); ... }; Widget.prototype.destroy = function destroy() { View.prototype.destroy.call(this); // ... delete sandboxes(this).sandbox; }; exports.Widget = Widget; In addition access to the namespace can be shared with other code by just handing them a namespace accessor function. let { dom } = require('./view'); Widget.prototype.setInnerHTM...
lang/type - Archive of obsolete content
dicating if value is a direct descendant of Object.prototype or null. isEmpty(value) Returns true if value is an Object with no properties and false otherwise. let { isEmpty } = require('sdk/lang/type'); isEmpty({}); // true isEmpty({ init: false }); // false Parameters value : object The variable to check. Returns boolean : Boolean indicating if value is an Object with no properties. isJSON(value) Returns true if value is a string, number, boolean, null, array of JSON-serializable values, or an object whose property values are themselves JSON-serializable. Returns false otherwise. let { isJSON } = require('sdk/lang/type'); isJSON({ value: 42 }); // true isJSON({ fn: function () {} ); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicatin...
Tools - Archive of obsolete content
cfx. console Enables your add-on to log error, warning or informational messages. jpm jpm is a command-line tool that enables you to test, run, and package add-ons. jpm-mobile The Node-based replacement for cfx --force-mobile. Enables you to run and test add-ons for Firefox Mobile (aka Fennec). jpmignore Use .jpmignore to ignore files from your XPI builds created via jpm. package.json The package.json file contains manifest data for your add-on, providing not only descriptive information about the add-on for presentation in the Add-ons Manager, but other metadata required of add-ons. ...
Overview - Archive of obsolete content
element the matcher tells the main add-on code, which displays the annotation panel. Working with Data We'll use the simple-storage module to store annotations. Because we are recording potentially sensitive information, we want to prevent the user creating annotations when in private browsing mode. The simplest way to do this is to omit the "private-browsing" key from the add-on's "package.json" file. If we do this, then the add-on won't see any private windows, and the annotator's widget will not appear in any private windows. Getting Started Let's get started by creating a directory called "annotator". Navigate to it and type cfx init. Next, we will implement the widget. ...
Storing annotations - Archive of obsolete content
give the user a chance to choose which data to keep, and prevent the user from adding any more data until the add-on is back under quota.) Respecting Private Browsing Since annotations record the user's browsing history we should avoid recording annotations in private windows. There's a very simple way to do this: do nothing. By omitting the "private-browsing" key from the annotator's "package.json" file, the annotator opts out of private browsing altogether. This means that its widget will not appear on any private windows and its selector and matcher content scripts won't run, so the user won't be able to enter any annotations in private windows. Try it: execute cfx run and open a new private window: you should no longer see the annotator's widget. Now we can create and store annotatio...
Display a Popup - Archive of obsolete content
el script and the add-on code. In this tutorial we'll create an add-on that adds an action button to the toolbar that displays a panel when clicked. The panel just contains a <textarea> element: when the user presses the return key, the contents of the <textarea> is sent to the main add-on code. The main add-on code logs the message to the console. ...
Getting started (cfx) - Archive of obsolete content
empty add-on In the command prompt, create a new directory. The directory doesn't have to be under the SDK root: you can create it anywhere you like. Navigate to it, type cfx init, and hit enter: mkdir my-addon cd my-addon cfx init You'll see some output like this: * lib directory created * data directory created * test directory created * doc directory created * README.md written * package.json written * test/test-main.js written * lib/main.js written * doc/main.md written Your sample add-on is now ready for testing: try "cfx test" and then "cfx run". Have fun!" Implementing the add-on Now you can write the add-on's code, which goes in the "main.js" file in your "lib" directory. This file was created for you in the previous step. Open it and add the following code: var buttons = req...
Unit Testing - Archive of obsolete content
The first two functions call atob() and btoa() and use assert.ok() to check that the output is as expected. The second function tests the module's error-handling code by passing an empty string into atob() and using assert.throws() to check that the expected exception is raised. At this point your add-on ought to look like this: /base64 /data icon-16.png package.json README.md index.js base64.js /test test-base64.js Now execute jpm --verbose test from the add-on's root directory. You should see something like this: console.info: jpm-utest: executing './test/test-base64.test atob' console.info: jpm-utest: pass: atob works console.info: jpm-utest: executing './test/test-base64.test btoa' console.info: jpm-utest: pass: btoa w...
Add-on SDK - Archive of obsolete content
migration A guide to porting XUL add-ons to the SDK. This guide includes a comparison of the two toolsets and a working example of porting a XUL add-on. Reference High-Level APIs Reference documentation for the high-level SDK APIs. Tools reference Reference documentation for the jpm tool used to develop, test and package add-ons, the console global used for logging, and the package.json file. Low-Level APIs Reference documentation for the low-level SDK APIs. ...
File I/O - Archive of obsolete content
e content type look up (which would be synchronous I/O). In this case an nsIChannel object has to be explicitly created from the file: Components.utils.import("resource://gre/modules/NetUtil.jsm"); // Content type hint is useful on mobile platforms where the filesystem // would otherwise try to determine the content type. var channel = NetUtil.newChannel(file); channel.contentType = "application/json"; NetUtil.asyncFetch(channel, function(inputStream, status) { ... }); Writing to a file Write a string This sample uses NetUtil.jsm and FileUtils.jsm. Components.utils.import("resource://gre/modules/NetUtil.jsm"); Components.utils.import("resource://gre/modules/FileUtils.jsm"); // file is nsIFile, data is a string // You can also optionally pass a flags parameter here. It defaults to //...
Examples and demos from articles - Archive of obsolete content
ts [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 appear on the web. Autogrowing <textarea> This example shows how to make a textarea really autogrowing during a typing. Insert some custom text in a <te...
Rosetta - Archive of obsolete content
*/ (function () { if (!window.rosetta) { return; } /* This function takes as argument a plain text (in this case, a code written in C) and returns another plain text written in ECMAScript */ function createECMASrc (sCSrc) { /* This is just an empty example... Enjoy in creating your C compiler! */ return "alert(\"Here you have the C code to be compiled to ECMAScript:\\n\\n\" + " + JSON.stringify(sCSrc) + ");"; } rosetta.appendCompiler([ "text/x-csrc", "text/x-c" ], createECMASrc); })(); Note: Creating a compiler from scratch can be a very difficult task. However, if you are able, feel free to public it for our Rosetta script ! Now, all you need is to include rosetta.js and your compiler within your HTML page and you will be able to execute scripts written in C together ...
JavaScript timers - Archive of obsolete content
lliseconds elapsed since 1 January 1970 00:00:00 UTC. Using JavaScript timers within workers Workers can use timeouts and intervals just like the main thread can. This can be useful, for example, if you want to have your worker thread run code periodically instead of nonstop. Functions available to workers In addition to the standard JavaScript set of functions (such as String, Array, Object, JSON etc), there are a variety of functions available from the DOM to workers. This article provides a list of those. Basic animations Since we're using script to control canvas elements it's also very easy to make (interactive) animations. Unfortunately the canvas element was never designed to be used in this way (unlike Flash) so there are limitations. Timer.jsm The Timer.jsm JavaScript code mod...
Jetpack Processes - Archive of obsolete content
t) Evaluates the given script contents in the given sandbox's global scope. At minimum, JavaScript 1.8.1 is used. Individual lines of the form //@line 1 "foo.js" can be used to specify filename and line number information for debugging purposes. gc() Synchronously performs garbage collection. Handles Messages that communicate between the browser and jetpack process may contain only serializable (JSON) data and handles. A handle can be used to provide context for messages. Either the browser or the jetpack implementation may create one. A handle keeps any arbitrary properties attached to it alive, but those properties are not transmitted across the process boundary. These arbitrary properties are the primary means through which context can be provided for messages; for instance, if the handle ...
Security best practices in extensions - Archive of obsolete content
s and other data handling Web content is more than just pages, and more and more add-ons are interacting with web services via an Application Programming Interface (API). Many of the items talked about so far in this document apply in this sphere, but here are some additional tips: API providers should use the https protocol, which provides better protection for data passed over the network. JSON has become a popular data format for return formats for Web services. Be sure to read Using native JSON to find out the correct way to handle it. APIs can't be used with self-signed certificates. Remote JavaScript and Content There are a number of ways of remote scripts being used in extensions. They can be included in content, or downloaded at intervals. Non-chrome urls in chrome XUL or HTM...
Tabbed browser - Archive of obsolete content
/gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyServiceGetter(this, "gSessionStore", "@mozilla.org/browser/sessionstore;1", "nsISessionStore"); // Create new tab, but don't load the content. ...
Search Extension Tutorial (Draft) - Archive of obsolete content
d-ons. search.xml <?xml version="1.0" encoding="UTF-8"?> <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> <ShortName>Example Engine</ShortName> <Description>Example search engine</Description> <InputEncoding>UTF-8</InputEncoding> <Image width="16" height="16" type="image/png">data:image/png;base64, ... ...
JavaScript Client API - Archive of obsolete content
.js. There's a base Record object, which defines the basic record API. But, you want to use a derived class, CryptoWrapper, which seamlessly encrypts and decrypts records on the client. This makes your synchronized data more secure and unreadable by the server operators. All you have to do is write an object that extends CryptoWrapper and maintains a property called cleartext. cleartext must be a JSON-able object. Put into it all values that you want to have encrypted, stored on the server, decrypted, and synced up. You may find it useful to write getters and setters for various properties of your record implementation. The skeleton of a sample record implementation: function FooRecord(collection, id) { CryptoWrapper.call(this, collection, id); } FooRecord.prototype = { __proto__: C...
Twitter - Archive of obsolete content
the parameters of the various methods at Twitter's API reference.) There are two special, optional properties: success and error. success is a function that's called when the request successfully completes, and error is a function called when it fails to complete. The library simply passes them to jQuery.ajax(), and so they are called like so: success(data, textStatus) data is Twitter's decoded JSON response. textStatus is a simple string describing the status. error(xmlHttpRequest, textStatus, errorThrown) xmlHttpRequest is the XHR used in the request. textStatus is a simple string describing the type of error. errorThrown is an exception object, if one was thrown. The examples below all use this first, simpler style. The second style will be familiar if you have used jQuery.ajax() --...
Plug-n-Hack Phase1 - Archive of obsolete content
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. ...
persist - Archive of obsolete content
<< XUL Reference home persist Type: space-separated list of attribute names A space-separated list of attributes that are maintained when the window is closed. When the window is re-opened, the values of persistent attributes are restored. In Mozilla, persistent attributes are stored in the per-profile file xulstore.json. Persistence can also be stored using the document.persist function. In order for persistence to work, the element must also have an id. Persistence will not remember the absence of an attribute, so for boolean attributes like checked where absence means false, you will need to explicitly set the attribute to false before the window closes (bug 15232). ...
XUL Questions and Answers - Archive of obsolete content
d, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. If you are using a button that matches one of these common usages, use the icon attribute to indicate this. How to use Dynamic Objects in Toolbar There may be a few ways to implement this: By building your menupopup from an RDF datasource, which could be generated on the server. By getting data (e.g. JSON string) from the server, parsing it on client, and building the menupopup using DOM methods (such as document.createElementNS). By getting data as XML from the server. (server can just send the XUL code to use for popup - alternatively it can send generic XML describing the attributes of the items in the menu and you generate the XUL on client by applying an XSLT transform.) Can I change a X...
XUL element attributes - Archive of obsolete content
than the total size of the children, the extra space is placed on the left or top side. persist Type: space-separated list of attribute names A space-separated list of attributes that are maintained when the window is closed. When the window is re-opened, the values of persistent attributes are restored. In Mozilla, persistent attributes are stored in the per-profile file xulstore.json. Persistence can also be stored using the document.persist function. In order for persistence to work, the element must also have an id. Persistence will not remember the absence of an attribute, so for boolean attributes like checked where absence means false, you will need to explicitly set the attribute to false before the window closes (bug 15232). popup Type: id Should be set to the...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
Components.utils.reportError(obj.toSource()); }; SOAPClient.Proxy = url; var body = new SOAPObject(method); body.ns = ns; for (var k in params) { body.appendChild(new SOAPObject(k).val(params[k])); } var req = new SOAPRequest(url, body); req.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) { < ...
Mozprofile - Archive of obsolete content
y or from a manifest. Example: from mozprofile import FirefoxProfile # create new profile to pass to mozmill/mozrunner profile = FirefoxProfile(addons=["adblock.xpi"]) Setting Preferences Preferences can be set in several ways: using the API: You can pass preferences in to the Profile class's constructor: obj = FirefoxProfile(preferences=[("accessibility.typeaheadfind.flashBar", 0)]) using a JSON blob file: mozprofile --preferences myprefs.json using a .ini file: mozprofile --preferences myprefs.ini via the command line: mozprofile --pref key:value --pref key:value [...] When setting preferences from an .ini file or the --pref switch, the value will be interpolated as an integer or a boolean (true/false) if possible. Setting Permissions mozprofile also takes care of adding permissions ...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
Implemented proposals not in ES.Next This section needs to be updated to reflect current changes. (May 2019) The following features are already implemented, but only available in the Firefox Nightly channel and not yet included in a draft edition of an ECMAScript specification. Additions to the ArrayBuffer ...
New in JavaScript 1.8.1 - Archive of obsolete content
The following is a changelog for JavaScript 1.8.1. This version was included in Firefox 3.5. JavaScript 1.8.1 is a modest update syntactically to JavaScript; the main change in this release is the addition of the Tracemonkey just-in-time compiler, which improves performance. New features in JavaScript 1.8.1 Object.getPrototypeOf() Support for native JSON String.prototype.trim() String.prototype.trimLeft() String.prototype.trimRight() Changed functionality in JavaScript 1.8.1 Implicit setting of properties in object and array initializers no longer execute setters in JavaScript. This makes the behavior of setting the values of properties more predictable. ...
ECMAScript 5 support in Mozilla - Archive of obsolete content
full support for ECMAScript 5.1 features. This article covers the features supported by different versions of Mozilla's JavaScript runtime. Supported features Added in JavaScript 1.8.5 (Gecko 2, Firefox 4 and later) Firefox 4 has full ECMAScript 5 support including the Object.* methods and strict mode. See New in JavaScript 1.8.5. Added in JavaScript 1.8.1 (Gecko 1.9.1, Firefox 3.5) Native JSON support Object.getPrototypeOf() method. String.trim() method, which trims whitespace from both ends of the string. Gecko 1.9.1.4 updated the implementation of JSON.stringify() to be compliant with ECMAScript 5. Improvements laid out by ECMAScript 5 have been made in the parsing algorithm that prevents evaluating XHTML as JavaScript code in certain circumstances. Added in JavaScript 1.6 (Gec...
New in JavaScript - Archive of obsolete content
. Released in October 2006. Includes generators, iterators, array comprehensions, let expressions, and destructuring assignment. JavaScript 1.8 Version shipped in Firefox 3. Released in June 2008. Includes expression closures, generator expressions and Array.reduce() JavaScript 1.8.1 Version shipped in Firefox 3.5. Released on June 30, 2009. Includes the TraceMonkey JIT and supports native JSON. JavaScript 1.8.2 Version shipped in Firefox 3.6. Released June 22, 2009. Includes only minor changes. JavaScript 1.8.5 Version shipped in Firefox 4. Released July 27, 2010. Includes many new features for ECMA-262 Edition 5 compliance. This is the last JavaScript version. ...
Visual-js game engine - Game development
or images (alias sprite - but for now there's no sprite and frame by frame animation methods). Small engine config . Some option in aspect view like npm install ... npm install typescript npm i clean-webpack-plugin --save-dev npm i html-webpack-plugin --save-dev Possible fix : npm i webpack --save-dev npm i extract-text-webpack-plugin --save-dev Fix code format : tslint -c tslint.json 'src/**/*.ts' --fix Download project link : Download link from BitBucket. ...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
essages whenever they wish, instead of having to schedule them around each other. When software communicates asynchronously, a program may make a request for information from another piece of software (such as a server), and continue to do other things while waiting for a reply. For example, the AJAX (Asynchronous JavaScript and XML) programming technique--now usually simply "Ajax", even though JSON is usually used rather than XML in modern applications--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 tas...
Deserialization - MDN Web Docs Glossary: Definitions of Web-related terms
The process whereby a lower-level format (e.g. that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure. In JavaScript, for example, you can deserialize a JSON string to an object by calling the function JSON.parse(). Learn more General knowledge Serialization on Wikipedia ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
t, if no external factors were applied to it. For example, inline elements are sized intrinsically: width, height, and vertical margin and padding have no impact, though horizontal margin and padding do. 238 JPEG Beginner, Composing, Glossary, Images, JPEG JPEG (Joint Photographic Experts Group) is a commonly used method of lossy compression for digital images. 239 JSON CodingScripting, Glossary, Intro, JSON, l10n:priority JavaScript Object Notation (JSON) is a data-interchange format. Although not a strict subset, JSON closely resembles a subset of JavaScript syntax. Though many programming languages support JSON, JSON is especially useful for JavaScript-based apps, including websites and browser extensions. 240 Jank Beginner, CodingSc...
Serialization - MDN Web Docs Glossary: Definitions of Web-related terms
The process whereby an object or data structure is translated into a format suitable for transferral over a network, or storage (e.g. in an array buffer or file format). In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON.stringify(). CSS values are serialized by calling the function CSSStyleDeclaration.getPropertyValue(). Learn more General knowledge Serialization on Wikipedia ...
MDN Web Docs Glossary: Definitions of Web-related terms
x IndexedDB Information architecture Inheritance Input method editor Instance Internationalization Internet Intrinsic Size IP Address IPv4 IPv6 IRC ISO ISP ITU J Jank Java JavaScript JPEG jQuery JSON K Key Keyword L Latency Layout viewport Lazy load LGPL Ligature Local scope Local variable Locale Localization Long task Loop Lossless compression lossy compression LTR (Left To Right) M Main Axis ...
Adding features to our bouncing balls demo - Learn web development
bove). ...
JavaScript object basics - Learn web development
Objects let us keep the information safely locked away in their own package, out of harm's way. ...
Inheritance in JavaScript - Learn web development
e core OOJS theory and syntax that we think you should know now. At this point you should understand JavaScript object and OOP basics, prototypes and prototypal inheritance, how to create classes (constructors) and object instances, add features to classes, and create subclasses that inherit from other classes. In the next article we'll have a look at how to work with JavaScript Object Notation (JSON), a common data exchange format written using JavaScript objects. ...
Object-oriented JavaScript for beginners - Learn web development
hole story, but it gives you an idea of what we are dealing with here. ...
Object prototypes - Learn web development
ototype property and how it can be used to add methods to constructors, and other related topics. ...
JavaScript — Dynamic client-side scripting - Learn web development
n objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it. Asynchronous JavaScript In this module we take a look at asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. Client-side web APIs When writing client-side JavaScript for web sites or applications, you won't go very far before you start to use APIs...
Client-Server Overview - Learn web development
at a Web Application might perform would be sending an email to users to confirm their registration with the site. The site might also perform logging or other operations. Returning something other than HTML Server-side website code does not have to return HTML snippets/files in the response. It can instead dynamically create and return other types of files (text, PDF, CSV, etc.) or even data (JSON, XML, etc.). The idea of returning data to a web browser so that it can dynamically update its own content (AJAX) has been around for quite a while. More recently "Single-page apps" have become popular, where the whole website is written with a single HTML file that is dynamically updated when needed. Websites created using this style of application push a lot of computational cost from the serv...
Introduction to the server side - Learn web development
roducts 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 sent). The server is not limited to sending information from databases, and might alternatively return the result of software tools, or data from communications services. The content can even be targeted for the type of client device that i...
Ember resources and troubleshooting - Learn web development
is possible to roll your own front-end data client. A common alternative is to any fully-featured front-end data client is The Fetch API. Using the design patterns provided by the framework, a Route using fetch() would look something like this: import Route from '@ember/routing/route'; export default class MyRoute extends Route { async model() { let response = await fetch('some/url/to/json/data'); let json = await response.json(); return { data: json }; } } See more information on specifying the Route's model here. Why can't I just use JavaScript? This is the most common question Ember folks hear from people who have previous experience with React. While it is technically possible to use JSX, or any other form of DOM creation, there has yet to be anything ...
Deployment and next steps - Learn web development
e analyzed our components and compiled the code to vanilla JavaScript. A look behind the Svelte compilation process By default, when you create a new app with npx degit sveltejs/template my-svelte-project, Svelte will use rollup as the module bundler. Note: There is also an official template for using webpack and also many community-maintained plugins for other bundlers. In the file package.json you can see that the dev and start scripts are just calling rollup: "scripts": { "build": "rollup -c", "dev": "rollup -c -w", "start": "sirv public" }, In the dev script we are passing the -w argument, which tells rollup to watch files and rebuild on changes. If we have a look at the rollup.config.js file, we can see that the Svelte compiler is just a rollup plugin: import svelte from '...
Setting up your own test automation environment - Learn web development
ace the YOUR-USER-NAME and YOUR-ACCESS-KEY placeholders in the code with your actual user name and access key values): driver.sleep(2000).then(function() { driver.getTitle().then(function(title) { if(title === 'webdriver - Google Search') { console.log('Test passed'); request({uri: "https://YOUR-USER-NAME:YOUR-ACCESS-KEY@www.browserstack.com/automate/sessions/" + sessionId + ".json", method:"PUT", form:{"status":"passed","reason":"Google results showed correct title"}}); } else { console.log('Test failed'); request({uri: "https://YOUR-USER-NAME:YOUR-ACCESS-KEY@www.browserstack.com/automate/sessions/" + sessionId + ".json", method:"PUT", form:{"status":"failed","reason":"Google results showed wrong title"}}); } }); }); These are fairly intuitive -- ...
Command line crash course - Learn web development
the side of simplicity and install globally to keep things simple. We'll look more at local installs and why they're good in the next article. Installing Prettier For this article we will install Prettier as a global command line utility. Prettier is an opinionated code formatting tool for front end developers, focusing around JavaScript-based languages and adding support for HTML, CSS, SCSS, JSON and more. Prettier can: Save the cognitive overhead of getting the style consistent manually across all your code files; Prettier can do this for you automatically. Help newcomers to web development format their code in best-practice fashion. Be installed on any operating system and even as a direct part of project tooling, ensuring that colleagues and friends who work on your code use the ...
Index
ns, 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 hosted on AMO automatically receive updates to new versions posted there. Other add-ons must specify the location of their update manifests. ...
Themes
emes Browser theme concepts Get an introduction to creating themes for the latest versions of Firefox Using the AMO theme generator Use the theme generator to create and submit a new theme to AMO Lightweight Themes Lightweight themes have been deprecated and are no longer accepted by AMO. Only browser themes will be accepted going forward. Tools & Resources Browser theme manifest.json keys Browser extensions theme API Discourse forum Theme related blog posts Archived resources ...
Testopia
than back porting. However, this means that most major feature will not be back ported to earlier versions unless and until we have time to do so. Anyone wishing to help in this effort is more than welcome. Bugzilla 4.x Mysql 5.0 or PostgreSQL 8.3 Mozilla compatible browser ;-) Additional Perl Modules: Text::CSV XML::Schema Validator XML::Schema::Parser (for importer) and JSON 2.10 TODO User preferences Notification emails More Reports See the Roadmap and Bug List for more details. Links FAQ Wiki Docs Bugs (Please read the Bug Reporting Guide) Official Testopia Blog IRC: #testopia or #bugzilla User Help support-webtools@lists.mozilla.org Developers dev-apps-webtools@lists.mozilla.org Downloa...
Creating MozSearch plugins
oo!: <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> <ShortName>Yahoo</ShortName> <Description>Yahoo Search</Description> <InputEncoding>UTF-8</InputEncoding> <Image width="16" height="16">data:image/x-icon;base64,R0lGODlhEAAQAJECAP8AAAAAAP///wAAACH5BAEAAAIALAAAAAAQABAAAAIplI+py+0NogQuyBDEnEd2kHkfFWUamEzmpZSfmaIHPHrRguUm/fT+UwAAOw==</Image> <Url type="application/x-suggestions+json" method="GET" template="http://ff.search.yahoo.com/gossip?output=fxjson&amp;command={searchTerms}" /> <Url type="text/html" method="GET" template="http://search.yahoo.com/search"> <Param name="p" value="{searchTerms}"/> <Param name="ei" value="UTF-8"/> <MozParam name="fr" condition="pref" pref="yahoo-fr" /> </Url> <SearchForm>http://search.yahoo.com/</SearchForm> </SearchPlugin> Let...
ESLint
-env mozilla/chrome-worker */ My file uses Chrome/XBL specific globals Either, specify the global at the top of the file: /* globals MyChromeGlobal */ or, add to the global section toolkit/.eslintrc.js if it is widely used. Foo.jsm exports a symbol, but that is not recognised by ESlint Check it is listed correctly in tools/lint/eslint/modules.json Using Services.scriptloader.loadSubScript? You'll need to include the following just above it: /* import-globals-from relative/path/to/file.js */ do_check_eq, add_task not defined in a test directory. Ensure there is a .eslintrc.js file that extends one of: "plugin:mozilla/browser-test" "plugin:mozilla/chrome-test" "plugin:mozilla/moc...
Performance best practices for Firefox front-end engineers
on that bug for more information. Use IndexedDB for storage AppCache and LocalStorage are synchronous storage APIs that will block the main thread when you use them. Avoid them at all costs! IndexedDB is preferable, as the API is asynchronous (all disk operations occur off of the main thread), and can be accessed from web workers. IndexedDB is also arguably better than storing and retrieving JSON from a file--particularly if the JSON encoding or decoding is occurring on the main thread. IndexedDB will do JavaScript object serialization and deserialization for you using the structured clone algorithm, meaning that you can stash things like maps, sets, dates, blobs, and more, without having to do conversions for JSON compatibility. A Promise-based wrapper for IndexedDB, IndexedDB.jsm, is a...
HTMLIFrameElement.getManifest()
Warning: Removed in Firefox 65. The getManifest() method of the HTMLIFrameElement interface retrieves the manifest of an app loaded in the browser <iframe> and returns it as JSON. Syntax instanceOfHTMLIframeElement.getManifest().then(function(json) { ... }); Parameters None. Return value A promise that resolves to a JSON object representation of the loaded app's manifest. Examples var browser = document.querySelector('iframe'); browser.addEventListener('mozbrowserloadend',function() { var request = browser.getManifest().then(function(json) { console.log(json); }); }); Specification Not part of any specification. ...
mozbrowsercontextmenu
is passed to the contextmenuItemSelected() function, to indicate which item has been selected. items An array of further Menu objects, which indicate the menu options available in a menu, if the context menu being accessed is a menu. ...
mozbrowsershowmodalprompt
alled. Obsolete properties of details msg_name A string representing the type of message. For that event, it's always showmodalprompt. initialValue A string representing the initial value for the window.prompt() methods. ...
Assert.jsm
essage ); Parameters actual Test subject to be evaluated as not equivalent to expected expected Test reference to evaluate against actual message Short explanation of the expected result deepEqual() The equivalence assertion tests a deep equality relation. We check using the most exact approximation of equality between two objects to keep the chance of false positives to a minimum. JSON.stringify is not designed to be used for this purpose; objects may have ambiguous toJSON() implementations that would influence the test. undefined deepEqual( actual, expected, message ); Parameters actual Test subject to be evaluated as equivalent to expected, including nested properties expected Test reference to evaluate against actual message Short explanation of the expected...
SourceMap.jsm
; Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap); SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be JSON.parse'd, or an object). According to the spec, source maps have the following attributes: version: Which version of the source map spec this map is following. sources: An array of URLs to the original source files. names: An array of identifiers that can be referenced by individual mappings. sourceRoot: Optional. The URL root from which all sources are relative. mapp...
Webapps.jsm
stall: function doInstall(aData, aMm) doInstallPackage: function doInstallPackage(aData, aMm) pushContentAction: function(windowID) popContentAction: function(windowID) actionCancelled: function(windowID) denyInstall: function(aData) _setupApp: function(aData, aId) _cloneApp: function(aData, aNewApp, aLocaleManifest, aManifest, aId, aLocalId) _writeManifestFile: function(aId, aIsPackage, aJsonManifest) _nextLocalId: function() _appIdForManifestURL: function(aURI) makeAppId: function() _saveApps: function() _readManifests: function(aData) _ensureSufficientStorage: function(aNewApp) _checkDownloadSize: function(aFreeBytes, aNewApp) _getRequestChannel: function(aFullPackagePath, aIsLocalFileInstall, aOldApp,) _sendDownloadProgressEvent: function(aNewApp, aProgress) _getPackage: ...
L10n Checks
../l10n/ de There are three modes available: 1: show just errors 2: show errors and important warnings 3: show all errors and warnings Spell checking In all modes you can tell L10n Checks to search for spelling errors, by setting the -c parameter, e.g.: check-l10n-completeness -c suite/locales/l10n.ini ../l10n/ de Spell checking requires enchant and pyenchant to be installed on the system. JSON output In all modes you can tell L10n Checks to present the output as JSON by setting the -j parameter to full_json, e.g.: check-l10n-completeness -j full_json suite/locales/l10n.ini ../l10n/ de JSON output requires simplejson to be present on the system if using Python 2.5. Verbose level In all modes you can set the verbose level, e.g.: check-l10n-completeness --verbose 5 full_json suite/locale...
Patches and pushes
"http://www.mozilla.org/2006/browser/search/"> <ShortName>Yahoo</ShortName> <Description>Yahoo Search</Description> <InputEncoding>UTF-8</InputEncoding> <Image width="16" height="16">data:image/x-icon;base64,R0lGODlhEAAQAJECAP8AAAAAAP///wAAACH5BAEAAAIALAAAAAAQABAAAAIplI+py+0NogQuyBDEnEd2kHkfFWUamEzmpZSfmaIHPHrRguUm/fT+UwAAOw==</Image> ***This tag is optional***<Url type="application/x-suggestions+json" method="GET" template="http://ff.search.yahoo.com/gossip?output=fxjson&amp;command={searchTerms}" />*** <Url type="text/html" method="GET" template="http://search.yahoo.com/search"> <Param name="p" value="{searchTerms}"/> <Param name="ei" value="UTF-8"/> <MozParam name="fr" condition="pref" pref="yahoo-fr" /> </Url> <SearchForm>http://search.yahoo.com/</SearchForm> </SearchPlugin> ...
MailNews automated testing
f the event-loop-spinning style of operation used by mozmill. Message synthesis: Create messages by specifying what properties the messages should have. Message injection: Inject synthesized messages via local or IMAP (using a fake server). Message manipulation: Mark messages as read, tag them, untag them, move them to other folders, trash them, etc. Enhanced logging: Supports generating rich JSON streams to disk or over the network for consumption by LogSploder or other tools. Performance testing Mail leak and bloat tests These tests start up Thunderbird or SeaMonkey and record any leaks found, as well as the total memory requirement. Although currently based on simple tests, these are useful for determining if new leaks have been introduced. For more information, see Leak and Bloat ...
Index
ce(2), SpiderMonkey JS_ObjectIsRegExp determines if a specified object, obj, is a RegExp object. If so, JS_ObjectIsRegExp returns true. Otherwise it returns false. 423 JS_PSGS JSAPI Reference, Reference, Reference(2), SpiderMonkey These macros encapsulate the definition of JSNative-backed JSPropertySpecs, by defining the JSNativeWrappers for them. 424 JS_ParseJSON Parse a string using the JSON syntax described in ECMAScript 5 and return the corresponding value. 425 JS_PopArguments JSAPI_Reference, Obsolete, SpiderMonkey JS_PopArguments frees the stack frame pointer previously allocated by JS_PushArguments and unroots the jsvals which have been associated with it (those returned by JS_PushArguments as well). 426 JS...
Running Parsemark
ozen or so large-payload JS sites globbed up from across the web. Yes, it includes GMail. Here's how you get your mitts on it. The test files are not checked into the source tree because they're non-Mozilla JS code. Download the suite of parse tests from Bug 548621 and decompress them. Within js/src/tests, run python parsemark.py -h to see help documentation. Generally you'll want to capture JSON results for your baseline and compare them to the results for the "current" version of your shell. A typical run can be done like so: cd js/src/tests python parsemark.py /path/to/baseline/js /path/to/parse-tests-dir/ -q > /tmp/baseline.json python parsemark.py /path/to/current/js /path/to/parse-tests-dir/ -q > /tmp/current.json python compare_bench.py /tmp/current.json /tmp/baseline.json NOT...
Zest runtimes
The following runtimes are available: Java https://github.com/mozilla/zest - this is the reference implementation The following runtimes are planned or an an early stage of implementation: https://github.com/mozilla/zest/tree/master/js Javascript https://github.com/darkowlzz/zest-runner https://github.com/darkowlzz/zest-cli - this is the zest-cli of js based runner. Python No code available yet If you are interested in working on an existing or new Zest runtime then please get in touch via the Zest group. ...
Zest
The core language does not define any graphical representation - that is expected to be defined by the tools that integrate Zest. ...
compare-locales
migration.dtd in another directory level deeper. The output closes with a summary, giving the total counts of missing and obsolete strings and words, and some statistics on how many strings are changed or not, excluding access- and commandkeys. That gives localizers an idea on how thorough the localization is. This number won't reach 100% in general, mid 80s should be the target, though. Pass --json to get just the summary in JSON format. ...
Mozilla Projects
To that end, this document will be revised over time as we find new and better ways of helping developers. Zest Zest is an experimental specialized scripting language (also known 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...
Setting up an update server
, false).path Once you have determined the update directory, close Firefox, browse to the directory and remove the subdirectory called updates. Next, you need to change the update URL to point to the local XML file. This can be done most reliably with an enterprise policy. The policy file location depends on the operating system you are using. Windows/Linux: <install dir>/distribution/policies.json macOS: <install dir>/Contents/Resources/distribution/policies.json Create the distribution directory, if necessary, and put this in policies.json: { "policies": { "AppUpdateURL": "http://127.0.0.1:8000/update.xml" } } Now you are ready to update! Launch Firefox out of its installation directory and navigate to the Update section about:preferences. You should see it downloading the upd...
Index
Mozilla › Tech › XPCOM › Index
Reference, XPCOM Interface Reference None. 705 nsIJSID Interfaces, Interfaces:Scriptable, XPCOM API Reference, XPCOM Interface Reference The following methods return objects that implement this interface: 706 nsIJSIID Interfaces, Interfaces:Scriptable, NeedsContent, XPCOM, XPCOM API Reference, XPCOM Interface Reference No summary! 707 nsIJSON Interfaces, Interfaces:Scriptable, NeedsExample, XPCOM API Reference, XPCOM Interface Reference Implemented by: @mozilla.org/dom/json;1. To create an instance, use: 708 nsIJetpack Interfaces, Interfaces:Scriptable, Jetpack, XPCOM, XPCOM Interface Reference This method asynchronously sends a message to the Jetpack process. 709 nsIJetpackService Interfa...
XPCshell Test Manifest Expressions
s of characters enclosed in double quotes " or single quotes '. No escape sequences are supported. Variables Variables are supported as a series of letters, digits or underscores beginning with a letter or an underscore. There are a fixed set of variables provided by the test harness via mozinfo.py, with many of the values initialized at configure time by writemozinfo.py which writes mozinfo.json into the root of the build directory. See also the official docs for this set of variables. Note that it currently seems like neither this list nor the one on the official docs is exhaustive, so if you need something and it's not here, best check the source code! os - The operating system on which the test is being run One of: 'win', 'mac', 'linux', 'android' os_version - The vers...
nsIFrameMessageListener
ethods receiveMessage() Note: This method is for JavaScript only. Called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name The name of the message. sync A boolean value indicating whether or not the message should be handled synchronously. If true, the response should be returned in the specified JSON object. json The JSON object in which to return the response if the message is being handled synchronously. objects Unimplemented An array of cpow, or null if sync is false. When the listener is called, the this value is the target of the message. void receiveMessage(); Parameters None. See also Content process event handling nsIFrameListener ...
nsIPushMessage
dom/interfaces/push/nsIPushNotifier.idlScriptable A push message sent to a system subscription. Inherits from: nsISupports Last changed in Gecko 46.0 (Firefox 46.0 / Thunderbird 46.0 / SeaMonkey 2.43) nsIPushMessage is the subject of a push-message observer notification. This interface resembles PushMessageData from the Push API. Method overview DOMString text(); jsval json(); void binary([optional] out uint32_t dataLen, [array, retval, size_is(dataLen)] out uint8_t data); Methods text() Extracts the message data as a UTF-8 text string. DOMString text(); Parameters None. json() Parses the message data as JSON. jsval json(); Parameters None. binary() Extracts the message data as a byte array. void binary( [optional] out uint32_t dataL...
nsIPushService
else if (topic == "push-subscription-change") { this.onPushSubscriptionChange(); } } }, onPushMessage(maybeMessage) { if (!maybeMesssage) { // The subject will be `null` for messages without data. return; } let message = maybeMesssage.QueryInterface(Ci.nsIPushMessage); message.text(); // Returns the message contents as a UTF-8 string. message.json(); // Parses the message as JSON. message.binary(); // Returns a byte array. }, onPushSubscriptionChange() { // Re-subscribe if the subscription was dropped. pushService.subscribe( this.scope, scriptSecurityManager.getSystemPrincipal(), (code, subscription) => { // ... }); } }; obsService.addObserver(pushObserver, "push-message", false); obsServic...
nsIPushSubscription
key: String.fromCharCode.apply(null, btoa(subscription.getKey("p256dh"))), secret: String.fromCharCode.apply(null, btoa(subscription.getKey("auth"))), })); } pushService.subscribe( "chrome://my-module/push", scriptSecurityManager.getSystemPrincipal(), (code, subscription) => ...
nsISHEntry
ata for the document. referrerURI nsIURI Referrer URI. refreshURIList nsISupportsArray Saved refresh URI list for the content viewer. saveLayoutStateFlag boolean Indicate whether layoutHistoryState should be saved. stateData nsIStructuredCloneContainer Get/set data associated with this history state via a pushState() call, serialized using structured clone. (Prior to Gecko 6.0 returned a JSON encoded string.) sticky boolean Whether the content viewer is marked "sticky" windowState nsISupports Saved state of the global window object. Methods addChildShell() Saved child docshells corresponding to contentViewer. The child shells are restored as children of the parent docshell, in this order, when the parent docshell restores a saved presentation. Append a child shell to the end...
nsISyncMessageSender
t. sendRpcMessage() Like sendSyncMessage(), except re-entrant. New RPC messages may be issued even if, earlier on the call stack, we are waiting for a reply to an earlier sendRpcMessage() call. Parameters Name Type Description messageName String The name of the message. Optional. This becomes the name property of the received message. obj JSONable object. The message payload. A structured clone of this becomes the data property of the received message. objects Object. An object each of whose properties is an object. This becomes the objects property of the received message, with each original object replaced with a cross process object wrapper for it. principal nsIPrincipal ...
nsIWebProgressListener
is now the <xul:browser> that saw the web progress activity // occur. If you need to hold onto an identifier for whichever frame // (be it the top-level, or a subframe) was using the WebProgress, use // the outerWindowID. This can be communicated back down to the content // in order to do send a command to a particular DOM Window. ...
XPCOM Interface Reference
IHapticFeedbacknsIHttpActivityDistributornsIHttpActivityObservernsIHttpChannelnsIHttpChannelInternalnsIHttpHeaderVisitornsIHttpServernsIHttpUpgradeListenernsIIDNServicensIIFrameBoxObjectnsIINIParsernsIINIParserFactorynsIINIParserWriternsIIOServicensIIdleServicensIInProcessContentFrameMessageManagernsIInputStreamnsIInputStreamCallbacknsIInstallLocationnsIInterfaceRequestornsIJSCIDnsIJSIDnsIJSIIDnsIJSONnsIJetpacknsIJetpackServicensIJumpListBuildernsIJumpListItemnsILivemarkServicensILoadGroupnsILocalFilensILocalFileMacnsILocalensILocaleServicensILoginInfonsILoginManagernsILoginManagerCryptonsILoginManagerIEMigrationHelpernsILoginManagerPrompternsILoginManagerStoragensILoginMetaInfonsIMIMEInputStreamnsIMacDockSupportnsIMarkupDocumentViewernsIMemorynsIMemoryMultiReporternsIMemoryMultiReporterCallba...
Test-Info
Data files are typically consumed by dashboards, like www.arewefissionyet.com. Running test-info locally "test-info" is a mach command and can be run from any source tree. ...
Mozilla
mozilla.org/build/buildsystem/supported-configurations.html Task graph After a change to the Gecko source code is pushed to version-control, jobs for that change appear on Treeherder. How does this work? Test-Info The test-info task group runs per-commit, only on mozilla-central. Each task generates one or more json-formatted data files providing detailed information on tests run in continuous integration, typically broken down by bugzilla component. Data files are typically consumed by dashboards, like www.arewefissionyet.com. Testing Mozilla code Testing your code is important! Before you can even get your code committed into the source tree, you have t...
Accessibility Inspector - Firefox Developer Tools
fully keyboard-accessible: You can tab between the Turn Off Accessibility Features button and left and right panels. When one of the panels is focused, you can move the focus up and down items using the up and down arrow keys, and use the left and right arrow keys to expand and collapse expandable rows (e.g., different hierarchy levels of the accessibility tree). Print accessibility tree to JSON You can print the contents of the accessibility tree to json by right-clicking on an entry in the Accessibility tab and selecting Print to JSON: When you do, you will get a new tab with the selected accessibility tree loaded into the JSON viewer: Once opened, you can save or copy the data as necessary. The JSON viewer can also show you the raw JSON data on a separate tab in the viewer. Ch...
Migrating from Firebug - Firefox Developer Tools
e objects. The difference is that they show the properties and methods within a side panel inside the Web Console. Show network requests The Console panel in Firebug allows to log AJAX requests (aka XMLHttpRequests). This option is also available within the DevTools Web Console via the Net > XHR. Furthermore, the Web Console even allows to display all other network requests via Net > Log. View JSON and XML structures To view JSON and XML responses of AJAX requests, Firebug has special tabs when expanding the request within the Console panel. The DevTools Web Console shows those structures directly under the "Response" tab. Multi-line command line Firebug's console has a multi-line command line called Command Editor. The DevTools do not have a side panel like the Command Editor (which is ...
Inspecting web sockets - Firefox Developer Tools
ze the interface to see more columns by choosing which ones to show from the context menu that is opened by right-clicking in the table header. Expanding each message Selecting a message in the list shows a preview of the data being sent in that message, at the bottom of the Response pane. Supported WS protocols The inspector currently supports the following web socket protocols: Plain JSON Socket.IO SockJS SignalR WAMP The payload based on those protocols is parsed and displayed as an expandable tree for easy inspection, although you can of course still see the raw data (as sent over the wire) as well. ...
UI Tour - Firefox Developer Tools
ol in the Details pane. access the Settings popup Recordings pane The recordings pane lists all the recordings you have loaded, including any you have made in this session and any you have imported. At any given time, one recording is selected, and that recording is displayed in the rest of the tool. To select a different recording, click its entry in the pane. To save the recording as a JSON file click "Save". Recording overview This displays an overview of the entire recording, with the x-axis representing time. It contains two elements: an overview of the Waterfall and a frame rate graph. Waterfall overview This presents a compressed view of the Waterfall: Recorded operations are color-coded using the same scheme as in the main Waterfall view. Frame rate graph The frame...
Storage Inspector - Firefox Developer Tools
s to IndexedDB or Cache): Sidebar When you select any row in the Storage table widget, the sidebar is shown with details about that row. If a cookie is selected, it will list all the details about that cookie. The sidebar can parse the value of the cookie or local storage item or an IndexedDB item and convert it into a meaningful object instead of just a string. For example: A stringified JSON like '{"foo": "bar"}' is shown as the origin JSON: {foo: "bar"}. A string containing a key separated value, like "1~2~3~4" or "1=2=3=4" is shown like an array: [1, 2, 3, 4]. A string containing key-value pairs, like "ID=1234:foo=bar" is shown as JSON: {ID:1234, foo: "bar"}. The shown values can also be filtered using the search box at the top of the sidebar. Working with the Storage Inspecto...
Console messages - Firefox Developer Tools
Logger extension, Web Console can display messages sent from the server. This enables you to use the Web Console to debug server-side code. It uses the Chrome Logger protocol. Briefly, the way it works is: Your server-side code -- Python, PHP, Node.js, etc. -- includes a library that provides a console API. Your server-side code uses this API to log messages. The server-side library creates JSON objects from the messages and encodes them for transmission. The messages are transmitted to the client as a response header named X-ChromeLogger-Data. The Web Console decodes these headers and displays them. To find a suitable library for your server code, see the Chrome Logger documentation. Interpreter input/output Commands sent to the browser using the Web Console's JavaScript interpret...
Web Console Helpers - Firefox Developer Tools
e working with iframes. clear() Clears the console output area. clearHistory() Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history. copy() Copies the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied. Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard. help()Deprecated since Gecko 62 :help Displays help text. Actually, in a delightful example of recursion, it brings you to this page. inspect() Given an object, generates rich output for that object. Once you select the object in the output area, you can use the arrow keys to navigate the object. keys(...
The JavaScript input interpreter - Firefox Developer Tools
y any of the following: a selector string that will be passed to document.querySelector to locate the iframe element the iframe element itself the content window inside the iframe See working with iframes. copy() New in Firefox 38. Copy the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied. Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard. clearHistory() New in Firefox 39. Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history. :screenshot New in Firefox 62. Create a screenshot of the current page with the supplied filename. If you don't supply...
Web Console remoting - Firefox Developer Tools
the $0 JSTerm helper. The response packet: { "from": "conn0.console9", "input": "document", "result": { "type": "object", "className": "HTMLDocument", "actor": "conn0.consoleObj20" "extensible": true, "frozen": false, "sealed": false }, "timestamp": 1347306273605, "exception": null, "exceptionMessage": null, "helperResult": null } exception holds the JSON-ification of the exception thrown during evaluation. exceptionMessage holds the exception.toString() result. result has the result ObjectActor instance. helperResult is anything that might come from a JSTerm helper result, JSON stuff (not content objects!). In Firefox 23: we renamed the error and errorMessage properties to exception and exceptionMessage respectively, to avoid conflict with ...
about:debugging - Firefox Developer Tools
u update the extension? If you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. For other changes, click the Reload button. This does what it says: Reloads any persistent scripts, such as background scripts Parses the manifest.json file again, so changes to permissions, content_scripts, browser_action or any other keys take effect Installed Extensions The permanently installed extensions are listed in the next section, Extensions. For each one, you see something like the following: The Inspect button, and the Extension ID and Internal UUID fields are the same as for temporary extensions. Just as it does with tem...
AuthenticatorAttestationResponse - Web APIs
c 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. This interface inherites from AuthenticatorResponse. Note: This interface is restricted to top-level contexts. Use from within an <iframe> element will not have any effect. Properties AuthenticatorAttestationResponse.clientDataJSON Secure contextRead only Client data for the authentication, such as origin and challenge. The clientDataJSON property is inherited from the AuthenticatorResponse. AuthenticatorAttestationResponse.attestationObject Secure contextRead only An ArrayBuffer containing authenticator data and an attestation statement for a newly-created key pair. Methods AuthenticatorAttestationResponse.getTra...
AuthenticatorResponse - Web APIs
a key pair. The child interfaces include information from the browser such as the challenge origin and either may be returned from PublicKeyCredential.response. Interfaces based on AuthenticatorResponse Below is a list of interfaces based on the AuthenticatorResponse interface. AuthenticatorAssertionResponse AuthenticatorAttestationResponse Properties AuthenticatorResponse.clientDataJSON A JSON string in an ArrayBuffer, representing the client data that was passed to CredentialsContainer.create() or CredentialsContainer.get(). Methods None. Examples Getting an AuthenticatorAssertionResponse var options = { challenge: new Uint8Array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publicKey": options }) .then(function (credentialInfoAssertion) { ...
Using the Beacon API - Web APIs
vent.type + "&location=" + location.href; // Send the beacon var status = navigator.sendBeacon(url, data); // Log the data and result console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status); }; The following example creates a submit handler and when that event is fired, the handler calls sendBeacon(). window.onsubmit = function send_analytics() { var data = JSON.stringify({ location: location.href, time: Date() }); navigator.sendBeacon('/analytics', data); }; WorkerNavigator.sendBeacon() The Beacon API's WorkerNavigator.sendBeacon() method works identically to the usual method, but is accessible from worker global scope. In the following example, a Worker sends a beacon using the URL and data from the global context. This code snippet i...
Blob - Web APIs
Web › API › Blob
lob on which it's called. Blob.prototype.stream() Returns a ReadableStream that can be used to read the contents of the Blob. Blob.prototype.text() Returns a promise that resolves with a USVString containing the entire contents of the Blob interpreted as UTF-8 text. Examples Creating a blob The Blob() constructor can create blobs from other objects. For example, to construct a blob from a JSON string: const obj = {hello: 'world'}; const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'}); Creating a URL representing the contents of a typed array The following code creates a JavaScript typed array and creates a new Blob containing the typed array's data. It then calls URL.createObjectURL() to convert the blob into a URL. HTML <p>This example creates a typed...
Body - Web APIs
Web › API › Body
een read. Methods Body.arrayBuffer() Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. Body.blob() Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. Body.formData() Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object. Body.json() Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. Body.text() Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text). The response is always decoded using UTF-8. Examples The example below uses a simple fetch call to grab an image and display it in...
CSSStyleSheet.insertRule() - Web APIs
e to the document (it may be better practice * to dynamically change classes, so style information can be kept in * genuine stylesheets and avoid adding extra elements to the DOM). * Note that an array is needed for declarations and rules since ECMAScript does * not guarantee a predictable object iteration order, and since CSS is * order-dependent. ...
console.log() - Web APIs
Web › API › Console › log
tput. See Outputting text to the console in the documentation of console for details. Difference between log() and dir() You might ask yourself what's the difference between console.dir() and console.log(). Another useful difference in Chrome exists when sending DOM elements to the console. Notice: console.log prints the element in an HTML-like tree console.dir prints the element in a JSON-like tree Specifically, console.log gives special treatment to DOM elements, whereas console.dir does not. This is often useful when trying to see the full representation of the DOM JS object. There's more information in the Chrome Console API reference about this and other functions. Logging objects Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj))). This way you ...
CrashReportBody - Web APIs
ing the reason for the crash. Current possible reasons are: oom: The browser ran out of memory. unresponsive: The page was killed due to being unresponsive. Examples Crash reports are generally only retrievable via endpoints set up using the Report-To header. It is difficult to retrieve a crash report via a ReportingObserver, as by that point the page would have crashed! Some sample JSON might look like this: { "type": "crash", "age": 42, "url": "https://example.com/", "user_agent": "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0", "body": { "reason": "oom" } } Note: Crash reports are always delivered to the endpoint group named default; there is currently no way to override this. If you want to receive other kinds of reports, but not cras...
DOMMatrixReadOnly - Web APIs
ntaining all 16 elements (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) which comprise the matrix. The elements are stored into the array as double-precision floating-point numbers in column-major (colexographical access access or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.) DOMMatrixReadOnly.toJSON() Returns a JSON representation of the DOMMatrixReadOnly object. DOMMatrixReadOnly.toString() Creates and returns a DOMString object which contains a string representation of the matrix in CSS matrix syntax, using the appropriate CSS matrix notation. See the matrix() CSS function for details on this syntax. For a 2D matrix, the elements a through f are listed, for a total of six values an...
DOMPointInit.x - Web APIs
Web › API › DOMPointInit › x
value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be NaN or +-Infinity). If this property is missing when the DOMPointInit object is passed into fromPoint(), the value is assumed to be 0 by default. DOMPointInit is used as an input when calling either DOMPointReadOnly.fromPoint() or DOMPoint.fromPoint(), and is returned by the DOMPointReadOnly.toJSON() and DOMPoint.toJSON() methods. Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'x' in that specification. Candidate Recommendation Initial definition ...
DOMPointInit - Web APIs
Properties DOMPointInit.x An unrestricted floating-point value indicating the x-coordinate of the point in space. This is generally the horizontal coordinate, with positive values being to the right and negative values to the left. The default value is 0. DOMPointInit.y An unrestricted floating-point number providing the point's y-coordinate. ...
DOMPointReadOnly - Web APIs
nt's depth coordinate, z. DOMPointReadOnly.w Read only The point's perspective value, w. Static methods DOMPointReadOnly.fromPoint() A static method that creates a new DOMPointReadOnly object given the coordinates provided in the specified DOMPointInit object. Methods matrixTransform() Applies a matrix transform specified as a DOMMatrixInit object to the DOMPointReadOnly object. toJSON() Returns a JSON representation of the DOMPointReadOnly object. Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMPoint' in that specification. Candidate Recommendation Latest spec version is an ED. ...
DOMQuad - Web APIs
Web › API › DOMQuad
1,p2,p3,p4 Read only are DOMPoint objects for each of the DOMQuad object's four corners. Methods DOMQuad.fromRect() Returns a new DOMQuad object based on the passed set of coordinates. DOMQuad.fromQuad() Returns a new DOMQuad object based on the passed set of coordinates. DOMQuad.getBounds() Returns a DOMRect object with the coordinates and dimensions of the DOMQuad object. DOMQuad.toJSON() Returns a JSON representation of the DOMQuad object. Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMQuad' in that specification. Candidate Recommendation Initial definition. ...
How to create a DOM tree - Web APIs
"denver"); addressElem5.setAttribute("state", "co"); addressElem5.setAttribute("country", "usa"); personElem2.appendChild(addressElem5); peopleElem.appendChild(personElem1); peopleElem.appendChild(personElem2); doc.appendChild(peopleElem); See also the DOM chapter of the XUL Tutorial. ...
ExtendableMessageEvent.data - Web APIs
yntax var myData = extendableMessageEvent.data; Value Any data type. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.lastEventId - Web APIs
yLastEventId = extendableMessageEvent.lastEventId; Value A DOMString. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.origin - Web APIs
tax var myOrigin = extendableMessageEvent.origin; Value A USVString. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.ports - Web APIs
extendableMessageEvent.ports; Value An array of MessagePort objects. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.source - Web APIs
ageEvent.source; Value A Client, ServiceWorker or MessagePort object. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
FileSystemEntry.remove() - Web APIs
The file system's state doesn't permit removing the file or directory. FileError.NOT_FOUND_ERR The file or directory doesn't exist. FileError.SECURITY_ERR The entry couldn't be removed due to permissions or other access constraints, or because there are too many calls being made on file resources. Example This example deletes a temporary work file. workingDirectory.getFile("tmp/workfile.json", {}, function(fileEntry) { fileEntry.remove(function() { /* the file was removed successfully */ }); }, handleError); Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet Explore...
GlobalEventHandlers.onerror - Web APIs
JavaScript. window.onerror = function (msg, url, lineNo, columnNo, error) { var string = msg.toLowerCase(); var substring = "script error"; if (string.indexOf(substring) > -1){ alert('Script Error: See Browser Console for Detail'); } else { var message = [ 'Message: ' + msg, 'URL: ' + url, 'Line: ' + lineNo, 'Column: ' + columnNo, 'Error object: ' + JSON.stringify(error) ].join(' - '); alert(message); } return false; }; When using the inline HTML markup (<body onerror="alert('an error occurred')">), the HTML specification requires arguments passed to onerror to be named event, source, lineno, colno, error. In browsers that have not implemented this requirement, they can still be obtained via arguments[0] through arguments[2]. Spec...
History API - Web APIs
history (that is, the pages visited in the tab or frame that the current page is loaded in). Examples The following example assigns a listener to the onpopstate property. And then illustrates some of the methods of the history object to add, replace, and move within the browser history for the current tab. ...
LargestContentfulPaint - Web APIs
estContentfulPaint.loadTime The time the element was loaded. LargestContentfulPaint.size The intrinsic size of the element returned as the area (width * height). LargestContentfulPaint.id The id of the element. This property returns an empty string when there is no id. LargestContentfulPaint.url If the element is an image, the request url of the image. Methods LargestContentfulPaint.toJSON() Returns the above properties as JSON. Examples The following example shows how to create a PerformanceObserver that listens for largest-contentful-paint entries and logs the LCP value to the console. This example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true. Note that in this examp...
LayoutShift - Web APIs
) times the distance fraction (distance moved as a fraction of viewport). LayoutShift.hadRecentInput Returns true if there was a user input in the past 500 milliseconds. LayoutShift.lastInputTime Returns the time of the most recent user input. LayoutShift.sources Returns an array of LayoutShiftAttribution objects with information on the elements that were shifted. Methods LayoutShift.toJSON() Converts the properties to JSON. Examples The following example shows how to capture layout shifts and log them to the console. Note that in this example data is only sent to the server when the user leaves the tab. // Catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativeLayoutShiftScore = 0; co...
PaymentRequest.prototype.id - Web APIs
Web › API › PaymentRequest › id
ency: "USD", value: "65.00" }, }, }; const request = new PaymentRequest(methodData, details); console.log(request.id); // super-store-order-123-12312 The id is then also available in the PaymentResponse returned from the show() method, but under the requestId attribute. const response = await request.show(); console.log(response.requestId === request.id); // And in serialized form too const json = response.toJSON(); console.log(json.requestId,response.requestId, request.id); Syntax var id = paymentRequest.id Value A DOMString. Specifications Specification Status Comment Payment Request APIThe definition of 'id' in that specification. Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is gen...
PaymentResponse.complete() - Web APIs
server using the Fetch API. It calls complete() with an answer appropriate to the status in the response. // Initialization of PaymentRequest arguments are excerpted for the // sake of brevity. ...
PaymentResponse.details - Web APIs
This data is returned by the payment app that satisfies the payment request, and must conform to the structure defined in the BasicCardResponse dictionary. Syntax var detailsObject = PaymentResponse.details; Example The following example extracts the details from the PaymentResponse object to the promise returned from PaymentRequest.show(). In a real-world implementation this data would then be sent to a payment server. ...
PaymentResponse.onpayerdetailchange - Web APIs
Candidate Recommendation Initial definition. ...
PaymentResponse: payerdetailchange event - Web APIs
} Specifications Specification Status Comment ...
PaymentResponse - Web APIs
The PaymentResponse interface of the Payment Request API is returned after a user selects a payment method and approves a payment request. Properties PaymentResponse.details Read only Secure context Returns a JSON-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer. The contents of the object depend on the payment method being used; for example, if the Basic Card payment method is used, this object must conform to the structure defined in the BasicCardResponse dictionary. PaymentResponse.methodName Read only Secure context Returns the payment method identifier for the payment method that the user selected, for example, Visa, Mastercard, Paypal, etc.. PaymentResponse.payerEmail R...
PerformanceNavigation - Web APIs
button or via the Location.reload() method. TYPE_BACK_FORWARD (2) The page was accessed by navigating into the history. TYPE_RESERVED (255) Any other way. PerformanceNavigation.redirectCount Read only An unsigned short representing the number of REDIRECTs done before reaching the page. Methods The Performance interface doesn't inherit any methods. PerformanceNavigation.toJSON() Is a jsonizer returning a json object representing the PerformanceNavigation object. Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceNavigation' in that specification. Recommendation Initial definition. ...
PerformanceNavigationTiming - Web APIs
ighResTimeStamp representing the time value equal to the time immediately after the user agent finishes the unload event of the previous document. PerformanceNavigationTiming.unloadEventStart Read only A DOMHighResTimeStamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document. Methods PerformanceNavigationTiming.toJSON() Returns a DOMString that is the JSON representation of the PerformanceNavigationTiming object. Specifications Specification Status Comment Navigation Timing Level 2The definition of 'PerformanceNavigationTiming' in that specification. Working Draft Initial definition. ...
PerformanceResourceTiming - Web APIs
ing any applied content-codings. PerformanceResourceTiming.decodedBodySizeRead only A number that is the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings. PerformanceResourceTiming.serverTimingRead only An array of PerformanceServerTiming entries containing server timing metrics. Methods PerformanceResourceTiming.toJSON() Returns a DOMString that is the JSON representation of the PerformanceResourceTiming object. Example See the example in Using the Resource Timing API. Specifications Specification Status Comment Resource Timing Level 1The definition of 'PerformanceResourceTiming' in that specification. Candidate Recommendation Initial definition. ...
PerformanceServerTiming - Web APIs
Properties PerformanceServerTiming.descriptionRead only A DOMString value of the server-specified metric description, or an empty string. PerformanceServerTiming.durationRead only A double that contains the server-specified metric duration, or value 0.0. PerformanceServerTiming.nameRead only A DOMString value of the server-specified metric name. Methods PerformanceServerTiming.toJSON() Returns a DOMString that is the JSON representation of the PerformanceServerTiming object. Example Given a server that sends the Server-Timing header, for example a node.js server like this: const http = require('http'); function requestHandler(request, response) { const headers = { 'Server-Timing': ` cache;desc="Cache Read";dur=23.2, db;dur=53, app;dur=47.2 `.
PerformanceTiming - Web APIs
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. ...
Performance API - Web APIs
can represent the value as a time in milliseconds accurate to a millisecond. Methods The Performance interface has two methods. The now() method returns a DOMHighResTimeStamp whose value that depends on the navigation start and scope. If the scope is a window, the value is the time the browser context was created and if the scope is a worker, the value is the time the worker was created. The toJSON() method returns a serialization of the Performance object, for those attributes that can be serialized. Properties The Performance interface has two properties. The timing property returns a PerformanceTiming object containing latency-related performance information such as the start of navigation time, start and end times for redirects, start and end times for responses, etc. The navigation ...
Performance Timeline - Web APIs
ype The type of performance metric (for example, "mark"). startTime A high resolution timestamp representing the starting time for the performance entry. duration A high resolution timestamp representing the time value of the duration of the performance event. (Some performance entry types have no concept of duration and this value is set to '0' for such types.) This interface includes a toJSON() method that returns the serialization of the PerformanceEntry object. The serialization is specific to the performance entry's type. Performance observers The performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's callback fu...
PopStateEvent - Web APIs
te event on page load. Chrome did until version 34, while Safari did until version 10.0. Syntax window.onpopstate = funcRef; funcRef is a handler function. ...
PublicKeyCredential.response - Web APIs
contexts and will not be available in an <iframe> for example. Syntax response = publicKeyCredential.response Value An AuthenticatorResponse object containing the data a relying party's script will receive and which should be sent to the relying party's server in order to validate the demand for creation or fetching. This object contains data from the client (AuthenticatorResponse/clientDataJSON) and from the authenticator. Examples var options = { challenge: new Uint8Array(16) /* from the server */, rp: { name: "Example CORP", id : "login.example.com" }, user: { id: new Uint8Array(16) /* from the server */, name: "jdoe@example.com", displayName: "John Doe" }, pubKeyCredParams: [ { type: "public-key", alg: -7 } ] }; navigator.cred...
PushEvent.data - Web APIs
Web › API › PushEvent › data
tion. Syntax var myPushData = PushEvent.data; Value A PushMessageData object. Examples The following example takes data from a PushEvent and displays it on all of the service workers' clients. ...
PushEvent - Web APIs
Web › API › PushEvent
e PushSubscription. Methods Inherits methods from its parent, ExtendableEvent. Examples The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
PushManager.register() - Web APIs
ul, the request's result will be a string, which is the endpoint URL. Note: if you do not need the URL any more, please use Pushmanager.unregister() to clean up after yourself. Example var req = navigator.push.register(); req.onsuccess = function(e) { var endpoint = req.result; debug("New endpoint: " + endpoint ); } req.onerror = function(e) { debug("Error getting a new endpoint: " + JSON.stringify(e)); } Specification Specification Status Comment Push API Working Draft Defines the PushManager interface. ...
PushManager.unregister() - Web APIs
owing properties: pushEndpoint A string representing the URL of the unregistered endpoint. version Undefined when unregister.onsuccess is called. Example var req = navigator.push.unregister(pushEndpoint); req.onsuccess = function(e) { var endpoint = req.result; debug("Unregistered endpoint: " + endpoint ); } req.onerror = function(e) { debug("Error unregistering the endpoint: " + JSON.stringify(e)); } Specification Specification Status Comment Push API Working Draft Defines the PushManager interface. ...
PushSubscription - Web APIs
An object containing the options used to create the subscription. PushSubscription.subscriptionId Read only A DOMString containing the subscription ID associated with the push subscription. Methods PushSubscription.getKey() Returns an ArrayBuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data. PushSubscription.toJSON() Standard serializer -- returns a JSON representation of the subscription properties. PushSubscription.unsubscribe() Starts the asynchronous process of unsubscribing from the push service, returning a Promise that resolves to a Boolean when the current subscription is successfully unregistered. Example navigator.serviceWorker.ready.then(function(reg) { reg.pushManager.getSubscription().t...
RTCIceCandidate - Web APIs
ype enumerated type. usernameFragment Read only A DOMString containing a randomly-generated username fragment ("ice-ufrag") which ICE uses for message integrity along with a randomly-generated password ("ice-pwd"). You can use this string to verify generations of ICE generation; each generation of the same ICE process will use the same usernameFragment, even across ICE restarts. Methods toJSON() Given the RTCIceCandidate's current configuration, toJSON() returns a DOMString containing a JSON representation of that configuration in the form of a RTCIceCandidateInit object. Examples For examples, see the article Signaling and video calling, which demonstrates the entire process. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication ...
RTCIceCandidateInit - Web APIs
Properties candidate Optional The ICE candidate-attribute. ...
RTCPeerConnection.createAnswer() - Web APIs
f code taken from the code that goes with the article Signaling and video calling. This code comes from the handler for the message sent to carry an offer to another peer across the signaling channel. Keep in mind that this is part of the signaling process, the transport layer for which is an implementation detail that's entirely up to you. In this case, a WebSocket connection is used to send a JSON message with a type field with the value "video-answer" to the other peer, carrying the answer to the device which sent the offer to connect. The contents of the object being passed to the sendToServer() function, along with everything else in the promise fulfillment handler, depend entirely on your design pc.createAnswer().then(function(answer) { return pc.setLocalDescription(answer); }) .th...
RTCPeerConnection.createOffer() - Web APIs
to generate the offer failed for some reason. Example Here we see a handler for the negotiationneeded event which creates the offer and sends it to the remote system over a signaling channel. Note: Keep in mind that this is part of the signaling process, the transport layer for which is an implementation detail that's entirely up to you. In this case, a WebSocket connection is used to send a JSON message with a type field with the value "video-offer" to the other peer. The contents of the object being passed to the sendToServer() function, along with everything else in the promise fulfillment handler, depend entirely on your design. myPeerConnection.createOffer().then(function(offer) { return myPeerConnection.setLocalDescription(offer); }) .then(function() { sendToServer({...
Resource Timing API - Web APIs
e Timing API includes two methods that extend the Performance interface. The clearResourceTimings() method removes all "resource" type performance entries from the browser's resource performance entry buffer. The setResourceTimingBufferSize() method sets the resource performance entry buffer size to the specified number of resource performance entries. The PerformanceResourceTiming interface's toJSON() method returns a JSON serialization of a "resource" type performance entry. Implementation status As shown in the PerformanceResourceTiming interface's Browser Compatibility table, most of these interfaces are broadly implemented by desktop browsers. However, note that some properties have little to no implementation so see each property's "Browser compatibility" section for more specific int...
Response - Web APIs
Web › API › Response
ds available to it: Body.arrayBuffer() Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. Body.blob() Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. Body.formData() Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object. Body.json() Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. Body.text() Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text). Examples In our basic fetch example (run example live) we use a simple fetch() call to grab an image and display it in an <img> el...
Using the Screen Capture API - Web APIs
mping configuration information For informational purposes, the startCapture() method shown above calls a method named dumpOptions(), which outputs the current track settings as well as the constraints that were placed upon the stream when it was created. function dumpOptionsInfo() { const videoTrack = videoElem.srcObject.getVideoTracks()[0]; console.info("Track settings:"); console.info(JSON.stringify(videoTrack.getSettings(), null, 2)); console.info("Track constraints:"); console.info(JSON.stringify(videoTrack.getConstraints(), null, 2)); } The track list is obtained by calling getVideoTracks() on the capture'd screen's MediaStream. The settings currently in effect are obtained using getSettings() and the established constraints are gotten with getConstraints() HTML The HTML ...
ServiceWorkerGlobalScope.onpush - Web APIs
d displays it on all of the service worker's clients. ...
ServiceWorkerGlobalScope: push event - Web APIs
The push event is sent to a service worker's global scope (represented by the ServiceWorkerGlobalScope interface) when the service worker has received a push message. Bubbles No Cancelable No Interface PushEvent Event handler property onpush Example This example sets up a handler for push events that takes JSON data, parses it, and dispatches the message for handling based on information contained within the message. self.addEventListener("push", event => { let message = event.data.json(); switch(message.type) { case "init": doInit(); break; case "shutdown": doShutdown(); break; } }, false); Specifications Specification Status Comment Push APIThe definition of 'push' ...
StyleSheet.media - Web APIs
Web › API › StyleSheet › media
ctype html> <html> <head> <link rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style rel="stylesheet" type="text/css" media="screen, print"> body { background-color: snow; } </style> </head> <body> <script> for (var iSheetIndex = 0; iSheetIndex < document.styleSheets.length; iSheetIndex++) { console.log('document.styleSheets[' + String(iSheetIndex) + '].media: ' + JSON.stringify(document.styleSheets[iSheetIndex].media)); if (iSheetIndex === 0) document.styleSheets[iSheetIndex].media.appendMedium('handheld'); if (iSheetIndex === 1) document.styleSheets[iSheetIndex].media.deleteMedium('print'); console.log('document.styleSheets[' + String(iSheetIndex) + '].media: ' + JSON.stringify(document.styleSheets[iSheetIndex].media)); } /* will log: docume...
SubtleCrypto.unwrapKey() - Web APIs
f encrypt + export. Syntax const result = crypto.subtle.unwrapKey( format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages ); Parameters format is a string describing the data format of the key to unwrap. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. jwk: JSON Web Key format. wrappedKey is an ArrayBuffer containing the wrapped key in the given format. unwrappingKey is the CryptoKey to use to decrypt the wrapped key. The key must have the unwrapKey usage set. unwrapAlgo is an object specifying the algorithm to be used to encrypt the exported key, and any extra parameters as required: To use RSA-OAEP, pass an RsaOaepParams object. To use...
SubtleCrypto - Web APIs
sword and later derive the same key from the same password to decrypt the data. Importing and exporting keys To make keys available outside your app, you need to export the key, and that's what exportKey() is for. You can choose one of a number of export formats. The inverse of exportKey() is importKey(). You can import keys from other systems, and support for standard formats like PKCS #8 and JSON Web Key helps you do this. The exportKey() function exports the key in an unencrypted format. If the key is sensitive you should use wrapKey(), which exports the key and then encrypts it using another key; the API calls a "key-wrapping key". The inverse of wrapKey() is unwrapKey(), which decrypts then imports the key. Storing keys CryptoKey objects can be stored using the structured clone alg...
msManipulationViewsEnabled - Web APIs
the future. ...
TransformStream - Web APIs
controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)) else if (Array.isArray(chunk) && chunk.every(value => typeof value === 'number')) controller.enqueue(new Uint8Array(chunk)) else if ('function' === typeof chunk.valueOf && chunk.valueOf() !== chunk) this.transform(chunk.valueOf(), controller) // hack else if ('toJSON' in chunk) this.transform(JSON.stringify(chunk), controller) break case 'symbol': controller.error("Cannot send a symbol as a chunk part") break case 'undefined': controller.error("Cannot send undefined as a chunk part") default: controller.enqueue(this.textencoder.encode(String(chunk))) break }, flush() { /* do any destructor ...
URL - Web APIs
Web › API › URL
, beginning with the leading ? character. searchParams Read only A URLSearchParams object which can be used to access the individual query parameters found in search. username A USVString containing the username specified before the domain name. Methods toString() Returns a USVString containing the whole URL. It is a synonym for URL.href, though it can't be used to modify the value. toJSON() Returns a USVString containing the whole URL. It returns the same string as the href property. Static methods createObjectURL() Returns a DOMString containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser. revokeObjectURL() Revokes an object URL previously created using URL.createObjectURL(). Usa...
Lifetime of a WebRTC session - Web APIs
connecting two devices, it doesn't make sense for them to have to use another one, defined by the specification, just for WebRTC. Since WebRTC doesn't live in a vacuum, there is likely other connectivity in play, so it makes sense to avoid having to add additional connection channels for signaling if an existing one can be used. In order to exchange signaling information, you can choose to send JSON objects back and forth over a WebSocket connection, or you could use XMPP or SIP over an appropriate channel, or you could use XMLHttpRequest over HTTPS with polling, or any other combination of technologies you can come up with. You could even use email as the signaling channel. It's also worth noting that the channel for performing signaling doesn't even need to be over the network. One peer c...
Writing WebSocket servers - Web APIs
c-Websocket-Protocol header. If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants. If you want your server to obey certain subprotocols, then naturally you'll need extra code on the server. Let's imagine we're using a subprotocol json. In this subprotocol, all data is passed as JSON. If the client solicits this protocol and the server wants to use it, the server needs to have a JSON parser. Practically speaking, this will be part of a library, but the server needs to pass the data around. Tip: To avoid name conflict, it's recommended to make your subprotocol name part of a domain string. If you are building a custom chat app...
The WebSocket API (WebSockets) - Web APIs
e-way connections) for Node.js Server and Client. SignalR: SignalR will use WebSockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same. Caddy: A web server capable of proxying arbitrary commands (stdin/stdout) as a websocket. ws: a popular WebSocket client & server library for Node.js. jsonrpc-bidirectional: Asynchronous RPC which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client). cowboy: Cowboy is a small, fast and modern HTTP server for Erlang/OTP with WebSocket support. Related Topics AJAX JavaScript Specifications Specification Status Comments ...
WebXR Device API - Web APIs
w to efficiently manage the input devices being used to control the WebXR session, and how to receive and process user inputs from those devices. Targeting and hit detection How to use an input source's targeting ray mode and targeting ray space to display a targeting ray, identify targeted surfaces or objects, and perform related tasks. Using WebXR input profiles A guide to interpreting the JSON data provided by the WebXR Input Profiles Registry, which can be used to determine what options and controls are available on the user's available input devices. Supporting advanced controllers and gamepads in WebXR applications WebXR uses the Gamepad object to describe the controls available on complex input devices (such as hand controllers with multiple buttons and/or axes) and gamepad-like ...
Using the Web Storage API - Web APIs
As you can see above, the event object associated with this event has a number of properties containing useful information -- the key of the data that changed, the old value before the change, the new value after that change, the URL o...
Functions and classes available to Web Workers - Web APIs
This article provides a list of those. Workers run in another global context, DedicatedWorkerGlobalScope, different from the current window. By default, methods and properties of Window are not available to them, but DedicatedWorkerGlobalScope, like Window, implements WindowTimers and WindowBase64. ...
Window.name - Web APIs
Web › API › Window › name
tab"; </script> <a href="url2" target="other-tab">This link will be opened in the other tab.</a> Notes The name of the window is used primarily for setting targets for hyperlinks and forms. Browsing contexts do not need to have names. It has also been used in some frameworks for providing cross-domain messaging (e.g., SessionVars and Dojo's dojox.io.windowName) as a more secure alternative to JSONP. Modern web applications hosting sensitive data should, however, not rely on window.name for cross-domain messaging but instead utilize the postMessage API. window.name will convert all values to their string representations by using the toString method. Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.name' in that specificatio...
WindowEventHandlers.onpopstate - Web APIs
ng history.back() in JavaScript), when navigating between two history entries for the same document. Syntax window.onpopstate = funcRef; funcRef is a handler function. ...
Using XMLHttpRequest - Web APIs
License, version 3 or later. |*| https://www.gnu.org/licenses/gpl-3.0-standalone.html |*| |*| Syntax: |*| |*| AJAXSubmit(HTMLFormElement); \*/ var AJAXSubmit = (function () { function ajaxSuccess () { /* console.log("AJAXSubmit - Success!"); */ console.log(this.responseText); /* you can get the serialized data through the "submittedData" custom property: */ /* console.log(JSON.stringify(this.submittedData)); */ } function submitData (oData) { /* the AJAX request... */ var oAjaxReq = new XMLHttpRequest(); oAjaxReq.submittedData = oData; oAjaxReq.onload = ajaxSuccess; if (oData.technique === 0) { /* method is GET */ oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/, oData.segments.length > 0 ? "?" + oData.segments.joi...
XMLHttpRequest.response - Web APIs
g is treated the same as "text", the default type. arraybuffer The response is a JavaScript ArrayBuffer containing binary data. blob The response is a Blob object containing the binary data. document The response is an HTML Document or XML XMLDocument, as appropriate based on the MIME type of the received data. See HTML in XMLHttpRequest to learn more about using XHR to fetch HTML content. json The response is a JavaScript object created by parsing the contents of received data as JSON. text The response is a text in a DOMString object. ms-stream The response is part of a streaming download; this response type is only allowed for download requests, and is only supported by Internet Explorer. Example This example presents a function, load(), which loads and processes a page ...
XMLHttpRequest.responseType - Web APIs
g is treated the same as "text", the default type. arraybuffer The response is a JavaScript ArrayBuffer containing binary data. blob The response is a Blob object containing the binary data. document The response is an HTML Document or XML XMLDocument, as appropriate based on the MIME type of the received data. See HTML in XMLHttpRequest to learn more about using XHR to fetch HTML content. json The response is a JavaScript object created by parsing the contents of received data as JSON. text The response is a text in a DOMString object. ms-stream The response is part of a streaming download; this response type is only allowed for download requests, and is only supported by Internet Explorer. Exceptions InvalidAccessError An attempt was made to change the value of responseTy...
XMLHttpRequestResponseType - Web APIs
g is treated the same as "text", the default type. arraybuffer The response is a JavaScript ArrayBuffer containing binary data. blob The response is a Blob object containing the binary data. document The response is an HTML Document or XML XMLDocument, as appropriate based on the MIME type of the received data. See HTML in XMLHttpRequest to learn more about using XHR to fetch HTML content. json The response is a JavaScript object created by parsing the contents of received data as JSON. text The response is a text in a DOMString object. ms-stream The response is part of a streaming download; this response type is only allowed for download requests, and is only supported by Internet Explorer. Deprecated values moz-chunked-arraybuffer A Firefox-only value which instructs ...
viewport-fit - CSS: Cascading Style Sheets
page is viewable. contain The viewport is scaled to fit the largest rectangle inscribed within the display. cover The viewport is scaled to fill the device display. It is highly recommended to make use of the safe area inset variables to ensure that important content doesn't end up outside the display. This descriptor hasn't been added to https://github.com/mdn/data/blob/master/css/at-rules.json yet. Accessibility concerns When using the viewport-fit descriptor, one must keep in mind that not all device displays are rectangular, and should therefore make use of the safe area inset variables. Formal definition Related at-rule@viewportInitial valueautoComputed valueas specified Formal syntax auto | contain | cover Examples Scaling viewport to fit device display @viewport { viewp...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
Web › HTML › Element › abbr
pec</abbr>) is a document that outlines in detail how a technology or API is intended to function and how it is accessed.</p> Result Accessibility concerns Spelling out the acronym or abbreviation in full the first time it is used on a page is beneficial for helping people understand it, especially if the content is technical or industry jargon. Example <p>JavaScript Object Notation (<abbr>JSON</abbr>) is a lightweight data-interchange format.</p> This is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are new to the language, and people with cognitive concerns. Specifications Specification Status Comment HTML Living StandardThe definition of '<abbr>' in that specification. Living S...
itemref - HTML: Hypertext Markup Language
fines a separate item while keeping the properties in the cells. Example HTML <div itemscope id="amanda" itemref="a b"></div> <p id="a">Name: <span itemprop="name">Amanda</span> </p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>Band: <span itemprop="name">Jazz Band</span> </p> <p>Size: <span itemprop="size">12</span> players</p> </div> Structured data (in JSON-LD format) { "@id": "amanda", "name": "Amanda", "band": { "@id": "b", "name": "Jazz Band", "size": 12 } } Result Specifications Specification Status Comment HTML MicrodataThe definition of 'itemref' in that specification. Working Draft HTML Living StandardThe definition of 'itemref' in that specification. Living Standard ...
Microformats - HTML: Hypertext Markup Language
preferably canonical URL p-street-address street number + name p-locality city/town/village p-country-name country name Nested h-card example <div class="h-card"> <a class="p-name u-url" href="http://blog.lizardwrangler.com/" >Mitchell Baker</a> (<a class="p-org h-card" href="http://mozilla.org/" >Mozilla Foundation</a>) </div> Parsed JSON: { "items": [{ "type": ["h-card"], "properties": { "name": ["Mitchell Baker"], "url": ["http://blog.lizardwrangler.com/"], "org": [{ "value": "Mozilla Foundation", "type": ["h-card"], "properties": { "name": ["Mozilla Foundation"], "url": ["http://mozilla.org/"] } }] } }] } Note: the nested h-card has implied 'name' and 'url' properties, j...
Common MIME types - HTTP
lication/java-archive .jpeg .jpg JPEG images image/jpeg .js JavaScript text/javascript, per the following specifications: https://html.spec.whatwg.org/multipage/#scriptingLanguages https://html.spec.whatwg.org/multipage/#dependencies:willful-violation https://datatracker.ietf.org/doc/draft-ietf-dispatch-javascript-mjs/ .json JSON format application/json .jsonld JSON-LD format application/ld+json .mid .midi Musical Instrument Digital Interface (MIDI) audio/midi audio/x-midi .mjs JavaScript module text/javascript .mp3 MP3 audio audio/mpeg .mpeg MPEG Video video/mpeg .mpkg Apple Installer Package application/vnd.apple.ins...
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own. An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json. For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers. The CORS mechanism supp...
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
ing, you need to specify the report-uri policy directive, providing at least one URI to which to deliver the reports: Content-Security-Policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi Then you need to set up your server to receive the reports; it can store or process them in whatever manner you determine is appropriate. Violation report syntax The report JSON object contains the following data: blocked-uri The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port. disposition Either "enforce" or "report" depending on whether the Content-Security-Policy-Report-Only header ...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
ookies available to JavaScript can be stolen through XSS. Security Information should be stored in cookies with the understanding that all cookie values are visible to, and can be changed by, the end-user. Depending on the application, it may be desirable to use an opaque identifier which is looked-up by the server or to investigate alternative authentication/confidentiality mechanisms such as JSON Web Tokens. Ways to mitigate attacks involving cookies: Use the HttpOnly attribute to prevent access to cookie values via JavaScript. Cookies that are used for sensitive information (such as indicating authentication) should have a short lifetime, with the SameSite attribute set to Strict or Lax. (See SameSite cookies, above.) In browsers that support SameSite, this has the effect of ensuri...
Cross-Origin Resource Policy (CORP) - HTTP
rly 2018, two side-channel hardware vulnerabilities known as Meltdown and Spectre were disclosed. These vulnerabilities allowed sensitive data disclosure due to a race condition which arose as part of speculative execution functionality, designed to improve performance. In response, Chromium shipped Cross-Origin Read Blocking, which automatically protects certain resources (of Content-Type HTML, JSON and XML) against cross-origin reads. If the application does not serve a no-sniff directive, Chromium will attempt to guess the Content-Type and apply the protection anyway. Cross-Origin Resource Policy is an opt-in response header which can protect any resource; there is no need for browsers to sniff MIME types. Usage Note: Due to a bug in Chrome, setting Cross-Origin-Resource-Policy can bre...
CSP: report-to - HTTP
agent to store reporting endpoints for an origin. Content-Security-Policy: ...; report-to groupname The directive has no effect in and of itself, but only gains meaning in combination with other directives. CSP version 1 Directive type Reporting directive This directive is not supported in the <meta> element. Syntax Content-Security-Policy: report-to <json-field-value>; Examples See Content-Security-Policy-Report-Only for more information and examples. Report-To: { "group": "csp-endpoint", "max_age": 10886400, "endpoints": [ { "url": "https://example.com/csp-reports" } ] }, { "group": "hpkp-endpoint", "max_age": 10886400, "endpoints": [ { "u...
Content-Security-Policy - HTTP
igation by any means, including <form> (if form-action is not specified), <a>, window.location, window.open, etc. Reporting directives Reporting directives control the reporting process of CSP violations. See also the Content-Security-Policy-Report-Only header. report-uri Instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. Though the report-to directive is intended to replace the deprecated report-uri directive, report-to is not supported in most browsers yet. So for compatibility with current browsers while also adding forward compatibility when browsers get report-to support, you can specify both report-uri and report-to: Content-Security-Policy: ...
HTTP headers - HTTP
Web › HTTP › Headers
n-Resource-Policy (CORP) Prevents other domains from reading the response of the resources to which this header is applied. Content-Security-Policy (CSP) Controls resources the user agent is allowed to load for a given page. Content-Security-Policy-Report-Only Allows web developers to experiment with policies by monitoring, but not enforcing, their effects. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI. Expect-CT Allows sites to opt in to reporting and/or enforcement of Certificate Transparency requirements, which prevents the use of misissued certificates for that site from going unnoticed. When a site enables the Expect-CT header, they are requesting that Chrome check that any certificate for that site appears in public CT logs. ...
A re-introduction to JavaScript (JS tutorial) - JavaScript
rt is a JavaScript string, while the value can be any JavaScript value -- including more objects. This allows you to build data structures of arbitrary complexity. There are two basic ways to create an empty object: var obj = new Object(); And: var obj = {}; These are semantically equivalent; the second is called object literal syntax and is more convenient. This syntax is also the core of JSON format and should be preferred at all times. Object literal syntax can be used to initialize an object in its entirety: var obj = { name: 'Carrot', for: 'Max', // 'for' is a reserved word, use '_for' instead. details: { color: 'orange', size: 12 } }; Attribute access can be chained together: obj.details.color; // orange obj['details']['size']; // 12 The following example cr...
JavaScript data types and data structures - JavaScript
f them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time. Usually, to bind data to a DOM node, one could set properties directly on the object, or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object. Structured data: JSON JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript, but used by many programming languages. JSON builds universal data structures. See JSON and JSON for more details. More objects in the standard library JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects. Determining types...
Grammar and types - JavaScript
See String for details on String objects. Using special characters in strings In addition to ordinary characters, you can also include special characters in strings, as shown in the following example. ...
JavaScript technologies overview - JavaScript
ling mechanisms (throw, try...catch, ability to create user-defined Error types) Types (boolean, number, string, function, object, ...) The global object. In a browser, this global object is the window object, but ECMAScript only defines the APIs not specific to browsers, e.g. parseInt, parseFloat, decodeURI, encodeURI... A prototype-based inheritance mechanism Built-in objects and functions (JSON, Math, Array.prototype methods, Object introspection methods, etc.) Strict mode Browser support As of October 2016, the current versions of the major Web browsers implement ECMAScript 5.1 and ECMAScript 2015, but older versions (still in use) implement ECMAScript 5 only. Future The major 6th Edition of ECMAScript was officially approved and published as a standard on June 17, 2015 by the EC...
JavaScript error reference - JavaScript
cal declaration "x" before initializationReferenceError: deprecated caller or arguments usageReferenceError: invalid assignment left-hand sideReferenceError: reference to undefined property "x"SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecatedSyntaxError: "use strict" not allowed in function with non-simple parametersSyntaxError: "x" is a reserved identifierSyntaxError: JSON.parse: bad parsingSyntaxError: Malformed formal parameterSyntaxError: Unexpected tokenSyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# insteadSyntaxError: a declaration in the head of a for-of loop can't have an initializerSyntaxError: applying the "delete" operator to an unqualified name is deprecatedSyntaxError: for-in loop head declarations may not have initializersS...
Array.prototype.shift() - JavaScript
y not behave in any meaningful manner. Array.prototype.pop() has similar behavior to shift, but applied to the last element in an array. Examples Removing an element from an array The following code displays the myFish array before and after removing its first element. It also displays the removed element: var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myFish before:', JSON.stringify(myFish)); // myFish before: ['angel', 'clown', 'mandarin', 'surgeon'] var shifted = myFish.shift(); console.log('myFish after:', myFish); // myFish after: ['clown', 'mandarin', 'surgeon'] console.log('Removed this element:', shifted); // Removed this element: angel Using shift() method in while loop The shift() method is often used in condition inside while loop. In the following ...
Array.prototype.slice() - JavaScript
Honda is changed to purple, both arrays reflect the change. // Using slice, create newCar from myCar. let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } } let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'] let newCar = myCar.slice(0, 2) // Display the values of myCar, newCar, and the color of myHonda // referenced from both arrays. console.log('myCar = ' + JSON.stringify(myCar)) console.log('newCar = ' + JSON.stringify(newCar)) console.log('myCar[0].color = ' + myCar[0].color) console.log('newCar[0].color = ' + newCar[0].color) // Change the color of myHonda. myHonda.color = 'purple' console.log('The new color of my Honda is ' + myHonda.color) // Display the color of myHonda referenced from both arrays. console.log('myCar[0].color = ' + myCar[0].color...
Date - JavaScript
ording to universal time. Date.prototype.setYear() Sets the year (usually 2-3 digits) for a specified date according to local time. Use setFullYear() instead. Date.prototype.toDateString() Returns the "date" portion of the Date as a human-readable string like 'Thu Apr 12 2018'. Date.prototype.toISOString() Converts a date to a string following the ISO 8601 Extended Format. Date.prototype.toJSON() Returns a string representing the Date using toISOString(). Intended for use by JSON.stringify(). Date.prototype.toGMTString() Returns a string representing the Date based on the GMT (UTC) time zone. Use toUTCString() instead. Date.prototype.toLocaleDateString() Returns a string with a locality sensitive representation of the date portion of this date based on system settings. Date.protot...
Intl.Locale.prototype.toString() - JavaScript
calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to JavaScript. Calling the toString method on a Locale object will return the identifier string for that particular Locale. The toString method allows Locale instances to be provided as an argument to existing Intl constructors, serialized in JSON, or any other context where an exact string representation is useful. Examples Using toString let myLocale = new Intl.Locale("fr-Latn-FR", {hourCycle: "h24", calendar: "gregory"}); console.log(myLocale.baseName); // Prints "fr-Latn-FR" console.log(myLocale.toString()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h24" Specifications Specification ECMAScript Internationalizati...
Number - JavaScript
example shows the minimum and maximum integer values that can be represented as Number object. (More details on this are described in the ECMAScript standard, chapter 6.1.6 The Number Type.) const biggestInt = Number.MAX_SAFE_INTEGER // (253 - 1) => 9007199254740991 const smallestInt = Number.MIN_SAFE_INTEGER // -(253 - 1) => -9007199254740991 When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them to Number type. A possible workaround is to use String instead. Larger numbers can be represented using the BigInt type. Using Number to convert a Date object The following example converts the Date object to a numerical value using Number as a function: let d = new Date('December ...
Promise.prototype.finally() - JavaScript
) will be rejected with 3. Note: A throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. Examples Using finally let isLoading = true; fetch(myRequest).then(function(response) { var contentType = response.headers.get("content-type"); if(contentType && contentType.includes("application/json")) { return response.json(); } throw new TypeError("Oops, we haven't got JSON!"); }) .then(function(json) { /* process your JSON further */ }) .catch(function(error) { console.error(error); /* this line can also throw, e.g. when console = {} */ }) .finally(function() { isLoading = false; }); Please do not add polyfills on MDN pages. For more details, refer to: https://di...
Promise.prototype.then() - JavaScript
en if the prior then's promise rejects"); }); You can also use chaining to implement one function with a Promise-based API on top of another such function. function fetch_current_data() { // The fetch() API returns a Promise. This function // exposes a similar API, except the fulfillment // value of this function's Promise has had more // work done on it. return fetch('current-data.json').then(response => { if (response.headers.get('content-type') != 'application/json') { throw new TypeError(); } var j = response.json(); // maybe do something with j return j; // fulfillment value given to user of // fetch_current_data().then() }); } If onFulfilled returns a promise, the return value of then will be resolved/rejected by the promise. fu...
Symbol - JavaScript
ymbols and for...in iteration Symbols are not enumerable 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] ...
uneval() - JavaScript
Description uneval() is a top-level function and is not associated with any object. ...
Standard built-in objects - JavaScript
rray Float64Array BigInt64Array BigUint64Array Keyed collections These objects represent collections which use keys. The iterable collections (Map and Set) contain elements which are easily iterated in the order of insertion. Map Set WeakMap WeakSet Structured data These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON). ArrayBuffer SharedArrayBuffer Atomics DataView JSON Control abstraction objects Control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example). Promise Generator GeneratorFunction AsyncFunction Reflection Reflect Proxy Internationalization Additions to the ECMAScript core for language-sensitive functionaliti...
Lexical grammar - JavaScript
ion. [1954, 1974, 1990, 2014] String literals A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for these closing quote code points: U+005C \ (backslash), U+000D <CR>, and U+000A <LF>. Prior to the proposal to make all JSON text valid ECMA-262, U+2028 <LS> and U+2029 <PS>, were also disallowed from appearing unescaped in string literals. Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded. 'foo' "bar" Hexadecimal escape sequences Hexadecimal escape sequences consist of \x fol...
for await...of - JavaScript
responseSize = 0; // The for-await-of loop. Async iterates over each portion of the response. for await (const chunk of streamAsyncIterable(response.body)) { // Incrementing the total response length. responseSize += chunk.length; } console.log(`Response Size: ${responseSize} bytes`); // expected output: "Response Size: 1071472" return responseSize; } getResponseSize('https://jsonplaceholder.typicode.com/photos'); Iterating over sync iterables and generators for await...of loop also consumes sync iterables and generators. In that case it internally awaits emitted values before assign them to the loop control variable. function* generator() { yield 0; yield 1; yield Promise.resolve(2); yield Promise.resolve(3); yield 4; } (async function() { for await (let n...
try...catch - JavaScript
this very common expected error } else { throw e; // re-throw the error unchanged } } The exception identifier When an exception is thrown in the try-block, exception_var (i.e., the e in catch (e)) holds the exception value. You can use this identifier to get information about the exception that was thrown. This identifier is only available in the catch-block's scope. function isValidJSON(text) { try { JSON.parse(text); return true; } catch { return false; } } The finally-block The finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. Note that the finally-block executes regardless of whether an exception is thrown. Also, if an exception is thrown, the s...
JavaScript reference - JavaScript
Number BigInt Math Date Text processing String RegExp Indexed Collections Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array Keyed collections Map Set WeakMap WeakSet Structured data ArrayBuffer SharedArrayBuffer Atomics DataView JSON Control abstraction Promise Generator GeneratorFunction AsyncFunction Reflection Reflect Proxy Internationalization Intl Intl.Collator Intl.DateTimeFormat Intl.DisplayNames Intl.ListFormat Intl.Locale Intl.NumberFormat Intl.PluralRules Intl.RelativeTimeFormat WebAssembly WebAssembly WebAssembly.Module WebAssembly.Instance WebAss...
JavaScript
arrays provide a mechanism for accessing raw binary data. Memory Management Memory life cycle and garbage collection in JavaScript. Concurrency model and Event Loop JavaScript has a concurrency model based on an "event loop". Reference Browse the complete JavaScript reference documentation. Standard objects Get to know standard built-in objects Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String, Map, Set, WeakMap, WeakSet, and others. Expressions and operators Learn more about the behavior of JavaScript's operators instanceof, typeof, new, this, the operator precedence, and more. Statements and declarations Learn how do-while, for-in, for-of, try-catch, let, var, const, if-else, switch, and more JavaScript statements and keywords work. Function...
Introduction to progressive web apps - Progressive web apps (PWAs)
em special capabilities. Some of the capabilities have already been enabled on certain web-based platforms by proprietary technologies like Open Graph, which provides a format for specifying similar metadata in the HTML <head> block using <meta> tags. The relevant web standard here is the Web app manifest, which defines features of an app such as name, icon, splash screen, and theme colors in a JSON-formatted manifest file. This is for use in contexts such as app listings and device home screens. Installability A core part of the web app experience is for users to have app icons on their home screen, and be able to tap to open apps into their own native container that feels nicely integrated with the underlying platform. Modern web apps can have this native app feel via properties set i...
Structural overview of progressive web apps - Progressive web apps (PWAs)
eturn caches.open(cacheName).then(function(cache) { console.log('[Service Worker] Caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return response; }); }); }) ); }); Auxiliary JavaScript file: games.js The games data for this app example is provided in a JavaScript source file called games.js. Other apps might use JSON or other formats for this data. var games = [ { slug: 'lost-in-cyberspace', name: 'Lost in Cyberspace', author: 'Zosia and Bartek', twitter: 'bartaz', website: '', github: 'github.com/bartaz/lost-in-cyberspace' }, { slug: 'vernissage', name: 'Vernissage', author: 'Platane', twitter: 'platane_', we...
Progressive web apps (PWAs)
features related to a PWA such as geolocation and even service workers are available only once the app has been loaded using HTTPS. Service workers A service worker is a script that allows intercepting and control of how a web browser handles its network requests and asset caching. With service workers, web developers can create reliably fast web pages and offline experiences. Manifest file A JSON file that controls how your app appears to the user and ensures that progressive web apps are discoverable. It describes the name of the app, the start URL, icons, and all of the other details necessary to transform the website into an app-like format. PWA advantages PWAs should be discoverable, installable, linkable, network independent, progressive, re-engageable, responsive, and safe. To fi...
Tutorials
n objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it. Client-side web APIs When writing client-side JavaScript for websites or applications, you won't go very far before you start to use APIs -- interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other websites or services. In this module, we will explore what APIs are, and how to use some of t...
XPath
es JXON could represent the most practical way and valid alternative to XPath. View All... Tools ChroPath XPath panel that integrates tightly into FireBug, providing an editor and inspector (FireFox Add-On). XMLQuire (formerly known as SketchPath) A Graphical XPath Builder/Debugger(.NET). XPath tester An online XPath Builder/Debugger. Related Topics XSLT, XQuery, XML, DOM, JXON, JSONPath Comparison of CSS Selectors and XPath ...