Search completed in 1.68 seconds.
419 results for "JSON":
Your results are loading. Please wait...
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.
...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.
... objective: to understand how to work with data stored in json, and create your own json objects.
...And 42 more matches
nsIJSON
dom/interfaces/json/nsijson.idlscriptable this interface provides a convenient way to encode and decode json strings from javascript code.
...however, you should use native json instead if at all possible.
... implemented by: @mozilla.org/dom/json;1.
...And 32 more matches
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.
... 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.
...And 29 more matches
JSON - JavaScript
the json object contains methods for parsing javascript object notation (json) and converting values to json.
... 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.
...And 12 more matches
JSON.parse() - JavaScript
the json.parse() method parses a json string, constructing the javascript value or object described by the string.
... syntax json.parse(text[, reviver]) parameters text the string to parse as json.
... see the json object for a description of json syntax.
...And 10 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.
... creating a manifest the package.json file is initially generated in your add-on's root directory the first time you run jpm init.
...And 9 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.
... 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.
...And 7 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.
...And 6 more matches
SyntaxError: JSON.parse: bad parsing - JavaScript
the javascript exceptions thrown by json.parse() occur when string failed to be parsed as json.
... message syntaxerror: json.parse: unterminated string literal syntaxerror: json.parse: bad control character in string literal syntaxerror: json.parse: bad character in string literal syntaxerror: json.parse: bad unicode escape syntaxerror: json.parse: bad escape character syntaxerror: json.parse: unterminated string syntaxerror: json.parse: no number after minus sign syntaxerror: json.parse: unexpected non-digit syntaxerror: json.parse: missing digits after decimal point syntaxerror: json.parse: unterminated fractional number syntaxerror: json.parse: missing digits after exponent indicator syntaxerror: json.parse: missing digits after exponent sign syntaxerror: json.parse: exponent part is missing a number syntaxerror: json.parse: unexpected end of data syntaxerror: json.parse: unexpected k...
...eyword syntaxerror: json.parse: unexpected character syntaxerror: json.parse: end of data while reading object contents syntaxerror: json.parse: expected property name or '}' syntaxerror: json.parse: end of data when ',' or ']' was expected syntaxerror: json.parse: expected ',' or ']' after array element syntaxerror: json.parse: end of data when property name was expected syntaxerror: json.parse: expected double-quoted property name syntaxerror: json.parse: end of data after property name when ':' was expected syntaxerror: json.parse: expected ':' after property name in object syntaxerror: json.parse: end of data after property value in object syntaxerror: json.parse: expected ',' or '}' after property value in object syntaxerror: json.parse: expected ',' or '}' after property-value pair in ob...
...And 6 more matches
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.
...And 5 more matches
Body.json() - Web APIs
WebAPIBodyjson
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.
...And 5 more matches
Downloading JSON and JavaScript in extensions - Archive of obsolete content
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.
... downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all.
... json is about state and does not allow functions to be decoded.
...And 3 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.
... index jsint (in js_parsejsonwithreviver only) a reviver function to apply to the created value after parsing; see json.parse.
...And 3 more matches
PerformanceEntry.toJSON() - Web APIs
the tojson() method is a serializer; it returns a json representation of the performance entry object.
... syntax json = perfentry.tojson(); arguments none return value json a json object that is the serialization of the performanceentry object.
... example the following example shows the use of the tojson() method.
...And 3 more matches
PushMessageData.json() - Web APIs
the json()method of the pushmessagedata interface extracts push message data by parsing it as a json string and returning the result.
... syntax var mydata = pushevent.data.json(); parameters none.
... returns the result of parsing push event data as json.
...And 3 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().
... 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.
...And 2 more matches
PaymentAddress.toJSON() - Web APIs
the tojson() property of the paymentaddress interface is a standard serializer that returns a json representation of the paymentaddress object's properties.
... syntax var json = paymentaddress.tojson() parameters none.
... return value a json object.
...And 2 more matches
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.
...And 2 more matches
Date.prototype.toJSON() - JavaScript
the tojson() method returns a string representation of the date object.
... syntax dateobj.tojson() return value a string representation of the given date.
...calling tojson() returns a string (using toisostring()) representing the date object's value.
...And 2 more matches
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.
... 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.
performance.toJSON() - Web APIs
the tojson() method of the performance interface is a standard serializer: it returns a json representation of the performance object's properties.
... syntax myperf = performance.tojson() arguments none return value myperf a json object that is the serialization of the performance object.
... example var js; js = window.performance.tojson(); console.log("json = " + json.stringify(js)); specifications specification status comment high resolution time level 2the definition of 'tojson() serializer' in that specification.
... recommendation defines tojson().
PerformanceServerTiming.toJSON - Web APIs
the tojson() method of the performanceservertiming interface returns a domstring that is the json representation of the performanceservertiming object.
... syntax var json = performanceservertiming.tojson() parameters none.
... return value a domstring containing json.
... specifications specification status comment server timingthe definition of 'tojson' in that specification.
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.
... 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.
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.
... 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.
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.
... 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.
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.
... 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.
URL.toJSON() - Web APIs
WebAPIURLtoJSON
the tojson() method of the url interface returns a usvstring containing a serialized version of the url, although in practice it seems to have the same effect as url.tostring().
... 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.
JXON - Archive of obsolete content
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.
...try: alert(json.stringify(myobject)); note: if you want to freeze the whole object tree (because of the "static" nature of an xml document), uncomment the string: /* object.freeze(this); */.
...And 26 more matches
Index - Web APIs
WebAPIIndex
.signature api, authenticatorassertionresponse, property, reference, web authentication api, webauthn the signature read-only property of the authenticatorassertionresponse interface is an arraybuffer object which is the signature of the authenticator for both authenticatorassertionresponse.authenticatordata and a sha-256 hash of the client data (authenticatorassertionresponse.clientdatajson).
... 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().
... 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.
...And 22 more matches
TypeScript support in Svelte - Learn web development
you could even add a script to your package.json file that runs that command.
... 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.
...And 16 more matches
cfx - Archive of obsolete content
this command 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.
...And 15 more matches
Promises - Archive of obsolete content
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.
... 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.
...And 15 more matches
cfx to jpm - Archive of obsolete content
id handling with cfx when you use cfx, the id is taken from the id field in the add-on's package.json file.
...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".
...And 10 more matches
Package management basics - Learn web development
we’ll call it parcel-experiment, but you can call it whatever you like: mkdir parcel-experiment cd parcel-experiment next, let's initialise our app as an npm package, which creates a config file — package.json — that allows us to save our configuration details in case we want to recreate this environment later on, or even publish the package to the npm registry (although this is somewhat beyond the scope of this article).
... type the following command, making sure you are inside the parcel-experiment directory: npm init you will now be asked some questions; npm will then create a default package.json file based on the answers: name: a name to identify the app.
... go into your parcel-experiment directory and you should now find you've got a package.json file.
...And 9 more matches
nsISessionStore
return value a json string representing the current state of all windows in the web browser.
... return value a json string representing the list of closed tabs for the window specified by awindow.
... return value a json string representing the list of closed windows.
...And 9 more matches
Using Fetch - Web APIs
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.
... 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.
...And 8 more matches
jpm - Archive of obsolete content
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.
...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.
...And 7 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
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.
...And 7 more matches
Signaling and video calling - Web APIs
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.
...as the name suggests, this sends a stringified json message to a particular username.
...the parameter msgstring is a stringified json object.
...And 7 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
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[...
...[html:]div) or an array of elements in json notation function tag(elemnameorarray, elemattr) { // array of elements?
...parse element namespace prefix (if none exists, default to defaultnamespace), and create element var elemns = namespace(elemnameorarray); var elem = doc.createelementns(elemns.namespace || jsontodom.defaultnamespace, elemns.shortname); // set element's attributes and/or callback functions (eg.
...And 6 more matches
Introducing a complete toolchain - Learn web development
this means that any file in the project we are working on gets formatted nicely, including html, css, javascript, json, markdown, and more.
...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).
... 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.
...And 6 more matches
Connecting to Remote Content - Archive of obsolete content
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.
... json content json is a very lightweight and simple data representation format, similar to the object representation used in javascript.
...And 5 more matches
Fetching data from the server - Learn web development
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 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 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.
...And 5 more matches
SubtleCrypto.importKey() - Web APIs
jwk: json web key format.
... keydata is an arraybuffer, a typedarray, a dataview, or a jsonwebkey object containing the key in the given format.
... supported formats this api supports four different key import/export formats: raw, pkcs #8, subjectpublickeyinfo, and json web key.
...And 5 more matches
self - Archive of obsolete content
it comes from the id property set in the package.json file in the main package (i.e.
...it comes from the name property in the main package's package.json file.
...it comes from the version property set in the package.json file in the main package.
...And 4 more matches
widget - Archive of obsolete content
any kind of jsonable value (object, array, string, etc.) can be used here.
...the message can be any json-serializable value.
... any kind of jsonable value (object, array, string, etc.) can be used here.
...And 4 more matches
Introduction to automated testing - Learn web development
type yes and press enter/return and npm will generate a package.json file in your directory.
...if you look in your project's package.json file, you'll see an entry for it in the devdependencies property.
... 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.
...And 4 more matches
Handling common JavaScript problems - Learn web development
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).
... this is supposed to be fetched from an external .json file using the following xmlhttprequest call: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new xmlhttprequest(); request.open('get', requesturl); request.send(); let superheroes = request.response; populateheader(superheroes); showheroes(superheroes); but this fails.
...And 4 more matches
Redis Tips
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.
... > 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.
... my least favorite flavor storing huge globs of json.
...And 4 more matches
Request.cache - Web APIs
WebAPIRequestcache
fetch("some.json", {cache: "no-store"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting, but update the http // cache with the downloaded resource.
... fetch("some.json", {cache: "reload"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting when dealing with a // properly configured server 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!
...And 4 more matches
Writing WebSocket client applications - Web APIs
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: document.getelementbyid("text").value, id: clientid, date: date.now() }; // send the msg object as a json-formatted string.
...And 4 more matches
eval() - JavaScript
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 ...
...but, in the code using eval(), the browser cannot assume this since what if your code looked like the following: function date(n){ return ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"][n%7 || 0]; } function loosejsonparse(obj){ return eval("(" + obj + ")"); } console.log(loosejsonparse( "{a:(4-1), b:function(){}, c:new date()}" )) thus, in the eval() version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called date().
... parsing json (converting strings to javascript objects) if the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to json, which allows the string to use a subset of javascript syntax to represent data.
...And 4 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
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.
...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 line 10, we use the _writefile method (which we’ll get to shortly) to write the json string representing the session to the file.
...And 3 more matches
Observer Notifications
topic data description bookmarks-restore-begin json sent just before bookmarks are restored from json.
... bookmarks-restore-success json sent just after bookmarks are restored from json.
... bookmarks-restore-failed json sent when bookmarks could not be sucessfully restored from json.
...And 3 more matches
nsITelemetry
static - true for histograms defined in histograms.json, false for ones defined with newhistogram().
... 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.
...And 3 more matches
Ajax navigation example - Web APIs
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>" .
..."</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>this is the content of <strong>first_page.php</strong>.</p> <?php if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); } else { ?> </div> <p>this paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</body>\n</html>"; } ?> second_page.php: <?php $page_title = "second page"; $as_json = false; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { $as_json = true...
..."</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>this is the content of <strong>second_page.php</strong>.</p> <?php if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); } else { ?> </div> <p>this paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</body>\n</html>"; } ?> third_page.php: <?php $page_title = "third page"; $page_content = "<p>this is ...
...And 3 more matches
JavaScript modules - JavaScript
45safari ios full support 10.3samsung internet android full support 8.0nodejs full support 13.2.0notes full support 13.2.0notes notes modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain "type": "module".
... full support 12.0.0notes disabled notes modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain "type": "module".
... 45safari ios full support 10.3samsung internet android full support 8.0nodejs full support 13.2.0notes full support 13.2.0notes notes modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain "type": "module".
...And 3 more matches
TypeError: cyclic object value - JavaScript
the javascript exception "cyclic object value" occurs when object references were found in json.
... json.stringify() doesn't try to solve them and fails accordingly.
... message typeerror: cyclic object value (firefox) typeerror: converting circular structure to json (chrome and opera) typeerror: circular reference in value argument not supported (edge) error type typeerror what went wrong?
...And 3 more matches
Object initializer - JavaScript
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.
... in json the values can only be strings, numbers, arrays, true, false, null, or another (json) object.
...And 3 more matches
Supporting search suggestions in search plugins - Archive of obsolete content
implementing suggestion support in the search 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.
...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.
...And 2 more matches
Theme concepts
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.
... 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.
...first, request "theme" permission in the extension's manifest.json file.
...And 2 more matches
Communicating with frame scripts
chrome code and frame scripts communicate back and forth using a messaging api which can include json-serializable objects as arguments.
... 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.
... data the json object passed as the second parameter to sendasyncmessage().
...And 2 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["@mozilla.org/dom/json;1"].createinstance(ci.nsijson); var searchresults = nativejson.decode(searchparam); // these 2 lines above are for thunderbird < v7 // since thunderbird 3, they can be replaced more efficiently by the following line: // var searchresults = json.parse(searchparam); var results = []; var comments = []; for (i=0; i<searchresults.length; i++) { if (searchresults[i].value.indexof(searchstring) == 0) { results.push(searchresults[i].value); if (searchresults[i].comment) comments.push(searchresults[i].commen...
...And 2 more matches
Dict.jsm
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(); array listvalues(); void set(string akey, object avalue); string tojson(); string tostring(); properties attribute type description count number the number of items in the dictionary.
... tojson() returns a json string representation of the dictionary.
...And 2 more matches
Web Authentication API - Web APIs
browser calls authenticatormakecredential() on authenticator - internally, the browser will validate the parameters and fill in any defaults, which become the authenticatorresponse.clientdatajson.
...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).
... 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.
...And 2 more matches
CSP: report-uri - HTTP
these violation reports consist of json documents sent via an http post request to the specified uri.
... 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__) .
...$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 " .
...And 2 more matches
Cross-domain Content Scripts - Archive of obsolete content
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/.
... </html> the "page-script.js" file locates "today's featured article" and sends its content to "main.js": // page-script.js var iframe = window.document.getelementbyid("wikipedia"); var todaysfeaturedarticle = iframe.contentwindow.document.getelementbyid("mp-tfa"); self.postmessage(todaysfeaturedarticle.textcontent); for this to work, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://en.m.wikipedia.org/"] } the add-on should successfully retrieve the iframe's content.
...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...
... 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.
port - Archive of obsolete content
the payload can be any value that is serializable to json.
... json-serializable values the payload for a message can be any json-serializable value.
... however, you do have to ensure that the payload can be serialized to json.
... this means that it needs to be a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable.
Communicating using "port" - Archive of obsolete content
the payload can be any value that is serializable to json.
... 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.
... however, you do have to ensure that the payload can be serialized to json.
... this means that it needs to be a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable.
page-worker - Archive of obsolete content
any kind of jsonable value (object, array, string, etc.) can be used here.
...must be json-able.
... any kind of jsonable value (object, array, string, etc.) can be used here.
...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.
panel - Archive of obsolete content
any kind of jsonable value (object, array, string, etc.) can be used here.
...must be stringifiable to json.
... any kind of jsonable value (object, array, string, etc.) can be used here.
...the message can be any json-serializable value.
request - Archive of obsolete content
the example below shows how to use request to get the most recent tweet from the @mozhacks account: var request = require("sdk/request").request; var latesttweetrequest = request({ url: "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=mozhacks&count=1", oncomplete: function (response) { var tweet = response.json[0]; console.log("user: " + tweet.user.screen_name); console.log("tweet: " + tweet.text); } }); // be a good consumer and check for rate limiting before doing more.
... request({ url: "https://api.twitter.com/1.1/application/rate_limit_status.json", oncomplete: function (response) { if (response.json.remaining_hits) { latesttweetrequest.get(); } else { console.log("you have been rate limited!"); } } }).get(); methods get() make a get request.
... json the content of the response as a javascript object.
... the value will be null if the document cannot be processed by json.parse.
console/traceback - Archive of obsolete content
usage tracebacks are stored in json format.
... 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.
dev/panel - Archive of obsolete content
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.
... = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: { mypanel: mypanel } }); in my-panel.js: // my-panel.js var content = document.getelementbyid("content"); window.addeventlistener("message", function(event) { var debuggee = event.ports[0]; console.log(debuggee); debuggee.onmessage = function(event) { content.textcontent = json.stringify(event.data); } debuggee.postmessage({ "to":"root", "type":"listtabs" }); }); if you do this, don't forget to call start() on the port before passing it over to the panel document.
... volcan.js: a javascript api for the debugging protocol communicating with the debugger server by exchanging json messages can be cumbersome.
...if the message reply contains some json object, then in volcan.js the object that fulfills the promise includes a corresponding json object.
Localization - Archive of obsolete content
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.
... for example, here's a "package.json" defining a german localization for title and description: { "locales": { "de": { "title": "monstergenerator", "description": "erstelle dein eigenes monster" } }, "name": "monster-builder", "license": "mpl 2.0", "author": "me", "version": "0.1", "title": "monster builder", "id": "monster-builder@me.org", "description": "build your own monster" } using localized strings in preferences by including a "preferences" structure in your add-on's "package.json" file, you can define preferences for your add-on that the user can see and edit using firefox's...
... for example, suppose your "package.json" defines a single preference: { "preferences": [ { "type": "string", "name": "monster_name", "value": "gerald", "title": "name" } ], "name": "monster-builder", "license": "mpl 2.0", "author": "me", "version": "0.1", "title": "monster builder", "id": "monster-builder@me.org", "description": "build ...
... the sdk tools compile the locale files into a json format when producing an xpi.
Code snippets - Archive of obsolete content
("crypto/keys"); // delete server: deletepath(""); corrupt a single engine on the server let engine = "bookmarks"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); components.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.
...envelope.payload = json.stringify(payload); r.put(json.stringify(envelope)); generate new keys // clients always wipe the server when they generate new keys.
...ids) { let record = bme._store.createrecord(id, "bookmarks"); let len = record.tostring().length; if (len > 1000) { console.log("id: " + id + ", len = " + len + ", " + record.title); } } print an alphabetically sorted list of members of a collection components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); let ids = json.parse(new resource(weave.service.storageurl + "bookmarks").get()); for each (let id in ids.sort()) { console.log(" " + id); } get a count of the number of members of a collection on the server let collection = "passwords"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); json.parse(new resource(weave.service.storageu...
...obj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full = true; coll.limit = null; coll.recordhandler = function(item) { item.collection = collection; item.decrypt(); if (item.deleted) { deleted++; } else { items[item.type] = 1 + (items[item.type] || 0); } }; coll.get(); console.log("deleted: " + deleted + ", " + json.stringify(items)); get a log from xul fennec view about:sync-log.
Visual typescript game engine - Game development
there's server package.json independently from the client part also config is not common.
... ├── package.json ├── package-lock.json ├── webpack.config.js ├── tsconfig.json ├── tslint.json ├── launch.json ├── workplace.code-workspace logo.png license ├── build/ (this is auto generated) | ├── externals/ | ├── templates/ | ├── imgs/ | ├── styles/ | | └── favicon.ico | ├── visualjs2.js | ├── app.html ├── src/ | ├── style/ | | ├── styles.css | ├── libs/ | | ├── class/ | | | ├── networking/ | | | | ├── rtc-multi-connection/ | | | | | ├── filebufferreader.js | | | | | ├── rtcmulticonnection2.js | | | | | ├── rtcmulticonnection3.js | | | |...
...| ├── examples/ | | ├── platformer/ | ├── html-components/ | | ├── register.html | | ├── login.html | | ├── games-list.html | | ├── user-profile.html | | ├── store.html | | ├── broadcaster.html | ├── index.html | ├── app-icon.ts | └── app.ts └── server/ | ├── package.json | ├── package-lock.json | ├── server-config.js | ├── database/ | | ├── database.js | | ├── common/ | | ├── email/ | | | ├── templates/ | | | | ├── confirmation.html.js | | | ├── nocommit.js (no commited for now) | | └── data/ (ignored - db system folder) | ├── rtc/ | | ├── serve...
... code format : npm run fix npm run tslint or use : tslint -c tslint.json 'src/**/*.ts' --fix tslint -c tslint.json 'src/**/*.ts' the external licence in this project : - networking based on : muaz khan mit license www.webrtc-experiment.com/licence - base physics based on : original source: matter.js https://github.com/liabru/matter-js matter.ts used because typescript orientation.
Third-party APIs - Learn web development
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.
... 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.
... function displayresults(json) { while (section.firstchild) { section.removechild(section.firstchild); } const articles = json.response.docs; if(articles.length === 10) { nav.style.display = 'block'; } else { nav.style.display = 'none'; } if(articles.length === 0) { const para = document.createelement('p'); para.textcontent = 'no results returned.' section.appendchild(para); } else { for(var i = 0; i < articles.length; i++) { const article = document.createelement('article'); const heading = document.createelement('h2'); const link = document.createelement('a'); const img = document.createele...
... next, we set the articles variable to equal json.response.docs — this is the array holding all the objects that represent the articles returned by the search.
Solve common problems in your JavaScript code - Learn web development
what is json?
... 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?
Server-side web frameworks - Learn web development
html, json, xml), and improving security against web attacks.
... web frameworks often provide a mechanism to make it easy to generate other formats from stored data, including json and xml.
...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.
... json and html/xml parsers and generators with css selector support.
Getting started with React - Learn web development
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'...
... the package.json file contains information about our 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`?
... 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.
Deploying our app - Learn web development
we're going to add the build command to our package.json file as an npm script, so that the command npm run build will trigger the build process.
... open the package.json file in your project's root directory, and find the scripts property.
...keep the json valid.
... go to your package.json file and open it up.
HTMLIFrameElement.getManifest()
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) { ...
... 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.
DMD
$ 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...
... adb shell am start -n org.mozilla.fennec_$username/.app trigger use the 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.
Hacking Tips
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).
...running this tool is a matter of running "python reduce.py js_shell /tmp/tl-data.json tl-reduced".
...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.
TPS Tests
%path% activate the environment source %path%/bin/activate run some tests note that the testfile is not a path, it should only be the filename from services/sync/tests/tps/ runtps --debug --testfile %test_file_name% --binary %firefox_binary_path% additionally, omitting a --testfile parameter will cause it to run all tps tests listed in services/sync/tests/tps/all_tests.json an example on osx, for running just the test_sync.js testfile against a locally built firefox (where the mozconfig set the objdir to obj-ff-artifact): runtps --debug --testfile test_sync.js --binary obj-ff-artifact/dist/nightly.app/contents/macos/firefox running tps against stage, or dev fxa tps can be configured using the $tps_venv_path/config.json file.
...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).
...they must look like: var phases = { "phase1": "profile1", "phase2": "profile2", "phase3": "profile1" }; between { and } it must be strict json.
...the python testrunner will be parsing it with an unforgiving call to json.loads, so anything other than strict json will fail.
nsIDOMWindowUtils
return value a json string summarizing the information profiled about the script.
... the structure of the json is unspecified and may vary between versions of firefox.
... return value a json string with all profile information accumulated for the script.
... the structure of the json is unspecified and may vary between versions of firefox.
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.
... the error tells us that the source map is not json data — so we're serving the wrong file.
... 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.
Using microtasks in JavaScript with queueMicrotask() - Web APIs
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.
...it starts by encoding it as json using the json.stringify() method.
...finally, we use the fetch() method to send the json string to the server.
... the server will receive the json string, then will presumably decode it and process the messages it finds in the resulting array.
Capabilities, constraints, and settings - Web APIs
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.
... 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.
... 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.
Using server-sent events - Web APIs
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.
...each event's data is a json object containing the iso 8601 timestamp corresponding to the time at which the event was generated.
...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.
SubtleCrypto.exportKey() - Web APIs
jwk: json web key format.
... if format was jwk, then the promise fulfills with a json object containing the key.
...a-oaep", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["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.
...*/ 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.
Attestation and Assertion - Web APIs
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.
...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.
Using Web Workers - Web APIs
to illustrate this, let's create for didactical purpose a function named emulatemessage(), which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa: function emulatemessage(vval) { return eval('(' + json.stringify(vval) + ')'); } // tests // test #1 var example1 = new number(3); console.log(typeof example1); // object console.log(typeof emulatemessage(example1)); // number // test #2 var example2 = true; console.log(typeof example2); // boolean console.log(typeof emulatemessage(example2)); // boolean // test #3 var example3 = new string('hello world'); console.log(typeof example3); // object ...
... 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.
...etc): calls a worker's queryable function * postmessage(string or json data): see worker.prototype.postmessage() * terminate(): terminates the worker * addlistener(name, function): adds a listener * removelistener(name): removes a listener queryableworker instances properties: * defaultlistener: the default listener executed only when the worker calls the postmessage() function directly */ function queryableworker(url, ...
Getting Started - Developer guides
it can send and receive information in various formats, including json, xml, html, and text files.
...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.
... the text box, the server's response would look like this: {"userdata":"jane","computedstring":"hi, jane!"} to use this data within alertcontents(), we can't just alert the responsetext, we have to parse it and alert computedstring, the property we want: function alertcontents() { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { var 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'])) ?
..."!"; $array = ['username' => $name, 'computedstring' => $computedstring]; echo json_encode($array); for more on dom methods, be sure to check out document object model (dom).
Ajax - Developer guides
WebGuideAJAX
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.
...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.
Trailing commas - JavaScript
json, however, disallows trailing commas.
...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 correctly: json.parse('[1, 2, 3, 4 ]'); json.parse('{"foo" : 1 }'); specifications specification ecmascript (ecma-262) ...
Web app manifests
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).
...it is a json-formatted file, with one exception: it is allowed to contain "//"-style comments.
...s?id=cheeaun.hackerweb" }] } deploying a manifest web app manifests are deployed 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).
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.
... 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.
... for search suggestions, the application/x-suggestions+json url template is used to fetch a suggestion list in json format.
Interacting with page scripts - Archive of obsolete content
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.
...to do this, add an option called “unsafe-content-script” under the “permissions” key in package.json, and set it to true.
...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); ...
Program ID - Archive of obsolete content
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.
context-menu - Archive of obsolete 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 message can be any json-serializable value.
...the message can be any json-serializable value.
simple-prefs - Archive of obsolete content
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", ...
... 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.
...you can change the sub-branch of extensions using the preferences-branch key in your add-on's package.json file.
content/worker - Archive of obsolete content
parameters data : number,string,json the data to send.
... must be stringifiable to json.
... arguments value : the event listener is passed the message, which must be a json-serializable value.
ui/frame - Archive of obsolete content
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.
... if you send a json object, the sdk takes care of serializing and deserializing it for you: // frame.js var label = window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); }, true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data.type == "ping") { console.log(e.data.reason); e.source.postmessage("pong", event.origin); } } globals constructors frame(options) creates an frame.
...if the payload was a json object, you can access it like an object: // frame.js var label = window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); }, true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); fun...
Getting Started (jpm) - Archive of obsolete content
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.
... 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.
...unless you've changed the value of "entry point" ("main" in package.json), this goes in "index.js" file in the root of your add-on.
How to convert an overlay extension to restartless - Archive of obsolete content
if you're getting json this way make sure to explicitly set the type as "text" if you intend to parse it yourself.
...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.
Interaction between privileged and non-privileged pages - Archive of obsolete content
chromium-like messaging: json request with json callback web page: <html> <head> <script> var something = { send_request: function(data, callback) { // analogue of chrome.extension.sendrequest var request = document.createtextnode(json.stringify(data)); request.addeventlistener("something-response", function(event) { request.parentnode.removechild(request); i...
...f (callback) { var response = json.parse(request.nodevalue); callback(response); } }, false); document.head.appendchild(request); var event = document.createevent("htmlevents"); event.initevent("something-query", true, false); request.dispatchevent(event); }, callback: function(response) { return alert("response: " + (response ?
...button> </body> </html> overlay on browser.xul in your extension: var something = { listen_request: function(callback) { // analogue of chrome.extension.onrequest.addlistener document.addeventlistener("something-query", function(event) { var node = event.target; if (!node || node.nodetype != node.text_node) return; var doc = node.ownerdocument; callback(json.parse(node.nodevalue), doc, function(response) { node.nodevalue = json.stringify(response); var event = doc.createevent("htmlevents"); event.initevent("something-response", true, false); return node.dispatchevent(event); }); }, false, true); }, callback: function(request, sender, callback) { if (request.foo) { return settimeout(function() ...
Appendix D: Loading Scripts - Archive of obsolete content
all communication between these contexts and outer contexts is marshalled through json encoding and decoding.
... 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.
Index - Archive of obsolete content
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.
... 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.
... 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.
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.$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.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; th...
...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);}}); ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Sending forms through JavaScript - Learn web development
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.
... 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.
Index - Learn web development
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.
... 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.
... 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.
Introduction to web APIs - Learn web development
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 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.
...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.
Getting started with Svelte - Learn web development
your browser will display something like this: application structure the starter template comes with the following 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?
HTMLIFrameElement.getStructuredData()
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.
...if the request is successful, the request.result is a json object representation of all microdata contained on the page loaded in the browser.
...s var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getstructureddata(); request.onsuccess = function() { console.log(request.result); } }); running this code in a browser api app and then loading up a page that contains microdata (such as the website of british alt-country band salter cane) will result in a json object being returned, along the lines of: { "items": [ { "type":["http://microformats.org/profile/hcard"], "properties":{"fn":["chris askew"], "n":[ { "properties": { "given-name":["chris"], "family-name":["askew"], ...
about:memory
(the filename will have a .json.gz suffix.) you can then attach or upload the file appropriately.
... 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.
Statistics API
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.
... 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.
The Publicity Stream API
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.
... 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.
...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.
nsIFrameMessageManager
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.
... 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.
nsIPushMessage
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.
... json() parses the message data as json.
... jsval json(); parameters none.
Inspecting web app manifests - Firefox Developer Tools
nifest successfully deployed, you'll get the following output shown: deploying a manifest to get a manifest deployed successfully, you need to include a <link> element in the <head> of your document that points to your .webmanifest file: <link rel="manifest" href="/manifest.webmanifest"> the .webmanifest extension is recommended in the spec, and should be served with an application/manifest+json mime type, although browsers generally tend to support manifests with other appropriate extensions like .json (mime type: application/json).
... you also need to make sure the json inside the file is of the correct format.
...it provides a link to the manifest file at the top which when clicked on brings up the json in a new tab.
Index - Firefox Developer Tools
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.
... 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.
Network request details - Firefox Developer Tools
(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.
... if you select copy all, the entire header is copied in json format, giving you something like this (after running the results through a json validator): { "response headers (1.113 kb)": { "headers": [ { "name": "accept-ranges", "value": "bytes" }, { "name": "age", "value": "0" }, { "name": "backend-timing", "value": "d=74716 t=1560258099074460" }, { "name": "cache-control", "value": "private, must-revalidate, max-age=0" }, { "name": "content-disposition", "value": "inline; filename=api-result.js" }, { "name": "content-encoding", "value": "gzip" }, { "name": "content-length", "value": "673" }, ...
...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.
AuthenticatorAssertionResponse - Web APIs
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.signature secure contextread only an assertion signature over authenticatorassertionresponse.authenticatordata and authenticatorresponse.clientdatajson.
DOMPointInit.w - Web APIs
WebAPIDOMPointInitw
the dompointinit dictionary's w property is used to specify the w perspective value of a point in space when either creating or serializing to json a dompoint or dompointreadonly object.
... 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().
DOMPointInit.y - Web APIs
WebAPIDOMPointInity
the dompointinit dictionary's y property is used to specify the y-coordinate of a point in 2d or 3d space when either creating or serializing to json a dompoint or dompointreadonly object.
... 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().
DOMPointInit.z - Web APIs
WebAPIDOMPointInitz
the dompointinit dictionary's z property is used to specify the z-coordinate of a point in 2d or 3d space when either creating or serializing to json a dompoint or dompointreadonly object.
... 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().
FileSystemDirectoryEntry.getDirectory() - Web APIs
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 = new filereader(); reader.addeventlistener("loadend", function() { dictionary = json.parse(reader.result); }); reader.readastext(dictfile); }); }); }); } the loaddictionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory.
...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.
FileSystemDirectoryEntry.getFile() - Web APIs
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 = new filereader(); reader.addeventlistener("loadend", function() { dictionary = json.parse(reader.result); }); reader.readastext(dictfile); }); }); }); } the loaddictionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory.
...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.
Using the Performance API - Web APIs
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.
... in the following example, json serialization for the performance, performance.timing and performance.navigation objects is printed in the object element.
... function print_json() { var json; var o = document.getelementsbytagname("output")[0]; if (window.performance.tojson === undefined) { json = "window.performance.tojson() is not supported"; o.innerhtml += json + "<br>"; } else { var s; json = window.performance.tojson(); // print the performance object s = json.stringify(json); o.innerhtml = "<p>performance = " + s + "</p>"; // print the performance.timing and performance.navigation objects var perf = json.parse(s); var timing = perf.timing; o.innerhtml += "<p>peformance.timing = " + json.stringify(timing) + "</p>"; var navigation = perf.navigation; o.innerhtml += "<p>peformance.navigation = " + json.stringify(navigation) + "</p>"; } } specifications the interfaces described...
Using Performance Timeline - Web APIs
this interface has four properties and a json serializer (tojson().
..." + properties[j] + " = not supported"); } } } } this interface also includes a tojson() method that returns the serialization of the performanceentry object.
... function perfentry_tojson() { // create a few performance entries performance.mark("mark-1"); performance.mark("mark-2"); performance.measure("meas-1", "mark-1", "mark-2"); var pelist = performance.getentries(); var pe = pelist[0]; if (pe.tojson === undefined) { log ("performanceentry.tojson() is not supported"); return; } // print the performanceentry object var json = pe.tojson(); var s = json.stringify(json); log("performanceentry.tojson = " + s); } 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 cal...
RTCSessionDescription - Web APIs
rtcsessiondescription.tojson() returns a json description of the object.
... the values of both properties, type and sdp, are contained in the generated json.
... example signalingchannel.onmessage = function (evt) { if (!pc) start(false); var message = json.parse(evt.data); if (message.sdp) pc.setremotedescription(new rtcsessiondescription(message), function () { // if we received an offer, we need to answer if (pc.remotedescription.type == "offer") pc.createanswer(localdesccreated, logerror); }, logerror); else pc.addicecandidate(new rtcicecandidate(message.candidate), function () {}, logerror); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescription' in that specification.
Request - Web APIs
WebAPIRequest
body.json() returns a promise that resolves with a json representation of the request body.
...pi request which need a body payload: const request = new request('https://example.com', {method: 'post', body: '{"foo": "bar"}'}); const url = request.url; const method = request.method; const credentials = request.credentials; const bodyused = request.bodyused; note: the body type can only be a blob, buffersource, formdata, urlsearchparams, usvstring or readablestream type, so for adding a json object to the payload you need to stringify that object.
... you could then fetch this api request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example and get the response: fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new error('something went wrong on api server!'); } }) .then(response => { console.debug(response); // ...
Using Service Workers - Web APIs
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.
...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).
...if you just passed in the url, and then tried to access the other items in the json separately when the for() loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.) we actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 31-34).
WebGLRenderingContext.vertexAttribPointer() - Web APIs
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.
... //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 < vertices.length; i++) { dv.setfloat32(20 * i, vertices[i].position[0], true); dv.setfloat32(20 * i + 4, vertices[i].position[1], true); dv.setfloat32(20 * i + 8, vertices[i].position[2], true); dv.setint8(20 * i + 12, vertices[i].normal[0] * 0x7f); dv.setint8(20 * i + 13, vertices[i].normal[1] * 0x7f); dv.setint8(20 * i + 14, vertices[i].normal[2] * 0x7f); dv.setint8(20 * i + 15, 0); dv.setuint16(20 * i + 16, vert...
...ices[i].texcoord[0] * 0xffff, true); dv.setuint16(20 * i + 18, vertices[i].texcoord[1] * 0xffff, true); } for higher performance, we could also do the previous json to arraybuffer conversion on the server-side, e.g.
Writing WebSocket servers - Web APIs
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.
Content-Location - HTTP
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: /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.
HTTP Index - HTTP
WebHTTPIndex
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.
...these violation reports consist of json documents sent via an http post request to the specified uri.
...these violation reports consist of json documents sent via an http post request to the specified uri.
Network Error Logging - HTTP
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.
...defaults to 0, so that no successful network requests will be reported if the key is not present in the json payload.
...defaults to 1, so that all failed network requests will be reported if the key is not present in the json payload.
JavaScript data types and data structures - JavaScript
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.
Compiling from Rust to WebAssembly - WebAssembly
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.
... reads your cargo.toml and produces an equivalent package.json.
...$ 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.
Loading Content Scripts - Archive of obsolete content
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.
self - Archive of obsolete content
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.
... 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.
Content Scripts - Archive of obsolete content
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.
... 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.
Content Processes - Archive of obsolete content
we can, however, pass json messages between scripts in different processes.
... event emitters the messaging api we use to send json messages between scripts in different processes is based on the use of event emitters.
XUL Migration Guide - Archive of obsolete content
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.
...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.
content/symbiont - Archive of obsolete content
any kind of jsonable value (object, array, string, etc.) can be used here.
... any kind of jsonable value (object, array, string, etc.) can be used here.
lang/type - Archive of obsolete content
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.
... let { isjson } = require('sdk/lang/type'); isjson({ value: 42 }); // true isjson({ fn: function () {} ); // false parameters value : mixed the variable to check.
jpmignore - Archive of obsolete content
for 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.
... this one would work for xemacs: .* * !/data/** !/lib/** !/locale/** !/node_modules/** !/package.json !/icon.png !/icon64.png !/copying !/bootstrap.js !/install.rdf *~ \#* ...
Using third-party modules (jpm) - Archive of obsolete content
the --save argument instructs npm to add this package to the dependencies key in the add-on's package.json file.
...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".
Security best practices in extensions - Archive of obsolete content
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.
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
bug 510537 date.prototype.tojson() returns a json format string for a date object.
... trailing commas no longer accepted in json.parse().
ECMAScript 5 support in Mozilla - Archive of obsolete content
added in javascript 1.8.1 (gecko 1.9.1, firefox 3.5) native json support object.getprototypeof() method.
... gecko 1.9.1.4 updated the implementation of json.stringify() to be compliant with ecmascript 5.
WAI-ARIA basics - Learn web development
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.
... 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.
Introducing asynchronous JavaScript - Learn web development
so you could have different actions to run on the response downloaded, such as processjson(), displaytext(), etc.
...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).
Introducing JavaScript objects - Learn web development
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.
...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.
Working with Svelte stores - Learn web development
give it the following content: import { writable } from 'svelte/store'; export const localstore = (key, initial) => { // receives the key of the local storage and an initial value const tostring = (value) => json.stringify(value, null, 2) // helper function const toobj = json.parse // helper function if (localstorage.getitem(key) === null) { // item not present in local storage localstorage.setitem(key, tostring(initial)) // initialize local storage with initial value } const saved = toobj(localstorage.getitem(key)) ...
... 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.
Getting started with Vue - Learn web development
the other option, "in package.json", will put all of your config settings into the app's package.json file.
...the cli adds a serve command to the project’s package.json file as an npm script, so you can easily run it.
Performance best practices for Firefox front-end engineers
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.
Browser API
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.
... htmliframeelement.getmanifest() retrieves the manifest of an app loaded in the browser <iframe> and returns it as json.
L10n Checks
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/locales/l10n.ini ../l10n/ de there are six levels.
Profiling with the Firefox Profiler
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.
...*/ ); ' -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.
L20n HTML Bindings
<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.
... <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.
SpiderMonkey Build Documentation
for a list of other available build options, type (assuming the current working directory is 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.
Creating JavaScript jstest reftests
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.
... you would like to contribute tests of an ecmascript, intl or json feature insufficiently covered by test262.
SpiderMonkey 1.8.5
new c apis js_assert_string_is_flat js_addgcthingroot js_addnamedgcthingroot js_addnamedobjectroot 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_de...
...finepropertybyid 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_getpropertyattrsgetterandsetterbyid js_getpropertybyid js_getpropertybyidd...
SpiderMonkey 1.8.7
new c apis js_assert_string_is_flat js_addgcthingroot js_addnamedgcthingroot js_addnamedobjectroot 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_de...
...finepropertybyid 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_getpropertyattrsgetterandsetterbyid js_getpropertybyid js_getpropertybyidd...
Running Parsemark
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 note: unfortunately the comparisons done are very noisy and not reliable!
Web Replay
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.
... this communicates with the replaying process via json and is fairly easy to extend for new features (such as web console support).
Places Developer Guide
backup/restore the new bookmarks system uses the json format for storing backups of users' bookmarks.
...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.dirsvc.get("profd", ci.nsilocalfile); jsonfile.append("bookmarks.json"); jsonfile.create(ci.nsilocalfile.normal_file_type, 0600); // export bookmarks in json format to file placesutils.backupbookmarkstofile(jsonfile); // restore bookmarks from the json file // note: this *overwrites* all pre-existing bookmarks placesutils.restorebookmarksfromjsonfile(jsonfile); history the toolkit history service is nsinavhistoryservice: var history = cc["@mozilla.o...
Components.utils.evalInSandbox
note: it's not safe to use evalinsandbox() to evaluate json strings; instead, use the techniques discussed in the article on json.
... you can also find firefox 3.5 specific information in using json in firefox.
nsIFrameMessageListener
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.
nsIJetpack
optional javascript values to send with the message; they must be either json-serializable types or handles.
...the first argument passed to it is the name of the message, and all arguments following it are either json-serializable types or handles.
nsIMessageListener
json same as data.
... if the message is synchronous, the possible return value is returned as json (will be changed to use structured clones).
nsIScriptableIO
example: writing 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 ...
Accessibility Inspector - Firefox Developer Tools
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.
Storage Inspector - Firefox Developer Tools
for example: a stringified json like '{"foo": "bar"}' is shown as the origin json: {foo: "bar"}.
... a string containing key-value pairs, like "id=1234:foo=bar" is shown as json: {id:1234, foo: "bar"}.
Web Console remoting - Firefox Developer Tools
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.
... helperresult is anything that might come from a jsterm helper result, json stuff (not content objects!).
about:debugging (before Firefox 68) - Firefox Developer Tools
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.
...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.
AuthenticatorAssertionResponse.signature - Web APIs
the signature read-only property of the authenticatorassertionresponse interface is an arraybuffer object which is the signature of the authenticator for both authenticatorassertionresponse.authenticatordata and a sha-256 hash of the client data (authenticatorassertionresponse.clientdatajson).
...and available from authenticatorassertionresponse.clientdatajson).
AuthenticatorAttestationResponse - Web APIs
properties authenticatorattestationresponse.clientdatajson secure contextread only client data for the authentication, such as origin and challenge.
... the clientdatajson property is inherited from the authenticatorresponse.
Body - Web APIs
WebAPIBody
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.
CacheStorage - Web APIs
async function getdata() { const cacheversion = 1; const cachename = `myapp-${ cacheversion }`; const url = 'https://jsonplaceholder.typicode.com/todos/1'; let cacheddata = await getcacheddata( cachename, url ); if ( cacheddata ) { console.log( 'retrieved cached data' ); return cacheddata; } console.log( 'fetching fresh data' ); const cachestorage = await caches.open( cachename ); await cachestorage.add( url ); cacheddata = await getcacheddata( cachename, url ); await delet...
...cachedresponse.ok ) { return false; } return await cachedresponse.json(); } // delete any old caches to respect user's disk space.
console.log() - Web APIs
WebAPIConsolelog
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.
... logging objects don't use console.log(obj), use console.log(json.parse(json.stringify(obj))).
DOMPointInit - Web APIs
the dompointinit dictionary is used to provide the values of the coordinates and perspective when creating and jsonifying a dompoint or dompointreadonly object.
...it's used as the return value when calling tojson().
FileSystemEntry.fullPath - Web APIs
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.
Working with the History API - Web APIs
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.
... 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.
Metadata.modificationTime - Web APIs
example this example tries to get a particular working file at tmp/workfile.json.
... 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.
PaymentAddress - Web APIs
methods paymentaddress.tojson() a standard serializer that returns a json representation of the paymentaddress object's properties.
... const json = response.tojson(); const httpresponse = await fetch("/pay/", { method: "post", body: json }); const result = httpresponse.ok ?
PaymentRequest.PaymentRequest() - Web APIs
data a json-serializable object that provides optional information that might be needed by the supported payment methods.
... data a json-serializable object that provides optional information that might be needed by the supported payment methods.
Performance - Web APIs
performance.tojson() is a jsonizer returning a json object representing the performance object.
... recommendation defines tojson() method.
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"; ...
...if (supported) { var js = obj[methods[i]](); log("..." + methods[i] + "() = " + json.stringify(js)); } else { log("..." + methods[i] + " = not supported"); } } } specifications specification status comment performance timeline level 2the definition of 'duration' in that specification.
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"; ...
...if (supported) { var js = obj[methods[i]](); log("..." + methods[i] + "() = " + json.stringify(js)); } else { log("..." + methods[i] + " = not supported"); } } } specifications specification status comment performance timeline level 2the definition of 'name' in that specification.
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"; ...
...if (supported) { var js = obj[methods[i]](); log("..." + methods[i] + "() = " + json.stringify(js)); } else { log("..." + methods[i] + " = not supported"); } } } specifications specification status comment performance timeline level 2the definition of 'starttime' in that specification.
PerformanceEntry - Web APIs
methods performanceentry.tojson() returns a json representation of the performanceentry object.
... candidate recommendation added tojson() serializer method.
PerformanceEventTiming - Web APIs
methods performanceeventtiming.tojson() converts the performanceeventtiming object to json.
...function sendtoanalytics(data) { const body = json.stringify(data); // use `navigator.sendbeacon()` if available, falling back to `fetch()`.
PushMessageData - Web APIs
pushmessagedata.json() extracts the data as a json object.
... examples self.addeventlistener('push', function(event) { var obj = event.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { firenotification(obj, event); port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); specifications specification status comment push apithe definition of 'pushmessagedata' in that specification.
RTCDataChannel.protocol - Web APIs
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.
... 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.
RTCDataChannel.send() - Web APIs
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.
Response - Web APIs
WebAPIResponse
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.
ServiceWorkerGlobalScope: push event - Web APIs
bubbles no cancelable no interface pushevent event handler property onpush example this example sets up a handler for push events that takes json data, parses it, and dispatches the message for handling based on information contained within the message.
... 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' in that specification.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
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.
...this is delivered to the app server using a fetch() call to post a json formatted rendition of the subscription's endpoint to the app server.
SubtleCrypto.wrapKey() - Web APIs
jwk: json web key format.
... window.crypto.subtle.generatekey( { name: "rsa-oaep", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["encrypt", "decrypt"] ) .then((keypair) => { return wrapcryptokey(keypair.publickey); }) .then((wrappedkey) => { console.log(wrappedkey); }); json web key import this code wraps an ecdsa private signing key.
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
signaler.send(description: pc.localdescription) } } else if (candidate) { try { await pc.addicecandidate(candidate); } catch(err) { if (!ignoreoffer) { throw err; } } } } catch(err) { console.error(err); } } upon receiving an incoming message from the signalingchannel through its onmessage event handler, the received json object is destructured to obtain the description or candidate found within.
... 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().
Inputs and input sources - Web APIs
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.
... 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.
Window: popstate event - Web APIs
examples a page at http://example.com/example.html running the following code will generate logs as indicated: window.addeventlistener('popstate', (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: h...
...ttp://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: http://example.com/example.html?page=3, state: {"page":3}" note that even though the original history entry (for http://example.com/example.html) has no state object associated...
Window: storage event - Web APIs
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.
Sending and Receiving Binary Data - Web APIs
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.
Index - Developer guides
WebGuideIndex
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.
... 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.
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
the <script> element can also be used with other languages, such as webgl's glsl shader programming language and json.
... <!-- 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.
Preloading content with rel="preload" - HTML: Hypertext Markup Language
resources that javascript can request, like json, imported scripts, or web workers.
... fetch: resource to be accessed by a fetch or xhr request, such as an arraybuffer or json file.
Content-Security-Policy-Report-Only - HTTP
these violation reports consist of json documents sent via an http post request to the specified uri.
... 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.
Index - HTTP
WebHTTPHeadersIndex
these violation reports consist of json documents sent via an http post request to the specified uri.
...these violation reports consist of json documents sent via an http post request to the specified uri.
X-Content-Type-Options - HTTP
however, it also enables cross-origin read blocking (corb) protection for html, txt, json and xml files (excluding svg image/svg+xml).
...onse 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 blocking (corb) protection for the mime-types: text/html text/plain text/json, application/json or any other type with a json extension: */*+json text/xml, application/xml or any other type with an xml extension: */*+xml (excluding image/svg+xml) specifications specification status comment fetchthe definition of 'x-content-type-options definition' in that specification.
TypeError: "x" is not a constructor - JavaScript
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?
...the following javascript standard built-in objects are not a constructor: math, json, symbol, reflect, intl, atomics.
BigInt - JavaScript
use within json using json.stringify() with any bigint value will raise a typeerror as bigint values aren't serialized in json by default.
... however, you can implement your own tojson method if needed: bigint.prototype.tojson = function() { return this.tostring() } instead of throwing, json.stringify now produces a string like this: json.stringify(bigint(1)) // '"1"' examples calculating primes // returns true if passed bigint is a prime number function isprime(p) { for (let i = 2n; i * i <= p; i++) { if (p % i === 0n) return false; } return true } // takes a bigint as an argument, returns nth prime number as bigint function nthprime(nth) { let maybeprime = 2n let prime = 0n while (nth >= 0n) { if (isprime(maybeprime)) { nth-- prime = maybeprime } maybeprime++ } return prime } nthprime(20n) // ↪ 73n specifications specification ecmascript (ecma-262)th...
Date - JavaScript
date.prototype.tojson() returns a string representing the date using toisostring().
... intended for use by json.stringify().
Object.assign() - JavaScript
function test() { 'use strict'; let obj1 = { a: 0 , b: { c: 0}}; let obj2 = object.assign({}, obj1); console.log(json.stringify(obj2)); // { "a": 0, "b": { "c": 0}} obj1.a = 1; console.log(json.stringify(obj1)); // { "a": 1, "b": { "c": 0}} console.log(json.stringify(obj2)); // { "a": 0, "b": { "c": 0}} obj2.a = 2; console.log(json.stringify(obj1)); // { "a": 1, "b": { "c": 0}} console.log(json.stringify(obj2)); // { "a": 2, "b": { "c": 0}} obj2.b.c = 3; console.log(json.stringify(obj1)); // {...
... "a": 1, "b": { "c": 3}} console.log(json.stringify(obj2)); // { "a": 2, "b": { "c": 3}} // deep clone obj1 = { a: 0 , b: { c: 0}}; let obj3 = json.parse(json.stringify(obj1)); obj1.a = 4; obj1.b.c = 4; console.log(json.stringify(obj3)); // { "a": 0, "b": { "c": 0}} } test(); merging objects const o1 = { a: 1 }; const o2 = { b: 2 }; const o3 = { c: 3 }; const obj = object.assign(o1, o2, o3); console.log(obj); // { a: 1, b: 2, c: 3 } console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
Standard built-in objects - JavaScript
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).
import - JavaScript
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.
... 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.
Add to Home screen - Progressive web apps (PWAs)
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).
....json.
How to make PWAs installable - Progressive web apps (PWAs)
the manifest file the key element is a web manifest file, which lists all the information about the website in a json format.
... 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.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
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.
... fetch('./register', { method: 'post', headers: { 'content-type': 'application/json' }, body: json.stringify({ subscription: subscription }), }); then the globaleventhandlers.onclick function on the subscribe button 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, ...
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); ...
Communicating using "postMessage" - Archive of obsolete content
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.
Two Types of Scripts - Archive of obsolete content
api add-on code content script the global objects defined in the core javascript language, such as math, array, and json.
l10n - Archive of obsolete content
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.
page-mod - Archive of obsolete content
a.url("show.js"), contentscriptoptions: { showoptions: true, numbers: [1, 2], greeting: "hello!" } }); the values are accessible to content scripts via the self.options property: // show.js if (self.options.showoptions) { window.alert(self.options.greeting); var sum = self.options.numbers[0] + self.options.numbers[1]; window.alert(sum); } the values can be any json-serializable value: a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable.
private-browsing - Archive of obsolete content
opting into private browsing add-ons built using the sdk must opt into private browsing by setting the following key in their package.json file: "permissions": {"private-browsing": true} if an add-on has not opted in, then the high-level sdk modules will not expose private windows, or objects (such as tabs) that are associated with private windows: the windows module will not list any private browser windows, generate any events for private browser windows, or let the add-on open any private browser windows the tabs mo...
url - Archive of obsolete content
tojson() returns a string representation of the url.
content/loader - Archive of obsolete content
any kind of jsonable value (object, array, string, etc.) can be used here.
core/heritage - Archive of obsolete content
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.
core/namespace - Archive of obsolete content
} widget.prototype = object.create(view.prototype); widget.prototype.postmessage = function postmessage(message) { let { sandbox } = sandboxes(this); sandbox.postmessage(json.stringify(json.parse(message))); ...
core/promise - Archive of obsolete content
// 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 o...
Tools - Archive of obsolete content
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
the simplest way to do this is to omit the "private-browsing" key from the add-on's "package.json" file.
Storing annotations - Archive of obsolete content
by omitting the "private-browsing" key from the annotator's "package.json" file, the annotator opts out of private browsing altogether.
Display a Popup - Archive of obsolete content
the add-on consists of seven files: package.json: created when you run jpm init index.js: the main add-on code, that creates the button and panel get-text.js: the content script that interacts with the panel content text-entry.html: the panel content itself, specified as html icon-16.png, icon-32.png, and icon-64.png: icons for the button in three different sizes the "index.js" looks like this: var data = require("sdk/self").data; // con...
Getting started (cfx) - Archive of obsolete content
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".
Unit Testing - Archive of obsolete content
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.
Add-on SDK - Archive of obsolete content
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.
File I/O - Archive of obsolete content
var channel = netutil.newchannel(file); channel.contenttype = "application/json"; netutil.asyncfetch(channel, function(inputstream, status) { ...
Examples and demos from articles - Archive of obsolete content
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.
Rosetta - Archive of obsolete content
*/ 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.
JavaScript timers - Archive of obsolete content
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.
Jetpack Processes - Archive of obsolete content
handles messages that communicate between the browser and jetpack process may contain only serializable (json) data and handles.
Tabbed browser - Archive of obsolete content
var url = "https://developer.mozilla.org"; var tab = gbrowser.addtab(null, {relatedtocurrent: true}); gsessionstore.settabstate(tab, json.stringify({ entries: [ { title: url } ], usertypedvalue: url, usertypedclear: 2, lastaccessed: tab.lastaccessed, index: 1, hidden: false, attributes: {}, image: null })); reusing tabs rather than open a new browser or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired url--if one is already op...
Search Extension Tutorial (Draft) - Archive of obsolete content
</image> <url type="application/x-suggestions+json" template="https://api.example.com/suggestions"> <param name="q" value="{searchterms}"/> </url> <url type="text/html" method="get" template="https://www.example.com/search"> <param name="q" value="{searchterms}"/> <param name="source" value="search-box"/> </url> <url type="application/x-moz-keywordsearch" method="get" template="https://www.example.com/searc...
JavaScript Client API - Archive of obsolete content
cleartext must be a json-able object.
Twitter - Archive of obsolete content
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.
Plug-n-Hack Phase1 - Archive of obsolete content
security tool commands manifest an example commands manifest (for owasp zap) is: https://code.google.com/p/zap-extensions/source/browse/branches/beta/src/org/zaproxy/zap/extension/plugnhack/resource/service.json firefox ui in firefox the tool commands will be made available via the developer toolbar (gcli) https://developer.mozilla.org/docs/tools/gcli a example of how the zap commands are currently displayed is: note that user specified parameters can be specified for commands, which can either be free text, a static pull down list of options or a dynamic list of options obtained from the tool on demand...
persist - Archive of obsolete content
in mozilla, persistent attributes are stored in the per-profile file xulstore.json.
XUL Questions and Answers - Archive of obsolete content
json string) from the server, parsing it on client, and building the menupopup using dom methods (such as document.createelementns).
XUL element attributes - Archive of obsolete content
in mozilla, persistent attributes are stored in the per-profile file xulstore.json.
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
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.
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
t yet implemented; in other browsers) regexp named capture groups (not yet implemented; in other browsers) ecmascript 2019 array.flat() (firefox 62) array.flatmap() (firefox 62) object.fromentries() (firefox 63) string.trimstart() and string.trimend() (firefox 61) optional catch binding (firefox 58) function.tostring() revision (firefox 54) symbol.description (firefox 63) well-formed json.stringify() (firefox 64) ecmascript 2020 this is the current es.next version.
New in JavaScript 1.8.1 - Archive of obsolete content
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.
New in JavaScript - Archive of obsolete content
includes the tracemonkey jit and supports native json.
Visual-js game engine - Game development
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
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.
Deserialization - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, for example, you can deserialize a json string to an object by calling the function json.parse().
Serialization - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, for example, you can serialize an object to a json string by calling the function json.stringify().
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
previous overview: objects in this module object basics object-oriented javascript for beginners object prototypes inheritance in javascript working with json data object building practice adding features to our bouncing balls demo ...
JavaScript object basics - Learn web development
overview: objects next in this module object basics object-oriented javascript for beginners object prototypes inheritance in javascript working with json data object building practice adding features to our bouncing balls demo ...
Inheritance in JavaScript - Learn web development
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
previous overview: objects next in this module object basics object-oriented javascript for beginners object prototypes inheritance in javascript working with json data object building practice adding features to our bouncing balls demo ...
Object prototypes - Learn web development
previous overview: objects next in this module object basics object-oriented javascript for beginners object prototypes inheritance in javascript working with json data object building practice adding features to our bouncing balls demo ...
JavaScript — Dynamic client-side scripting - Learn web development
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-Server Overview - Learn web development
it can instead dynamically create and return other types of files (text, pdf, csv, etc.) or even data (json, xml, etc.).
Introduction to the server side - Learn web development
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).
Ember resources and troubleshooting - Learn web development
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.
Deployment and next steps - Learn web development
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.
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
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.
Index
689 updates firefox supports automated updates to add-ons using json update manifests.
Themes
tools & resources browser theme manifest.json keys browser extensions theme api discourse forum theme related blog posts archived resources ...
Testopia
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.
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
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?
mozbrowsercontextmenu
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsercontextmenu", function(event) { console.log("asking for menu:" + json.stringify(event.details)); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsershowmodalprompt
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsershowmodalprompt", function( event ) { console.log("asking for prompt:" + json.stringify(event.detail)); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
Assert.jsm
json.stringify is not designed to be used for this purpose; objects may have ambiguous tojson() implementations that would influence the test.
SourceMap.jsm
new sourcemapconsumer(rawsourcemap) the only parameter is the raw source map (either as a string which can be json.parse'd, or an object).
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: ...
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
enhanced logging: supports generating rich json streams to disk or over the network for consumption by logsploder or other tools.
Index
424 js_parsejson parse a string using the json syntax described in ecmascript 5 and return the corresponding value.
JSProtoKey
mxr search for jsproto_null jsproto_object object mxr search for jsproto_object jsproto_function function mxr search for jsproto_function jsproto_array array mxr search for jsproto_array jsproto_boolean boolean mxr search for jsproto_boolean jsproto_json json mxr search for jsproto_json jsproto_date date mxr search for jsproto_date jsproto_math math mxr search for jsproto_math jsproto_number number mxr search for jsproto_number jsproto_string string mxr search for jsproto_string jsproto_regexp regexp mxr search for jsproto_regexp jsproto_error ...
Zest runtimes
as zest is written in json it requires a runtime in order to be evaluated.
Zest
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.
compare-locales
pass --json to get just the summary in json format.
Mozilla Projects
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.
Setting up an update server
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!
Index
MozillaTechXPCOMIndex
707 nsijson interfaces, interfaces:scriptable, needsexample, xpcom api reference, xpcom interface reference implemented by: @mozilla.org/dom/json;1.
Components.utils.import
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.lo...
XPCshell Test Manifest Expressions
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.
nsIPushService
message.json(); // parses the message as json.
nsIPushSubscription
.getservice(ci.nsipushservice); function sendsubscriptiontoserver(subscription) { let request = cc["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(ci.nsixmlhttprequest); request.open("post", "https://example.com/register-for-push", true); request.addeventlistener("error", () => { cu.reporterror("error sending subscription to server"); }); request.send(json.stringify({ endpoint: subscription.endpoint, // base64-encode the key and authentication secret.
nsISHEntry
(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.
nsISyncMessageSender
obj jsonable object.
nsIWebProgressListener
cu.reporterror("saw: " + data.name + " -- passing: " + json.stringify(data)); }); /** * below is the contents of example-framescript.js */ const {classes: cc, interfaces: ci, utils: cu} = components; cu.import("resource://gre/modules/xpcomutils.jsm"); var mylistener = { queryinterface: xpcomutils.generateqi(["nsiwebprogresslistener", "nsisupportsweakreference"]), onstatechange: function(awebprogres...
XPCOM Interface Reference
ihapticfeedbacknsihttpactivitydistributornsihttpactivityobservernsihttpchannelnsihttpchannelinternalnsihttpheadervisitornsihttpservernsihttpupgradelistenernsiidnservicensiiframeboxobjectnsiiniparsernsiiniparserfactorynsiiniparserwriternsiioservicensiidleservicensiinprocesscontentframemessagemanagernsiinputstreamnsiinputstreamcallbacknsiinstalllocationnsiinterfacerequestornsijscidnsijsidnsijsiidnsijsonnsijetpacknsijetpackservicensijumplistbuildernsijumplistitemnsilivemarkservicensiloadgroupnsilocalfilensilocalfilemacnsilocalensilocaleservicensilogininfonsiloginmanagernsiloginmanagercryptonsiloginmanageriemigrationhelpernsiloginmanagerprompternsiloginmanagerstoragensiloginmetainfonsimimeinputstreamnsimacdocksupportnsimarkupdocumentviewernsimemorynsimemorymultireporternsimemorymultireportercallba...
Test-Info
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.
Mozilla
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.
Migrating from Firebug - Firefox Developer Tools
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.
Inspecting web sockets - Firefox Developer Tools
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
to save the recording as a json file click "save".
Console messages - Firefox Developer Tools
the server-side library creates json objects from the messages and encodes them for transmission.
Web Console Helpers - Firefox Developer Tools
otherwise, json.stringify will be called on the argument, and the result will be copied to the clipboard.
The JavaScript input interpreter - Firefox Developer Tools
otherwise, json.stringify will be called on the argument, and the result will be copied to the clipboard.
about:debugging - Firefox Developer Tools
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.
AuthenticatorResponse - Web APIs
authenticatorassertionresponse authenticatorattestationresponse properties authenticatorresponse.clientdatajson a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get().
Using the Beacon API - Web APIs
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.
Blob - Web APIs
WebAPIBlob
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.
CSSStyleSheet.insertRule() - Web APIs
* @param {array} rules accepts an array of json-encoded declarations * @example addstylesheetrules([ ['h2', // also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green', true] // 'true' for !important rules ], ['.myclass', ['background-color', 'yellow'] ] ]); */ function addstylesheetrules (rules) { var styleel = document.createelement('style'); // append <style> eleme...
CrashReportBody - Web APIs
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.
DOMMatrixReadOnly - Web APIs
(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.
DOMPointInit.x - Web APIs
WebAPIDOMPointInitx
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.
DOMPointReadOnly - Web APIs
tojson() returns a json representation of the dompointreadonly object.
DOMQuad - Web APIs
WebAPIDOMQuad
domquad.tojson() returns a json representation of the domquad object.
How to create a DOM tree - Web APIs
you can automate the creation of a dom tree using a jxon reverse algorithm in association with the following json representation: { "people": { "person": [{ "address": [{ "@street": "321 south st", "@city": "denver", "@state": "co", "@country": "usa" }, { "@street": "123 main st", "@city": "arlington", "@state": "ma", "@country": "usa" }], "@first-name": "eric", "@middle-initial": "h", "@last-name": "ju...
ExtendableMessageEvent.data - Web APIs
var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.data); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessagee...
ExtendableMessageEvent.lastEventId - Web APIs
var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.lasteventid); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablem...
ExtendableMessageEvent.origin - Web APIs
var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.origin); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessag...
ExtendableMessageEvent.ports - Web APIs
var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessageevent.ports' in that spe...
ExtendableMessageEvent.source - Web APIs
var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.source); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessag...
FileSystemEntry.remove() - Web APIs
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.
GlobalEventHandlers.onerror - Web APIs
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.
History API - Web APIs
window.onpopstate = function(event) { alert(`location: ${document.location}, state: ${json.stringify(event.state)}`) } history.pushstate({page: 1}, "title 1", "?page=1") history.pushstate({page: 2}, "title 2", "?page=2") history.replacestate({page: 3}, "title 3", "?page=3") history.back() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back() // alerts "location: http://example.com/example.html, state: null" history.go(2) // alerts "location: h...
LargestContentfulPaint - Web APIs
methods largestcontentfulpaint.tojson() returns the above properties as json.
LayoutShift - Web APIs
methods layoutshift.tojson() converts the properties to json.
PaymentRequest.prototype.id - Web APIs
WebAPIPaymentRequestid
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.
PaymentRequest.shippingOption - Web APIs
quest)); }; // sync update to the total request.onshippingoptionchange = ev => { const shippingoption = shippingoptions.find( option => option.id === request.id ); const newtotal = { currency: "usd", label: "total due", value: calculatenewtotal(shippingoption), }; ev.updatewith({ ...details, total: newtotal }); }; async function checkshipping(request) { try { const json = request.shippingaddress.tojson(); await ensurecanshipto(json); const { shippingoptions, total } = await calculateshipping(json); return { ...details, shippingoptions, total }; } catch (err) { return { ...details, error: `sorry!
PaymentResponse.complete() - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); payment.show().then(function(paymentresponse) { var fetchoptions = { method: 'post', credentials: include, body: json.stringify(paymentresponse) }; var serverpaymentrequest = new request('secure/payment/endpoint'); fetch(serverpaymentrequest, fetchoptions).then( response => { if (response.status < 400) { paymentresponse.complete("success"); } else { paymentresponse.complete("fail"); }; }).catch( reason => { paymentresponse.complete("fail"); }); }).catch(function(err) { con...
PaymentResponse.details - Web APIs
the details read-only property of the paymentresponse interface returns a json-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine a successful funds transfer.
PaymentResponse.onpayerdetailchange - Web APIs
e.all(promisestovalidate).then(results => results.reduce((errors, result), object.assign(errors, result)) ); // if we found any errors, wait for them to be corrected if (object.getownpropertynames(errors).length) { await response.retry(errors); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things/", { method: "post", body: response.json() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); specifications specification status comment payment request apithe definition of 'onpayerdetailchange' in that specification.
PaymentResponse: payerdetailchange event - Web APIs
e.all(promisestovalidate).then(results => results.reduce((errors, result), object.assign(errors, result)) ); // if we found any errors, wait for them to be corrected if (object.getownpropertynames(errors).length) { await response.retry(errors); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things/", { method: "post", body: response.json() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); addeventlistener equivalent you could also set up the event handler using the addeventlistener() method: response.addeventlistener("payerdetailchange", async ev => { ...
PaymentResponse - Web APIs
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.
PerformanceNavigation - Web APIs
performancenavigation.tojson() is a jsonizer returning a json object representing the performancenavigation object.
PerformanceNavigationTiming - Web APIs
methods performancenavigationtiming.tojson() returns a domstring that is the json representation of the performancenavigationtiming object.
PerformanceResourceTiming - Web APIs
methods performanceresourcetiming.tojson() returns a domstring that is the json representation of the performanceresourcetiming object.
PerformanceServerTiming - Web APIs
methods performanceservertiming.tojson() returns a domstring that is the json representation of the performanceservertiming object.
PerformanceTiming - Web APIs
performancetiming.tojson() returns a json object representing this performancetiming object.
Performance API - Web APIs
the tojson() method returns a serialization of the performance object, for those attributes that can be serialized.
Performance Timeline - Web APIs
(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.
PopStateEvent - Web APIs
the popstate event as an example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "locati...
PublicKeyCredential.response - Web APIs
this object contains data from the client (authenticatorresponse/clientdatajson) and from the authenticator.
PushEvent.data - Web APIs
WebAPIPushEventdata
self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) ...
PushEvent - Web APIs
WebAPIPushEvent
self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new self.notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwin...
PushManager.register() - Web APIs
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
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
pushsubscription.tojson() standard serializer — returns a json representation of the subscription properties.
RTCIceCandidate - Web APIs
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.
RTCIceCandidateInit.candidate - Web APIs
if your client-side signaling layer builds and transmits a json string including the candidate to the remote peer, the remote peer might handle receiving that json message like this: function goticecandidatemessage(msg) { var icecandidate = new rtcicecandidate({ candidate: msg.candidate; }); pc.addicecandidate(icecandidate).catch({ /* handle error */ }); } it's helpful to note that for backward compatibility with older versions of the ...
RTCIceCandidateInit - Web APIs
it's also used as the return value from the rtcicecandidate.tojson() method, and can be passed directly into rtcpeerconnection.addicecandidate() to add a candidate to the peer connection.
RTCPeerConnection.addIceCandidate() - Web APIs
// this example assumes that the other peer is using a signaling channel as follows: // // pc.onicecandidate = event => { // if (event.candidate) { // signalingchannel.send(json.stringify({ice: event.candidate})); // "ice" is arbitrary // } else { // // all ice candidates have been sent // } // } signalingchannel.onmessage = receivedstring => { const message = json.parse(receivedstring); if (message.ice) { // a typical value of ice here might look something like this: // // {candidate: "candidate:0 1 udp 2122154243 192.168.1.9 53421 typ host", sd...
RTCPeerConnection.createAnswer() - Web APIs
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.
RTCPeerConnection.createOffer() - Web APIs
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.
Resource Timing API - Web APIs
the performanceresourcetiming interface's tojson() method returns a json serialization of a "resource" type performance entry.
Using the Screen Capture API - Web APIs
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.
ServiceWorkerGlobalScope.onpush - Web APIs
the data payload of the push message is available in the event object's data property (pushevent.data, which contains a pushmessagedata object.) self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) ...
StyleSheet.media - Web APIs
WebAPIStyleSheetmedia
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
jwk: json web key format.
SubtleCrypto - Web APIs
you can import keys from other systems, and support for standard formats like pkcs #8 and json web key helps you do this.
msManipulationViewsEnabled - Web APIs
example using a json file: { msmanipulationviewsenabled: true, } see also touch api microsoft api extensions ...
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
WebAPIURL
tojson() returns a usvstring containing the whole url.
Lifetime of a WebRTC session - Web APIs
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.
The WebSocket API (WebSockets) - Web APIs
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).
WebXR Device API - Web APIs
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.
Using the Web Storage API - Web APIs
s page (see events.js) the only javascript is as follows: window.addeventlistener('storage', function(e) { document.queryselector('.my-key').textcontent = e.key; document.queryselector('.my-old').textcontent = e.oldvalue; document.queryselector('.my-new').textcontent = e.newvalue; document.queryselector('.my-url').textcontent = e.url; document.queryselector('.my-storage').textcontent = json.stringify(e.storagearea); }); here we add an event listener to the window object that fires when the storage object associated with the current origin is changed.
Functions and classes available to Web Workers - Web APIs
in addition to the standard javascript set of functions (such as string, array, object, json, etc), there are a variety of functions available from the dom to workers.
Window.name - Web APIs
WebAPIWindowname
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.
WindowEventHandlers.onpopstate - Web APIs
examples for example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "locati...
Using XMLHttpRequest - Web APIs
|*| 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...
XMLHttpRequest.response - Web APIs
json the response is a javascript object created by parsing the contents of received data as json.
XMLHttpRequest.responseType - Web APIs
json the response is a javascript object created by parsing the contents of received data as json.
XMLHttpRequestResponseType - Web APIs
json the response is a javascript object created by parsing the contents of received data as json.
viewport-fit - CSS: Cascading Style Sheets
this descriptor hasn't been added to https://github.com/mdn/data/blob/master/css/at-rules.json yet.
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
WebHTMLElementabbr
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.
itemref - HTML: Hypertext Markup Language
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.
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
WebHTTPCORS
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.
Content Security Policy (CSP) - HTTP
WebHTTPCSP
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.
Using HTTP cookies - HTTP
WebHTTPCookies
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.
Cross-Origin Resource Policy (CORP) - HTTP
in response, chromium shipped cross-origin read blocking, which automatically protects certain resources (of content-type html, json and xml) against cross-origin reads.
Accept-Patch - HTTP
header type response header forbidden header name yes syntax accept-patch: application/example, text/example accept-patch: text/example;charset=utf-8 accept-patch: application/merge-patch+json directives none examples accept-patch: application/example, text/example accept-patch: text/example;charset=utf-8 accept-patch: application/merge-patch+json specifications specification title rfc 5789, section 3.1: accept-patch http patch ...
CSP: report-to - HTTP
syntax content-security-policy: report-to <json-field-value>; examples see content-security-policy-report-only for more information and examples.
Content-Security-Policy - HTTP
these violation reports consist of json documents sent via an http post request to the specified uri.
HTTP headers - HTTP
WebHTTPHeaders
these violation reports consist of json documents sent via an http post request to the specified uri.
A re-introduction to JavaScript (JS tutorial) - JavaScript
this syntax is also the core of json format and should be preferred at all times.
Grammar and types - JavaScript
line-feed.` // multiline strings `in javascript, template strings can run over multiple lines, but double and single quoted strings cannot.` // string interpolation var name = 'bob', time = 'today'; `hello ${name}, how are you ${time}?` // construct an http request prefix used to interpret the replacements and construction post`http://foo.org/bar?a=${a}&b=${b} content-type: application/json x-credentials: ${credentials} { "foo": ${foo}, "bar": ${bar}}`(myonreadystatechangehandler); you should use string literals unless you specifically need to use a string object.
JavaScript technologies overview - JavaScript
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.
JavaScript error reference - JavaScript
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.
Array.prototype.filter() - JavaScript
find all prime numbers in an array the following example returns all prime numbers in the array: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log(array.filter(isprime)); // [2, 3, 5, 7, 11, 13] filtering invalid entries from json the following example uses filter() to create a filtered json of all elements with non-zero, numeric id.
Array.prototype.shift() - JavaScript
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.
Array.prototype.slice() - JavaScript
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.
Intl.Locale.prototype.toString() - JavaScript
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.
Number - JavaScript
(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.
Promise.prototype.finally() - JavaScript
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.
Promise.prototype.then() - JavaScript
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.
Symbol - JavaScript
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().
uneval() - JavaScript
note: this will not return a json representation of object.
Lexical grammar - JavaScript
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.
for await...of - JavaScript
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.
try...catch - JavaScript
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.
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
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.
Introduction to progressive web apps - Progressive web apps (PWAs)
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.
Structural overview of progressive web apps - Progressive web apps (PWAs)
other apps might use json or other formats for this data.
Progressive web apps (PWAs)
manifest file a json file that controls how your app appears to the user and ensures that progressive web apps are discoverable.
Tutorials
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.
XPath
related topics xslt, xquery, xml, dom, jxon, jsonpath comparison of css selectors and xpath ...