Search completed in 1.72 seconds.
JS_AlreadyHasOwnProperty
this article covers features introduced in spidermonkey 1.8 determine whether a property is al
ready physically present on a jsobject.
... syntax boo js_al
readyhasownproperty(jscontext *cx, js::handleobject obj, const char *name, bool *foundp); boo js_al
readyhasownucproperty(jscontext *cx, js::handleobject obj, const char16_t *name, size_t namelen, bool *foundp); boo js_al
readyhasownpropertybyid(jscontext *cx, js::handleobject obj, js::handleid id, bool *foundp); // added in spidermonkey 1.8.1 boo js_al
readyhasownelement(jscontext *cx, js::handleobject obj, uint32_t index, bool *foundp); name type description cx jscontext * pointer to a js context.
... name or id const char * or const char16_t *or js::handleid (in js_al
readyhasownproperty, al
readyhasownucproperty, and js_al
readyhasownpropertybyid) the name of the property to search for.
...And 4 more matches
WritableStreamDefaultWriter.ready - Web APIs
the
ready read-only property of the writablestreamdefaultwriter interface returns a promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.
... syntax var promise = writablestreamdefaultwriter.
ready; value a promise.
... example the following example shows two uses of the
ready property.
...And 4 more matches
Document.readyState - Web APIs
the document.
readystate property describes the loading state of the document.
... when the value of this property changes, a
readystatechange event fires on the document object.
... syntax var string = document.
readystate; values the
readystate of a document can be one of following: loading the document is still loading.
...And 3 more matches
IDBRequest.readyState - Web APIs
the
readystate read-only property of the idbrequest interface returns the state of the request.
... syntax var current
readystate = request.
readystate; value the idbrequest
readystate of the request, which takes one of the following two values: value meaning pending the request is pending.
...the
readystate of the 2nd request is logged to the developer console.
...And 3 more matches
already_AddRefed
« xpcom api reference al
ready_addrefed in association with nscomptr allows you to assign in a pointer without addrefing it.
... you may want to use this as a return type from a function that has al
ready produced an addrefed pointer as a result.
... in fact, it is preferred to use al
ready_addrefed in this case over returning a raw pointer or nscomptr (see the nscomptr user manual).
...And 2 more matches
Animation.ready - Web APIs
the read-only animation.
ready property of the web animations api returns a promise which resolves when the animation is
ready to play.
... a new promise is created every time the animation enters the "pending" play state as well as when the animation is canceled, since in both of those scenarios, the animation is
ready to be started again.
... syntax var
readypromise = animation.
ready; value a promise which resolves when the animation is
ready to be played.
...And 2 more matches
MediaSource.readyState - Web APIs
the
readystate read-only property of the mediasource interface returns an enum representing the state of the current mediasource.
... open: the source is attached to a media element and
ready to receive sourcebuffer objects.
... syntax var my
readystate = mediasource.
readystate; value a domstring.
...And 2 more matches
EventSource.readyState - Web APIs
the
readystate read-only property of the eventsource interface returns a number representing the state of the connection.
... syntax var my
readystate = eventsource.
readystate; value a number representing the state of the connection.
... possible values are: 0 — connecting 1 — open 2 — closed examples var evtsource = new eventsource('sse.php'); console.log(evtsource.
readystate); note: you can find a full example on github — see simple sse demo using php.
... specifications specification status comment html living standardthe definition of '
readystate' in that specification.
HTMLMediaElement.readyState - Web APIs
the htmlmediaelement.
readystate property indicates the readiness state of the media.
... syntax var
readystate = audioorvideo.
readystate; value an unsigned short.
... <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addeventlistener('loadeddata', function() { if(obj.
readystate >= 2) { obj.play(); } }); specifications specification status comment html living standardthe definition of 'htmlmediaelement.
readystate' in that specification.
... living standard html5the definition of 'htmlmediaelement.
readystate' in that specification.
RTCDataChannel.readyState - Web APIs
the read-only rtcdatachannel property
readystate returns an enum of type rtcdatachannelstate which indicates the state of the data channel's underlying data connection.
... syntax var state = adatachannel.
readystate; values a string which is one of the values in the rtcdatachannelstate enum, indicating the current state of the underlying data transport.
... example var datachannel = peerconnection.createdatachannel("file transfer"); var sendqueue = []; function sendmessage(msg) { switch(datachannel.
readystate) { case "connecting": console.log("connection not open; queueing: " + msg); sendqueue.push(msg); break; case "open": sendqueue.foreach((msg) => datachannel.send(msg)); break; case "closing": console.log("attempted to send message while closing: " + msg); break; case "closed": console.log("error!
... attempt to send while connection closed."); break; } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.
readystate' in that specification.
WebSocket.readyState - Web APIs
the websocket.
readystate read-only property returns the current state of the websocket connection.
... syntax var
readystate = awebsocket.
readystate; value one of the following unsigned short values: value state description 0 connecting socket has been created.
... 1 open the connection is open and
ready to communicate.
... specifications specification status comment html living standardthe definition of 'websocket:
readystate' in that specification.
XMLHttpRequest.onreadystatechange - Web APIs
an eventhandler that is called whenever the
readystate attribute changes.
...the xmlhttprequest.on
readystatechange property contains the event handler to be called when the
readystatechange event is fired, that is every time the
readystate property of the xmlhttprequest changes.
... syntax xmlhttprequest.on
readystatechange = callback; values callback is the function to be executed when the
readystate changes.
... examples const xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.on
readystatechange = function () { // in local files, status is 0 upon success in mozilla firefox if(xhr.
readystate === xmlhttprequest.done) { var status = xhr.status; if (status === 0 || (status >= 200 && status < 400)) { // the request has been completed successfully console.log(xhr.responsetext); } else { // oh no!
NPP_WriteReady - Archive of obsolete content
syntax #include <npapi.h> int32 npp_write
ready(npp instance, npstream* stream); parameters the function has the following parameters: instance pointer to the current plug-in instance.
... description the browser calls npp_write
ready before each call to npp_write to determine whether a plug-in can receive data and how many bytes it can receive.
...the npp_write function may pass a larger buffer, but the plug-in is required to consume only the amount of data returned by npp_write
ready.
Document: readystatechange event - Web APIs
the
readystatechange event is fired when the
readystate attribute of a document has changed.
... bubbles no cancelable no interface event event handler property on
readystatechange examples live example html <div class="controls"> <button id="reload" type="button">reload</button> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js const log = document.queryselector('.event-log-contents'); const reload = document.querys...
...elector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('
readystatechange', (event) => { log.textcontent = log.textcontent + `
readystate: ${document.
readystate}\n`; }); document.addeventlistener('domcontentloaded', (event) => { log.textcontent = log.textcontent + `domcontentloaded\n`; }); result specifications specification status comment html living standardthe definition of '
readystatechange' in that specification.
FileReader.readyState - Web APIs
the filereader
readystate property provides the current state of the reading operation a filereader is in.
... example var reader = new filereader(); console.log('empty', reader.
readystate); //
readystate will be 0 reader.readastext(blob); console.log('loading', reader.
readystate); //
readystate will be 1 reader.onloadend = function () { console.log('done', reader.
readystate); //
readystate will be 2 }; value a number which is one of the three possible state constants define for the filereader api.
... specifications specification status comment file apithe definition of '
readystate' in that specification.
MediaStreamTrack.readyState - Web APIs
the mediastreamtrack.
readystate read-only property returns an enumerated value giving the status of the track.
... syntax const state = track.
readystate value it takes one of the following values: "live" which indicates that an input is connected and does its best-effort in providing real-time data.
... specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.
readystate' in that specification.
ServiceWorkerContainer.ready - Web APIs
the
ready read-only property of the serviceworkercontainer interface provides a way of delaying code execution until a service worker is active.
... syntax navigator.serviceworker.
ready.then(function(serviceworkerregistration) { ...
... example if ('serviceworker' in navigator) { navigator.serviceworker.
ready .then(function(registration) { console.log('a service worker is active:', registration.active); // at this point, you can call methods that require an active // service worker, like registration.pushmanager.subscribe() }); } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration.
ready' in that specification.
XMLHttpRequest.readyState - Web APIs
the xmlhttprequest.
readystate property returns the state an xmlhttprequest client is in.
...instead of unsent, opened, headers_received, loading and done, the names
readystate_uninitialized (0),
readystate_loading (1),
readystate_loaded (2),
readystate_interactive (3) and
readystate_complete (4) are used.
... example var xhr = new xmlhttprequest(); console.log('unsent', xhr.
readystate); //
readystate will be 0 xhr.open('get', '/api', true); console.log('opened', xhr.
readystate); //
readystate will be 1 xhr.onprogress = function () { console.log('loading', xhr.
readystate); //
readystate will be 3 }; xhr.onload = function () { console.log('done', xhr.
readystate); //
readystate will be 4 }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
updateready - Archive of obsolete content
the update
ready event is fired when the resources listed in the application cache manifest have been newly redownloaded, and the script can use swapcache() to switch to the new cache.
... related events checking noupdate downloading progress cached update
ready obsolete error ...
FontFaceSet.ready - Web APIs
the
ready readonly property of the fontfaceset interface returns a promise that resolves to the given fontfaceset.
... syntax fontfaceset.
ready.then(function(fontfaceset) { // ...
Index - Web APIs
77 animation.
ready api, animation, experimental, property,
ready,
ready promise, reference, web animations, web animations api the read-only animation.
ready property of the web animations api returns a promise which resolves when the animation is
ready to play.
... a new promise is created every time the animation enters the "pending" play state as well as when the animation is canceled, since in both of those scenarios, the animation is
ready to be started again.
... 180 audioprocessingevent api, deprecated, interface, internationalization, reference, référence(2), web audio api the web audio api audioprocessingevent represents events that occur when a scriptprocessornode input buffer is
ready to be processed.
...And 70 more matches
tabs - Archive of obsolete content
tabs.on('
ready', function(tab) { console.log('tab is loaded', tab.title, tab.url); }); access tabs the module itself can be used as a list of all opened tabs across all windows.
... in particular, you can enumerate it: var tabs = require('sdk/tabs'); for (let tab of tabs) console.log(tab.title); you can also access individual tabs by index: var tabs = require('sdk/tabs'); tabs.on('
ready', function () { console.log('first: ' + tabs[0].title); console.log('last: ' + tabs[tabs.length-1].title); }); you can access the currently active tab: var tabs = require('sdk/tabs'); tabs.on('activate', function () { console.log('active: ' + tabs.activetab.url); }); track a single tab given a tab, you can register event listeners to be notified when the tab is closed, activated or deactivated, or when the page hosted by the tab is loaded or retrieved from the "back-forward cache": var tabs = require("sdk/tabs"); function onopen(tab) { console.log(tab.url + " is open")...
...ole.log(tab.url + " is activated"); } function logdeactivate(tab) { console.log(tab.url + " is deactivated"); } function logclose(tab) { console.log(tab.url + " is closed"); } tabs.on('open', onopen); manipulate a tab you can get and set various properties of tabs (but note that properties relating to the tab's content, such as the url, will not contain valid values until after the tab's
ready event fires).
...And 16 more matches
sslfnc.html
to change a value in a socket that is al
ready open, use ssl_optionset.
... as mentioned in communication, when an application imports a socket into ssl after the tcp connection on that socket has al
ready been established, it must call ssl_resethandshake to determine whether the socket is for a client or server.
...however, these settings control the behavior of pr_connect and pr_accept only; if you don't call one of those functions after importing a non-ssl socket with ssl_import (as in the case of an al
ready established tcp connection), ssl still needs to know whether the application is functioning as a client or server.
...And 14 more matches
Getting Started Guide
if you're al
ready familiar with nscomptrs, then you might want to skip ahead to the reference manual or the faq.
...you should al
ready know this, and should be able to just skim this short section.
... if this is unfamiliar material, you're not
ready for nscomptrs yet.
...And 14 more matches
Streams - Plugins
the browser calls the plug-in methods npp_newstream, npp_write
ready, npp_write, and npp_destroystream to, respectively, create a stream, find out how much data the plug-in can handle, push data into the stream, and delete it.
... the plug-in can set the output parameter type to one of these transmission modes: np_normal: (default): the plug-in can process the data progressively as it arrives from the network or file system through a series of calls to npp_write
ready and npp_write.
... finding out how much data the plug-in can accept after a call to npp_newstream and before writing data to the plug-in, the browser calls npp_write
ready to determine the maximum number of bytes that the plug-in can consume.
...And 14 more matches
Front-end web developer - Learn web development
for example, if you al
ready know html, you can skip ahead to the css section.
... how will i know i'm
ready to move on?
...it is important to get you set up and
ready to do work for exercises later on in the course.
...And 11 more matches
Client-side storage - Learn web development
you are now
ready to start adding code to it.
... inside the window.onload handler, add the following: // open our database; it is created if it doesn't al
ready exist // (see onupgradeneeded below) let request = window.indexeddb.open('notes_db', 1); this line creates a request to open version 1 of a database called notes_db.
... if this doesn't al
ready exist, it will be created for you by subsequent code.
...And 11 more matches
Index
6 creating a python xpcom component guide, needshelp, pyxpcom, xpcom, xpcom:language bindings creating applications with mozilla al
ready provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
...the result is structured cloned back to the original context, unless it is native (for example, if it returns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper al
ready), so it's guaranteed to behave predictably.
...any time a new value is assigned into an nscomptr, the nscomptr automatically always releases its old referent, if any, and (unless you tell it you al
ready have) addrefs the new.
...And 11 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.
...since the message has al
ready been stringified, we can send it with no further processing.
...each peer sends candidates in the order they're discovered, and keeps sending candidates until it runs out of suggestions, even if media has al
ready started streaming.
...And 11 more matches
nsIFile
copyto() this method copies a source file to a new location if it does not al
ready exist.
... ns_error_file_al
ready_exists indicates that there is al
ready a file named "newname" in the destination directory.
... copytofollowinglinks() this method copies a source file to a new location if it does not al
ready exist.
...And 10 more matches
ui/frame - Archive of obsolete content
if the frame script initiates the conversation, you need to specify "*" as the origin: window.parent.postmessage("ping", "*"); if the frame script has received a message from the add-on al
ready, it can use the origin property of the event object passed to the message hander: // listen for messages from the add-on, and send a reply window.addeventlistener("message", function(event) { event.source.postmessage("pong", event.origin) }, false); this frame script listens to change events on the "city-selector" <select> element, and sends a message to the add-on containing the value for th...
... toolbar } = require("sdk/ui/toolbar"); var frame = new frame({ url: "./city-info.html", onmessage: function(e) { // message only the frame that pinged us e.source.postmessage("pong", e.origin); } }); var toolbar = toolbar({ name: "ping-pong", title: "ping pong", items: [frame] }); this does not have to be the message event: the other events frame can emit: attach, load and
ready, also provide access to source and origin.
... on
ready function assign a listener to the frame's
ready event.
...And 9 more matches
HTTP Cache
important difference in behavior from the old cache: when the cache entry object is al
ready present in memory or open as “force-new” (a.k.a “open-truncate”) this callback is invoked sooner then the asyncopenuri method returns (i.e.
... the writer stored all necessary meta data in the cache entry and called metadata
ready on it: other consumers now get the entry and may examine and potentially modify the meta data and read the data (if any) of the cache entry.
...the response payload) to write to the cache entry, it must open the output stream on it before it calls metadata
ready.
...And 9 more matches
OS.File for the main thread
the following variant does the same thing but will fail if "file.txt" al
ready exists: let encoder = new textencoder(); // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp", nooverwrite: t...
...promise = os.file.move(os.path.join('c:', 'jean', 'test.txt'), os.path.join('c:', 'jean', 'testrenamed.txt')); promise.then( function() { console.log('rename successful') }, function(arejectreason) { console.log('rename failed, arejectreason = ', arejectreason) } ) the nooverwrite true is important, as default is false which means if a file in the directory exists al
ready with the same name it will no longer be there after this "rename" operation, which is a "move".
... file.close(); }, function onerror(reason) { file.close(); throw reason; }); return promise; } or a variant using task.js (or at least the subset al
ready present on mozilla-central): let writestream = function writestream(data, outfile, chunksize) { return task.spawn(function() { let view = new uint8array(data); let pos = 0; while (pos < view.bytelength) { pos += yield outfile.write(view.subarray(pos, chunksize)); } outfile.close(); }).then( null, function onfailure(reason) { outfile.close(); thro...
...And 9 more matches
nsIZipWriter
ns_error_file_al
ready_exists the specified path al
ready exists in the zip file.
... ns_error_in_progress the zip writer is al
ready performing another operation.
... ns_error_file_al
ready_exists the specified path al
ready exists in the zip file.
...And 9 more matches
Getting Started - Developer guides
at this stage, you need to tell the xmlhttp request object which javascript function will handle the response, by setting the on
readystatechange property of the object and naming it after the function to call when the request changes state, like this: httprequest.on
readystatechange = nameofthefunction; note that there are no parentheses or parameters after the function name, because you're assigning a reference to the function, rather than actually calling it.
... alternatively, instead of giving a function name, you can use the javascript technique of defining functions on the fly (called "anonymous functions") to define the actions that will process the response, like this: httprequest.on
readystatechange = function(){ // process the server response here.
...for example, use the following before calling send() for form data sent as a query string: httprequest.setrequestheader('content-type', 'application/x-www-form-urlencoded'); step 2 – handling the server response when you sent the request, you provided the name of a javascript function to handle the response: httprequest.on
readystatechange = nameofthefunction; what should this function do?
...And 9 more matches
Index - Archive of obsolete content
135 cfx to jpm cfx, jpm, sdk, add-on a guide to working with jpm if you're al
ready familiar with cfx.
...after the "escrowauthoritycert" parameter, the method takes some javascript code that is invoked when the crmf request is
ready.
...the private key for the certificates must al
ready reside in the user's personal private key database.
...And 8 more matches
WebIDL bindings
dosomethingelse(optional long maybenumber); [throws] void dosomethingelse(myinterface otherinstance); void dotheother(any something); void doyetanotherthing(optional boolean actuallydoit = false); static void staticoperation(any arg); }; will require these method declarations: class myclass { void dosomething(int32_t anumber); double dosomething(myclass* aotherinstance); al
ready_addrefed<myinterface> dosomethingelse(optional<int32_t> amaybenumber, errorresult& rv); void dosomethingelse(myclass& aotherinstance, errorresult& rv); void dotheother(jscontext* cx, js::value asomething); void doyetanotherthing(bool aactuallydoit); static void staticoperation(const globalobject& aglobal, js::value asomething); } c++ re...
... for example, this idl: [constructor, constructor(unsigned long somenumber)] interface myinterface { }; will require the following declarations in myclass: class myclass { // various nsisupports stuff or whatnot static al
ready_addrefed<myclass> constructor(const globalobject& aglobal, errorresult& rv); static al
ready_addrefed<myclass> constructor(const globalobject& aglobal, uint32_t asomenumber, errorresult& rv); }; c++ reflections of webidl types the exact c++ representation for webidl types ...
... date mozilla::dom::date domstring const nsastring& mozilla::dom::domstring& (outparam) nsastring& (outparam) nsstring& (outparam) nsstring utf8string const nsacstring& nsacstring& (outparam) nscstring double double double double float float float float interface: non-nullable foo& al
ready_addrefed<foo> foo* owningnonnull<foo> interface: nullable foo* al
ready_addrefed<foo> foo* refptr<foo> long int32_t int32_t int32_t long long int64_t int64_t int64_t object js::handle<jsobject*> js::mutablehandle<jsobject*> jsobject* octet uint8_t uint8_t uint8_t sequence cons...
...And 8 more matches
DevTools API - Firefox Developer Tools
toolbox-
ready(toolbox) a new toolbox has been created and is
ready to use.
... {toolid}-
ready(toolbox, panel) a tool with the given id has finished its initialization and is
ready to be used.
... getpanelwhen
ready(toolid) similar to getpanel() but waits for the tool to load first.
...And 8 more matches
dev/panel - Archive of obsolete content
you can use the class utility function: const { panel } = require("dev/panel"); const { class } = require("sdk/core/heritage"); const mypanel = class({ extends: panel, label: "my panel", tooltip: "my new devtool", icon: "./my-devtool.png", url: "./my-devtool.html", setup: function(options) { // my setup goes here }, dispose: function() { // my teardown goes here }, on
ready: function() { // i can send messages to // the panel document here } }); alternatively, you can use the extend function: const { extend } = require("sdk/core/heritage"); function mypanel() {}; mypanel.prototype = extend(panel.prototype, { label: "my panel", tooltip: "...", ....
... optional on
ready function an event handler that will be called when the document in the panel becomes interactive.
... it's equivalent to document.
readystate === "interactive".
...And 7 more matches
Error codes returned by Mozilla APIs
ns_error_al
ready_initialized (0xc1f30002) an attempt is made to initialize a component or object again which has al
ready been initialized.
... ns_error_file_al
ready_exists (0x80520008) an attempt was made to create a file that al
ready exists.
... ns_error_file_is_locked (0x8052000e) this error indicates that a file cannot be accessed because it is locked, typically because the file is al
ready being used by another application.
...And 7 more matches
Extending a Protocol
implementing the navigator.echo() in your favorite editor, open dom/webidl/navigator.webidl at the end of the file, add: partial interface navigator { [throws] promise<domstring> echo(domstring astring); }; now we need to implement the echo() method in c++, so open up ./dom/base/navigator.h and let's add the method definition, so under public:: al
ready_addrefed<promise> echo(const nsastring& astring, errorresult& arv); we use nsastring& as the domstring comes in from js as utf-16.
... now let's implement the method in ./dom/base/navigator.cpp - we add a little bit of error boilerplate stuff, as is customary: al
ready_addrefed<promise> navigator::echo(const nsastring& astring, errorresult& arv) { if (!mwindow || !mwindow->getdocshell()) { arv.throw(ns_error_unexpected); return nullptr; } refptr<promise> echopromise = promise::create(mwindow->asglobal(), arv); if (ns_warn_if(arv.failed())) { return nullptr; } // message passing magic will happen here!
... defining windowglobalparent's alloc/deallocpechoparent() open up dom/ipc/windowglobalparent.h and we are going to add two things: at the top, add #include "mozilla/dom/echoparent.h" and then, as part of the windowglobalparent class definition, add the following two public methods: al
ready_addrefed<echoparent> allocpechoparent(); bool deallocpechoparent(pechoparent* aactor); natrually, we will have to do the alloc/dealloc dance for the children too.
...And 6 more matches
L20n Javascript API
you can listen to the
ready event (emitted by the context instance when all the resources have been compiled) and use ctx.getsync and ctx.getentitysync to get translations synchronously.
... alternatively, you can register callbacks to execute when the context is
ready (or when globals change and translations need to be updated) with ctx.localize.
...this array (with defaultlocale appended to it if it is not al
ready present) will be used to negotiate the fallback chain for the user.
...And 6 more matches
Index
a trust anchor is just another x.509 certificate that is al
ready known and has been deliberately marked as trusted by a software vendor, administrators inside an organizational infrastructure, or the software user.
...when using an ssl network connection, you'll al
ready have two layers, the basic nspr layer and an ssl library layer.
...(note: mozilla does not distribute a "fips mode"-
ready nss with firefox.) this page attempts to provide an informal explanation of what it is, who would use it, and why.
...And 6 more matches
Necko walkthrough
nspipeinputstream::asyncwait sets the callback to be used later for a response if a target is specified (in this case, the main thread), callback is proxied via an nsinputstream
readyevent, which is created now and may be called later otherwise, the callback would be called directly, when the socket is readable et voila, the transaction has been posted to the socket thread, and the main thread continues on, unblocked from network io.
... if a connection entry al
ready exists matching the required conn info, then that one will be used; otherwise a new one is created (makenewconnection - creates socket etc.).
... nshttpconnection::activate this connection is passed the transaction nshttpconnection::onoutputstream
ready nshttpconnection::onsocketwritable tries to write the request data from the current transaction (mtransaction) tells the transaction to now wait (`resumerecv) nshttpconnection::resumerecv nshttptransaction::readsegments readrequestsegment is passed to mrequeststream->readsegments - this function pointer is called and used to read the request bytes, which in turn calls ...
...And 6 more matches
Starting WebLock
we have al
ready created a module that implements most of the generic component functionality (e.g.
...this process is similar to using createinstance from the nsicomponentmanager, but there is no aggregation parameter since the object has al
ready been constructed.
... there are two startup notifications, both of which create the observer if it isn't al
ready created.
...And 6 more matches
Event reference
media events event name fired when audioprocess the input buffer of a scriptprocessornode is
ready to be processed.
... emptied the media has become empty; for example, this event is sent if the media has al
ready been loaded (or partially loaded), and the load() method is called to reload it.
... playing playback is
ready to start after having been paused or delayed due to lack of data.
...And 6 more matches
page-mod - Archive of obsolete content
attachto controls whether to attach scripts to tabs that were al
ready open when the page-mod was created, and whether to attach scripts to iframes as well as the topmost document.
... for example, if you maintain a list of workers attached to a page-mod: var workers = []; var pagemod = require("sdk/page-mod").pagemod({ include: ['*'], contentscriptwhen: '
ready', contentscriptfile: data.url('pagemod.js'), onattach: function(worker) { workers.push(worker); } }); you can remove workers when they are no longer valid by listening to detach: var workers = []; function detachworker(worker, workerarray) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } var pagemod = require("sdk/page-mod").pa...
...gemod({ include: ['*'], contentscriptwhen: '
ready', contentscriptfile: data.url('pagemod.js'), onattach: function(worker) { workers.push(worker); worker.on('detach', function () { detachworker(this, workers); }); } }); cleaning up on add-on removal content scripts receive a detach message when the add-on that attached them is disabled or removed: you can use this in the content script to undo any changes that you've made.
...And 5 more matches
Index - Learn web development
you've seen this stuff al
ready in the course, but only in passing — here we'll discuss it all explicitly.
... 140 css layout beginner, css, floating, grids, guide, landing, layout, learn, module, multiple column, positioning, alignment, flexbox, float, table at this point we've al
ready looked at css fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside.
... 153 test your skills: fundamental layout comprehension assessment, beginner, css, layout, learn if you have worked through this module then you will have al
ready covered the basics of what you need to know to do css layout today, and to work with older css as well.
...And 5 more matches
Introducing a complete toolchain - Learn web development
in addition, you should include tests before you deploy to your production server to ensure your software works as intended — this al
ready sounds like a necessary toolchain.
... once you've signed up for github (click the sign up link on the homepage if you don't al
ready have an account, and follow the instructions), you can use your github account for authentication on netlify (click sign up, then choose github from the "sign up with one of the following" list), so technically you only need to create one new account.
...you should have node.js and npm installed al
ready, but if not, refer back to that section.
...And 5 more matches
sslerr.html
sec_error_duplicate_cert -8170 certificate al
ready exists in your database.
... sec_error_duplicate_cert_name -8169 downloaded certificate's name duplicates one al
ready in your database.
... sec_error_cert_nickname_collision -8124 a certificate with the same nickname al
ready exists.
...And 5 more matches
Bytecode Descriptions
val must al
ready be a numeric value, such as the result of jsop::tonumeric.
...there must not al
ready be a generator object for the current frame (that is, this instruction must execute at most once per generator or async call).
...if the current function is an async function or async generator, the frame's return value slot must contain the current frame's result promise, which must al
ready be resolved or rejected.
...And 5 more matches
nsIAccessibleRetrieval
create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it al
ready exists.
...create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it al
ready exists.
...create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it al
ready exists.
...And 5 more matches
Reference Manual
this section will help you if you're al
ready familiar with nscomptr but you need details.
...e(nsisupports*, nsresult*) do_queryreferent(nsiweakreference*), do_queryreferent(nsiweakreference*, nsresult*) don't addref dont_addref(t*), getter_addrefs(t*) n/a e.g., one of the possibilities for assigning into an nscomptr, but you don't want to addref the pointer you are assigning (because it has al
ready been addrefed for some reason) is dont_addref(t*) found at the intersection of "don't addref" and "don't qi".
...nscomptr<nsifoo> foo( dont_queryinterface(afooptr) ); // or foo = dont_queryinterface(afooptr); by using this form, you are promising that the pointer you are assigning in is al
ready a pointer to the xpcom-correct interface matching the nscomptrs underlying type, in this case, nsifoo.
...And 5 more matches
Using IndexedDB - Web APIs
if the database doesn't al
ready exist, it is created by the open operation, then an onupgradeneeded event is triggered and you create the database schema in the handler for this event.
...you should create the object stores needed for this version of the database: // this event is only implemented in recent browsers request.onupgradeneeded = function(event) { // save the idbdatabase interface var db = event.target.result; // create an objectstore for this database var objectstore = db.createobjectstore("name", { keypath: "mykey" }); }; in this case, the database will al
ready have the object stores from the previous version of the database, so you do not have to create these object stores again.
...if you need to save that information, you should read it out and save it somewhere else before upgrading the database.) trying to create an object store with a name that al
ready exists (or trying to delete an object store with a name that does not al
ready exist) will throw an error.
...And 5 more matches
widget - Archive of obsolete content
scripting trusted widget content we've al
ready seen that you can package html files in your add-on's data directory and use them to define the widget's content.
...widgets.widget({ id: "auto-update-widget", label: "widget that updates content on a timer", content: "0", contentscript: 'settimeout(function() {' + ' document.body.innerhtml++;' + '}, 2000)', contentscriptwhen: "
ready" }); // a widget created with a specified width, that grows.
...var widget = widgets.widget({ id: "message-test", label: "bi-directional communication!", content: "<foo>bar</foo>", contentscriptwhen: "
ready", contentscript: 'self.on("message", function(message) {' + ' alert("got message: " + message);' + '});' + 'self.postmessage("
ready");', onmessage: function(message) { if (message == "
ready") widget.postmessage("me too"); } }); globals constructors widget(options) creates a new widget.
...And 4 more matches
CSS3 - Archive of obsolete content
while some modules are al
ready w3c recommendations, other still are early working drafts.
...some modules, like selectors 4 or css borders and backgrounds level 4 al
ready have an editor's draft, though they haven't yet reached the first published working draft status.
... css modules status completed modules a few css modules al
ready became a standard as a w3c recommendation.
...And 4 more matches
MMgc - Archive of obsolete content
it has a get method which returns the pointer to the original object, or null if that object has al
ready been destroyed.
...in order to be correct we must account for a new or unmarked object being stored into an object we've al
ready marked.
... in implementation terms this means a new or unmarked object is stored in an object that has al
ready been processed by the marking algorithm and is no longer in the queue.
...And 4 more matches
JavaScript Client API - Archive of obsolete content
depending of what type of data you're working with, you might al
ready have guids built into your data that you can make use of (note that guids must be allowed to change and should be url friendly).
...unless the items you're syncing have their own inherent guids al
ready defined, you'll need to invent guids for all your items at this time.
... invent guids for any items // that don't have them al
ready, and remember the mapping for later use.
...And 4 more matches
Building up a basic demo with A-Frame - Game development
the webxr and webgl apis al
ready enable us to start creating virtual reality (vr) experiences inside web browsers, but the community is still waiting for tools and libraries to appear, to make this easier.
... high level overview the current version of a-frame is 0.3.2, which means it's highly experimental, but it al
ready works and you can test it right away in the browser.
...add it now: <a-box color="#0095dd" position="0 1 0" rotation="20 40 0"> </a-box> it contains a few parameters al
ready defined: color, position and rotation — these are fairly obvious, and define the base color of the cube, the position inside the 3d scene, and the rotation of the cube.
...And 4 more matches
TypeScript support in Svelte - Learn web development
code along with us git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/07-typescript-support or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/07-typescript-support remember to run npm install && npm run dev to start your app in development mode.
...thanks to the hard work of the svelte team, together with many contributors, we have an official solution
ready to be put to the test.
... porting our to-do list app to typescript now we are
ready to start porting our to-list application to take advantage of all the features that typescript offers to us.
...And 4 more matches
Package management basics - Learn web development
you could certainly code this yourself, but there's a strong chance that someone else has al
ready solved this problem — why waste time reinventing the wheel?
... we've met npm al
ready, but stepping back from npm itself, a package manager is a system that will manage your project dependencies.
... installing parcel run the following command to install parcel locally: npm install parcel-bundler once that's done all the things, we're now
ready for some "modern client-side development" (which really means using build tools to make the developer experience a little easier).
...And 4 more matches
Accessible Toolkit Checklist
the approaches there are two basic kinds of toolkits, which each provide different challenges when implementing accessibility: native widget toolkits , like eclipse and wxwidgets, al
ready have some accessibility built-in.
...since the individual widgets predominately come from the operating system, they al
ready implement standard keyboard commands and follow the operating system's visual theme.
... also, assistive technologies al
ready understand native widgets so it is only necessary to implement microsoft active accessibility (msaa) api support for custom controls.
...And 4 more matches
nsIXPConnect
nsixpconnectwrappednative getwrappednativeofjsobject( in jscontextptr ajscontext, in jsobjectptr ajsobj ); parameters ajscontext missing description ajsobj missing description return value missing description exceptions thrown missing exception missing description getwrappednativeofnativeobject() this only succeeds if the native object is al
ready wrapped by xpconnect.
... note: in c++, the out jsval parameter must al
ready be a strong gc root.
... nsixpconnectjsobjectholder holdobject( in jscontextptr ajscontext, in jsobjectptr aobject ); parameters ajscontext missing description aobject missing description return value missing description exceptions thrown missing exception missing description initclasses() initializes classes on a global object that has al
ready been created.
...And 4 more matches
Using writable streams - Web APIs
write(chunk,controller) — a method that is called repeatedly every time a new chunk is
ready to be written to the underlying sink (specified in the chunk parameter).
...: sendmessage("hello, world.", writablestream); the sendmessage() definition looks like so: function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } so here we create a writer to write the chunks to the stream using writablestream.getwriter().
...And 4 more matches
Cross-browser audio basics - Developer guides
// associate functions with the 'onclick' events play.onclick = playaudio; pause.onclick = pauseaudio; function playaudio() { myaudio.play(); } function pauseaudio() { myaudio.pause(); } } media loading events above we have shown how you can create a very simple audio player, but what if we want to show progress, buffering and only activate the buttons when the media is
ready to play?
...the playhead is in position but not quite
ready to play.
... myaudio.addeventlistener("progress", function() { // you could let the user know the media is downloading }); canplay canplay is a useful event to detect should you want to determine whether the media is
ready to play.
...And 4 more matches
ui/sidebar - Archive of obsolete content
there are two events emitted by the sidebar which will give you a worker: attach and
ready.
... listen to attach if the first message in your add-on goes from the sidebar scripts to the main add-on code, and listen to
ready if the first message goes from the main add-on code to the sidebar script.
...you should see console output like: console.log: add-on: add-on script got the message console.log: add-on: sidebar script got the reply using
ready the
ready event is emitted when the dom for the sidebar's content is
ready.
...And 3 more matches
New Skin Notes - Archive of obsolete content
devmo has a new skin that is
ready for testing.
...there's no real reason for user to give him info that he al
ready visited xml main page.
...it looks odd when someone who uses devmo on regular basis sees some violet links just because he al
ready worked with this site yesterday.also, the current color for visited links makes them less visible.
...And 3 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
for plugin vendors who have al
ready written a native code (e.g.
...rather than re-initiate the download of the plugin with the yet another browser, the second netscape gecko browser can detect that an installation has al
ready occurred.
...in a nutshell, the first install problem can be summed up by the question: how can a browser which is installed on a user's machine after a given plugin has al
ready been installed by the user benefit from the existing installation rather than download the same plugin again?
...And 3 more matches
NPP_NewStream - Archive of obsolete content
np_normal (default): delivers stream data to the instance in a series of calls to npp_write
ready and npp_write.
...values: np_normal (default): delivers stream data to the instance in a series of calls to npp_write
ready and npp_write.
...if the stream comes from a local file, the npp_write and npp_write
ready functions are not called.
...And 3 more matches
NPP_Write - Archive of obsolete content
if the return value is smaller than the size of the buffer, the browser sends the remaining data to the plug-in through subsequent calls to npp_write
ready and npp_write.
...description the browser calls the npp_write function to deliver the data specified in a previous npp_write
ready call to the plug-in.
... a plug-in must consume at least as many bytes as indicated in the npp_write
ready call.
...And 3 more matches
Understanding client-side JavaScript frameworks - Learn web development
we are not aiming to exhaustively teach you everything you need to know about react/reactdom, or vue, or some other specific framework; the framework teams' own docs (and other resources) do that job al
ready.
...this article will walk you through putting the basic app component structure and styling in place,
ready for individual component definition and interactivity, which we'll add later.
...getting started with ember in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it
ready for development.
...And 3 more matches
Introduction to automated testing - Learn web development
(if you al
ready have node and npm installed, jump to point 4) install it like you would any other program.
... once the install completes, test that node is installed by typing the following into the terminal, which returns the installed versions of node and npm: node -v npm -v if you've got node/npm al
ready installed, you should update them to their latest versions.
...you can customize it later, but for now it'll look something like this: { "name": "node-test", "version": "1.0.0", "description": "test for npm projects", "main": "index.js", "scripts": { "test": "test" }, "author": "chris mills", "license": "mit" } with this, you are
ready to move on.
...And 3 more matches
Handling common JavaScript problems - Learn web development
if you are not al
ready familiar with the basics of troubleshooting javascript, you should study that article before moving on.
... to install it: install atom (if you haven't got an up-to-date version al
ready installed) — download it from the atom page linked above.
... the console api you may al
ready know what is wrong with this code, but let's explore it some more to show how you could investigate this.
...And 3 more matches
Application Translation with Mercurial
if it is 'translated', the branch has al
ready been translated.
... progress tracking tool to track which strings and files al
ready have been translated and later also to see which new strings have al
ready been tested in the product as being a good translation for the functionality behind the translated strings and that the translated texts fit into the available, the translation progress should be tracked.
... go back to the localization directory: cd /c/mozilla/de-mozilla-aurora initiate mercurial queues: hg qinit get to know the translation style for having good chances that the translation suggestions get accepted, they should match the translation style of the texts in the application al
ready translated.
...And 3 more matches
Index
you also need to determine if a localization effort al
ready exists for your locale.
...now you're
ready for the final phase: becoming an official l10n release.
...editing the raw xliff file is also rather easy, especially if you're al
ready familiar with xml.
...And 3 more matches
Localizing with Koala
s removed, 0 files unresolved configure the locale locale id: x-testing (put your locale's code) version: 3.6 location: choose the folder where you want to keep the localized files or leave empty for now check "mercurial" if you wish to use mercurial to keep the revision history of your files (very recommended) existing localizations: url: if you're editing an existing localization or you al
ready have a repository set up (either on hg.mozilla.org or bitbucket), type the url of the remote repository, e.g.
...new localizations: url: if you al
ready have a repository set up by l10n-drivers (on bitbucket), type the url of the remote repository, e.g.
...just open the console and issue the following commands: c:\users\stas> cd c:\mozilla\l10n\locale\x-testing c:\mozilla\l10n\locale\x-testing> rmdir 3.6 c:\mozilla\l10n\locale\x-testing> hg clone http://hg.mozilla.org/releases/l10n-mozilla-1.9.2/x-testing 3.6 new localizations: if you have the bitbucket repository al
ready set up by l10n-drivers, the steps are the same as above.
...And 3 more matches
Release phase
now you're
ready for the final phase: becoming an official l10n release.
...depending on which branch you work on, the url of your repository might look like this: http://hg.mozilla.org/releases/l10n-central/x-testing if you followed the koala or plain text approach, you probably al
ready have a local clone of the repository.
...consequently, if you al
ready have a local clone that you pulled using http, you'll need to modify a config file to tell mercurial to push through ssh.
...And 3 more matches
Mozilla DOM Hacking Guide
we al
ready know what nsixpcscriptable is used for (see the previous section).
... static prbool sisinitialized: keeps track of wether class info was al
ready initialized, because init() shouldn't be called twice.
...this object al
ready implements the domimplementation interface, but dom2 html says it should also implement the htmldomimplementation interface, so here we go.
...And 3 more matches
Midas
if there is a selection and all of the characters are al
ready bold, the bold will be removed.
... if there is a selection and all of the characters are al
ready italic, the italic will be removed.
... if there is a selection and all of the characters are al
ready striked, the strikethrough will be removed.
...And 3 more matches
Introduction to NSPR
preempting threads preemption is the act of taking control away from a
ready thread at an arbitrary point and giving control to another appropriate thread.
... it might be viewed as taking the executing thread and adding it to the end of the
ready queue for its appropriate priority, then simply running the scheduling algorithm to find the most appropriate thread.
...should another thread (or the same thread) al
ready have the lock held, the calling thread blocks, waiting for the situation to improve.
...And 3 more matches
PR_Poll
detects when i/o is
ready for a set of socket file descriptors.
... timeout amount of time the call will block waiting for i/o to become
ready.
... if this time expires without any i/o becoming
ready, pr_poll returns zero.
...And 3 more matches
sslintro.html
it is also possible for an application to import a socket into ssl after the tcp connection on that socket has al
ready been established.
... in this case, initial configuration takes place in the same way: pass the existing nspr file descriptor to ssl_importfd and perform any additional configuration that has not al
ready been determined by the model file descriptor.
...these can be used, for example, when interrupting and restarting socket communications, when the application needs to change socket parameters, or when an application imports a socket into ssl after the tcp connection on that socket has al
ready been established.
...And 3 more matches
GCIntegration - SpiderMonkey Redirect 1
at a high level, there are three issues to be aware of: interactions between the garbage collector and the cycle collector incremental garbage collection moving garbage collection the apis for gc/cc interaction and incremental gc are al
ready in place.
... {{ svg{source: "http://people.mozilla.org/~wmccloskey/incremental1.svg", embedding: "iframe", height:"130"} }} assume object b is al
ready marked, as in the leftmost frame, while objects a and c have not been marked yet.
...assume that an incremental gc has al
ready started, and a and b have been marked.
...And 3 more matches
Introduction to XPCOM for the DOM
this is a contract between the caller, who says "i don't add a reference to this object because you have al
ready done it", and the callee who says "i add a reference to this object, so don't do it!".
...we have al
ready seen what getter_addrefs() does to nscomptr's.
... build system this is the really easy part: it's just copying what's al
ready there.
...And 3 more matches
nsIAsyncInputStream
method overview void asyncwait(in nsiinputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult astatus); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the oninputstream
ready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream).
...after the oninputstream
ready event is dispatched, the stream releases its reference to the nsiinputstreamcallback object.
...in other words, this method may be called when the stream al
ready has data to read.
...And 3 more matches
nsIAsyncOutputStream
method overview void asyncwait(in nsioutputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult reason); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the onoutputstream
ready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream).
...after the nsioutputstreamcallback.onoutputstream
ready() event is dispatched, the stream releases its reference to the nsioutputstreamcallback object.
...in other words, this method may be called when the stream al
ready has room for more data.
...And 3 more matches
Background Tasks API - Web APIs
currently, timeremaining() has an upper limit of 50 milliseconds, but in reality you will often have less time than that, since the event loop may al
ready be eating into that time on complex sites, with browser extensions needing processor time, and so forth.
...by the time your callback is run, the current frame has al
ready finished drawing, and all layout updates and computations have been completed.
... statusrefreshscheduled is used to track whether or not we've al
ready scheduled an update of the status display box for the upcoming frame, so that we only do it once per frame the shim to function even if idle callbacks aren't supported.
...And 3 more matches
DirectoryEntrySync - Web APIs
object literal condition result create: true exclusive: true path al
ready exists an error is thrown.
...if a file al
ready exists, no error is thrown.
... path_exists_err the file al
ready exists.
...And 3 more matches
Using the Notifications API - Web APIs
firefox is al
ready doing this from version 72, for example, and safari has done it for some time.
... checking current permission status you can check to see if you al
ready have permission by checking the value of the notification.permission read only property.
...we don't want to show it if permission has al
ready been granted, but if the user chose to deny permission, we want to give them the chance to change their mind later on.
...And 3 more matches
SVGLengthList - Web APIs
if the inserted item is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if newitem is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if the item is al
ready in this list, note that the index of the item to insert before is before the removal of the item.
...And 3 more matches
SVGNumberList - Web APIs
if the inserted item is al
ready in a list, it is removed from its previous list before it is inserted into this list.
... if newitem is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if the item is al
ready in this list, note that the index of the item to insert before is before the removal of the item.
...And 3 more matches
SVGPathSegList - Web APIs
if the inserted item is al
ready in a list, it is removed from its previous list before it is inserted into this list.
... if newitem is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if the item is al
ready in this list, note that the index of the item to insert before is before the removal of the item.
...And 3 more matches
SVGPointList - Web APIs
if the inserted item is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if newitem is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if the item is al
ready in this list, note that the index of the item to insert before is before the removal of the item.
...And 3 more matches
SVGStringList - Web APIs
if the inserted item is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if newitem is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if the item is al
ready in this list, note that the index of the item to insert before is before the removal of the item.
...And 3 more matches
SVGTransformList - Web APIs
if the inserted item is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if newitem is al
ready in a list, it is removed from its previous list before it is inserted into this list.
...if the item is al
ready in this list, note that the index of the item to insert before is before the removal of the item.
...And 3 more matches
Window.open() - Web APIs
=yes,status=yes"; function openrequestedpopup() { windowobjectreference = window.open("http://www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function openrequestedpopup() { windowobjectreference = window.open( "http://www.domainname.ext/path/imagefile.png", "descriptivewindowname", "resizable,scrollbars,status" ); } if a window with the name al
ready exists, then url is loaded into the existing window.
...*/ }; } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="promotefirefoxwindowname" onclick="openffpromotionpopup(); return false;" title="this link will create a new window or will re-use an al
ready opened one" >promote firefox adoption</a></p> the above code solves a few usability problems related to links opening secondary window.
...ctreference.closed) { windowobjectreference = window.open(url, windowname, "resizable,scrollbars,status"); } else { windowobjectreference.focus(); }; } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="promotefirefoxwindow" onclick="openrequestedpopup(this.href, this.target); return false;" title="this link will create a new window or will re-use an al
ready opened one" >promote firefox adoption</a></p> you can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner: <script type="text/javascript"> var windowobjectreference = null; // global variable var previousurl; /* global variable that will store the url currently in the secondary window */ func...
...And 3 more matches
WritableStream.WritableStream() - Web APIs
write(chunk, controller) optional this method, also defined by the developer, will be called when a new chunk of data (specified in the chunk parameter) is
ready to be written to the underlying sink.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += dec...
...And 3 more matches
Using Promises - JavaScript
since most people are consumers of al
ready-created promises, this guide will explain consumption of returned promises before explaining how to create them.
... here's some code that uses createaudiofileasync(): function successcallback(result) { console.log("audio file
ready at url: " + result); } function failurecallback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, successcallback, failurecallback); modern functions return a promise that you can attach your callbacks to instead: if createaudiofileasync() were rewritten to return a promise, using it could be as simple as this: createaudiofileasync(audi...
... in an ideal world, all asynchronous functions would al
ready return promises.
...And 3 more matches
Promise - JavaScript
if the promise has al
ready been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
...promises in javascript represent processes that are al
ready happening, which can be chained with callback functions.
... const promisea = new promise(myexecutorfunc); const promiseb = promisea.then(handlefulfilled1, handlerejected1); const promisec = promisea.then(handlefulfilled2, handlerejected2); an action can be assigned to an al
ready "settled" promise.
...And 3 more matches
Working with Events - Archive of obsolete content
for example, the following add-on registers a listener with the tabs module to listen for the
ready event, and logs a string to the console reporting the event: var tabs = require("sdk/tabs"); tabs.on("
ready", function () { console.log("tab loaded"); }); it is not possible to enumerate the set of listeners for a given event.
... adding listeners in constructors event emitters may be modules, as is the case for the
ready event above, or they may be objects returned by constructors.
... in the latter case the options object passed to the constructor typically defines properties whose names are the names of supported event types prefixed with "on": for example, "onopen", "on
ready" and so on.
...And 2 more matches
jspage - Archive of obsolete content
}else{if(c[a]){c[a].keys.each(function(e){this.addevent(a,e);},this);}}return this;}});element.nativeevents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,dommousescroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,domcontentloaded:1,
readystatechange:1,error:1,abort:1,scroll:1}; (function(){var a=function(b){var c=b.relatedtarget;if(c==undefined){return true;}if(c===false){return false;}return($type(this)!="document"&&c!=this&&c.prefix!="xul"&&!this.haschild(c)); };element.events=new hash({mouseenter:{base:"mouseover",condition:a},mouseleave:{base:"mouseout",condition:a},mousewheel:{base:(browser.engine.gecko)?"dommousescroll":"mou...
...%c.a==c.b); },index:function(a){var b=this,c=0;while((b=b.previoussibling)){if(b.nodetype==1&&++c>a){return false;}}return(c==a);},even:function(b,a){return selectors.pseudo["nth-child"].call(this,"2n+1",a); },odd:function(b,a){return selectors.pseudo["nth-child"].call(this,"2n",a);},selected:function(){return this.selected;},enabled:function(){return(this.disabled===false); }});element.events.dom
ready={onadd:function(a){if(browser.loaded){a.call(this);}}};(function(){var b=function(){if(browser.loaded){return;}browser.loaded=true; window.fireevent("dom
ready");document.fireevent("dom
ready");};window.addevent("load",b);if(browser.engine.trident){var a=document.createelement("div"); (function(){($try(function(){a.doscroll();return document.id(a).inject(document.body).set("html","temp").dispose();...
...}))?b():arguments.callee.delay(50);})(); }else{if(browser.engine.webkit&&browser.engine.version<525){(function(){(["loaded","complete"].contains(document.
readystate))?b():arguments.callee.delay(50); })();}else{document.addevent("domcontentloaded",b);}}})();var json=new hash(this.json&&{stringify:json.stringify,parse:json.parse}).extend({$specialchars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replacechars:function(a){return json.$specialchars[a]||"\\u00"+math.floor(a.charcodeat()/16).tostring(16)+(a.charcodeat()%16).tostring(16); },encode:function(b){switch($type(b)){case"string":return'"'+b.replace(/[\x00-\x1f\\"]/g,json.$replacechars)+'"';case"array":return"["+string(b.map(json.encode).clean())+"]"; case"object":case"hash":var a=[];hash.each(b,function(e,d...
...And 2 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
what this means to you as the developer is this: you can take advantage of skills you al
ready have with xml or web technologies to design and implement anything from a simple text editor to a comprehensive ide - complete with all of the interface widgets that you would find in virtually any major application framework.
...in addition, if the organization maintains sophisticated, interactive websites, it will al
ready possess a wealth of technical expertise that will be relevant for creating xul applications.
... in addition to the technologies al
ready mentioned, we go even further by allowing you to even create your own custom interface widgets.
...And 2 more matches
Mozilla release FAQ - Archive of obsolete content
originally, the plan was just to re-stabilize the code and release 5.0, but it was decided within the community that the more ambitious changes that were planned for later integration were close to being
ready.
...first, you should make sure that mozilla doesn't al
ready have the feature you wish to add.
...assured that it's not al
ready there, you should post to the mozilla usenet groups, asking for help.
...And 2 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
it is assumed that you have al
ready downloaded, extracted, and consumed the necessary documentation to get up and running with some basic rhino scripts.
... if you don’t al
ready have it, you’ll need to also download the jdbc driver for mysql, extract the class files, and include the path in your classpath environment variable.
...however, taking advantage of frameworks such as aptana jaxer (spidermonkey) and helma (rhino) can reveal even greater rewards as a great deal of work has al
ready been done for you.
...And 2 more matches
RDF in Mozilla FAQ - Archive of obsolete content
var remote = ds.queryinterface(components.interfaces.nsirdfremotedatasource); if (remote.loaded) { alert("the datasource was al
ready loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); } say the datasource wasn't loaded, and is loading asynchronously.
...var remote = ds.queryinterface(components.interfaces.nsirdfremotedatasource); if (remote.loaded) { alert("the datasource was al
ready loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); // rdf/xml datasources are all nsirdfxmlsinks var sink = ds.queryinterface(components.interfaces.nsirdfxmlsink); // attach the observer to the datasource-as-sink sink.addxmlsinkobserver(observer); // now observer's methods will be called-back as // the load progresses.
...you can "make a resource into a container" if it isn't one al
ready using makeseq(), makebag(), or makealt().
...And 2 more matches
Desktop gamepad controls - Game development
api status, browser and hardware support the gamepad api is still in working draft status, although browser support is al
ready quite good — around 63% global coverage, according to caniuse.com.
... pressed buttons we will need a function that will do exactly that on every frame: function gamepadupdatehandler() { buttonspressed = []; if(controller.buttons) { for(var b=0; b<controller.buttons.length; b++) { if(controller.buttons[b].pressed) { buttonspressed.push(b); } } } } we first reset the buttonspressed array to get it
ready to store the latest info we'll write to it from the current frame.
...if we want to check the button is not held al
ready (so it's a new press), then looping through the cached states from the previous frame does the job — if the button was al
ready pressed, then we ignore the new press and set it to false.
...And 2 more matches
Drawing graphics - Learn web development
so that's it — our canvas is now primed and
ready for drawing on!
... update the variables that describe the sequence of triangles, so we can be
ready to draw the next one.
...the next time the browser is
ready to update the screen, your function will get called.
...And 2 more matches
A first splash into JavaScript - Learn web development
if you haven't al
ready done so, save your code, refresh the page in your browser, and open the developer tools javascript console.
... the last three lines in the function (lines 26–28 above) get us
ready for the next guess to be submitted.
... we add 1 to the guesscount variable so the player uses up their turn (++ is an incrementation operation — increment by 1), and empty the value out of the form text field and focus it again,
ready for the next guess to be entered.
...And 2 more matches
Getting started with Ember - Learn web development
previous overview: client-side javascript frameworks next in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it
ready for development.
...go here to find out how to install node and npm, if you haven't al
ready got them.
...(good suggestions are your "desktop" or "documents" directories, so that it is easy to find): ember new todomvc or, on windows: npx ember-cli new todomvc this generates a production-
ready application development environment that includes the following features by default: development server with live reload.
...And 2 more matches
Starting our Svelte Todo list app - Learn web development
in this article we will first have a look at the desired functionality of our app, then we'll create a todos.svelte component and put static markup and styles in place, leaving everything
ready to start developing our to-do list app features, which we'll go on to in subsequent articles.
... code along with us git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/02-starting-our-todo-app or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/02-starting-our-todo-app remember to run npm install && npm run dev to start your app in development mode.
... repl to code along with us using the repl, start at https://svelte.dev/repl/b7b831ea3a354d3789cefbc31e2ca495?version=3.23.2 todo list app features this is how our todo list app wil look like once it's
ready: using this ui our user will be able to: browse their tasks.
...And 2 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
previous overview: client-side javascript frameworks next now that we have our markup and styles
ready we can start developing the required features for our svelte to-do list app.
... code along with us git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/03-adding-dynamic-behavior or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior remember to run npm install && npm run dev to start your app in development mode.
... we've turned our static markup into a dynamic template
ready to display the tasks from our component's state.
...And 2 more matches
Mozilla accessibility architecture
we use the accessibility cache to retrieve accessibles that have al
ready been created for a given dom node.
...these crashes occur when the assistive techology releases after some gecko modules have al
ready been unloaded, when the necessary destructors no longer exist in memory.
...the member variables keeping track of the number of children, parent, first child and next sibling allow us to have instant traversal around accessible nodes that have al
ready been visited.
...And 2 more matches
Multiprocess on Windows
as you should al
ready know from the prerequisite reading, single threaded apartments receive remote procedure calls (rpcs) from com, via the windows message queue.
...since we are using com, we al
ready generate metadata by declaring interfaces using midl.
...any typelibs that are al
ready registered in the system registry will automatically be available for use by the interceptor.
...And 2 more matches
HTML parser threading
this method returns immediately if another invocation of it is al
ready on the call stack (nested event loop case).
...(only the al
ready executed ops are destructed and the rest are left in the queue.) the last op in the queue may be an op for attempting to execute a script that may block the parser (ops for attempting to execute async and defer scripts are normal tree ops and don't need to be the last op in a queue).
...it is possible that the parser thread ends up parsing all remaining data into speculations before the main thread is
ready to receive more tree ops.
...And 2 more matches
IPDL Tutorial
the following ipdl code defines a very basic interaction of browser and plugin actors: async protocol pplugin { child: async init(nscstring pluginpath); async shutdown(); parent: async
ready(); }; this code declares the pplugin protocol.
...one message can be sent from the child to the parent,
ready().
...each incoming message is a pure-virtual c++ method which must be implemented: class ppluginparent { public: bool sendinit(const nscstring& pluginpath) { // generated code to send an init() message } bool sendshutdown() { // generated code to send a shutdown() message } protected: /** * a subclass of ppluginparent must implement this method to handle the
ready() message.
...And 2 more matches
CustomizableUI.jsm
anode is the widget's node, acontainer is the area it was moved into (nb: it might al
ready have been there and been moved to a different position!) onwidgetundomove(anode, acontainer) fired after undoing a reset to default placements moves a widget's node to a different location.
... anode is the widget's node, acontainer is the area it was moved into (nb: it might al
ready have been there and been moved to a different position!) onareareset(aarea, acontainer) fired after a reset to default placements is complete on an area's dom node.
... if the widget is not in any area, or if the widget is al
ready at the indicated position, this will no-op.
...And 2 more matches
Deferred
if the associated promise has al
ready been resolved, either to a value, a rejection, or another promise, this method does nothing.
... note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is al
ready resolved to the pending promise value as its resolution.
...if the promise has al
ready been resolved, either to a value, a rejection, or another promise, this method does nothing.
...And 2 more matches
Promise
you don't need to import the promise.jsm module to use a promise object to which you al
ready have a reference.
...if the associated promise has al
ready been resolved, either to a value, a rejection, or another promise, this method does nothing.
... note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is fulfilled or rejected, will have no effect the second time, as the associated promise is al
ready resolved to the pending promise.
...And 2 more matches
NSPR Error Handling
pr_is_connected_error an attempt to connect on an al
ready connected network file descriptor.
... pr_socket_address_is_bound_erro attempt to bind an address to a tcp file descriptor that is al
ready bound.
... pr_file_is_locked_error an attempt to acquire a lock on a file has failed because the file is al
ready locked.
...And 2 more matches
Index
137 jsobjectops.getrequiredslot jsapi reference, obsolete, spidermonkey get and set a required slot, one that should al
ready have been allocated.
... 190 js_al
readyhasownproperty jsapi reference, spidermonkey these functions attempt to determine whether a property al
ready exists on a specific jsobject without modifying the object.
...this will not recurse through non-extensible objects, on the assumption that those are al
ready deep-frozen.
...And 2 more matches
Observer Notifications
xpcom-shutdown-threads shuts down the thread manager, causing all nsthreads to finish processing any events al
ready queued and stop accepting new events.
... the window id can be obtained from subject.queryinterface(components.interfaces.nsisupportspruint64).data toplevel-window-
ready nsiwindowwatcher called just after a new top level window has been opened and is
ready, but has not yet loaded a document.
... topic data description highlighter-
ready - sent when the highlighter component is initialized.
...And 2 more matches
mozIStorageConnection
resshandler(); void rollbacktransaction(); void setgrowthincrement(in print32 aincrement, in autf8string adatabasename); mozistorageprogresshandler setprogresshandler(in print32 agranularity, in mozistorageprogresshandler ahandler); boolean tableexists(in autf8string atablename); attributes attribute type description connection
ready boolean indicates if the connection is open and
ready to use.
...this should not be used until the database is
ready.
... note: the database engine does not support nested transactions, so attempting to start a transaction when one is al
ready active will throw an exception.
...And 2 more matches
mozIStorageService
if the filename is al
ready taken, attempts will be made to ensure that it is unique.
...the specified file is created if it does not al
ready exist.
...consumers should check mozistorageconnection.connection
ready to ensure that they can use the database.
...And 2 more matches
nsIWindowsRegKey
if the key is al
ready closed, then this method does nothing.
...the value will be created if it does not al
ready exist.
...the value will be created if it does not al
ready exist.
...And 2 more matches
Content Index API - Web APIs
the content index api is an extension to service workers, which allows developers to add urls and metadata of al
ready cached pages, under the scope of the current service worker.
... // reference registration const registration = await navigator.serviceworker.
ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index.
...amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.
ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, b...
...And 2 more matches
Rendering and the WebXR frame animation callback - Web APIs
refresh rate and frame rate assuming you've called the xrsession method requestanimationframe() since the last time the screen refreshed, the browser will call your frame renderer callback every time it's
ready to repaint your app or site window.
... hardare vertical refresh rate when the browser is
ready to refresh the <canvas> within which your webxr content is displayed, it calls your frame rendering callback, which uses the specified timestamp and any other relevant data, such as models and textures, as well as application state, to render the scene—as it should appear at the specified time—into the webgl backbuffer.
...60 fps is al
ready beyond the point at which most people can easily detect that the animation isn't simply a series of still images going by really fast.
...And 2 more matches
Using the Web Animations API - Web APIs
to prevent the cake from eating itself up before the user has had the chance to click on it, we call animation.pause() on it immediately after it is defined, like so: nommingcake.pause(); we can now use the animation.play() method to run it whenever we’re
ready: nommingcake.play(); specifically, we want to link it to alice’s animation, so she gets bigger as the cupcake gets eaten.
...then we pause her: alicechange.pause(); if we had left her paused at the beginning of her animation, she’d start at half her full size, as if she’d drunk the entire bottle al
ready!
... we want to set her animation’s “playhead” in the middle, so she’s al
ready halfway done.
...And 2 more matches
WritableStream - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += dec...
... the defaultwriter.
ready property returns a promise that resolves when the sink (the first property of the writablestream constructor) is done writing data.
...And 2 more matches
Writing Web Audio API code that works in every browser - Developer guides
you probably have al
ready read the announcement on the web audio api coming to firefox, and are totally excited and
ready to make your until-now-webkit-only sites work with firefox, which uses the unprefixed version of the spec.
...in addition, not all features of web audio are al
ready implemented in firefox yet.
...and it won't do anything if the unprefixed versions are al
ready present.
...And 2 more matches
Using the application cache - HTML: Hypertext Markup Language
since the document has al
ready been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically).
... update
ready there is a new version of the application cache available.
... there is a corresponding update
ready event, which is fired instead of the cached event when a new update has been downloaded but not yet activated using the swapcache() method.
...And 2 more matches
Content Scripts - Archive of obsolete content
you can load multiple scripts by passing an array of strings to either contentscript or contentscriptfile: // main.js var tabs = require("sdk/tabs"); tabs.on('
ready', function(tab) { tab.attach({ contentscript: ['document.body.style.border = "5px solid red";', 'window.alert("hi");'] }); }); // main.js var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: [data.url("jquery.min.js"), data.url("my-content-script.js")] }); if you do this, the scripts can inter...
... "
ready": load the scripts after the dom for the page has been loaded: that is, at the point the domcontentloaded event fires.
... 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.
... here's a simple add-on that sends a message to a content script using port: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.on("
ready", function(tab) { var worker = tab.attach({ contentscriptfile: self.data.url("content-script.js") }); worker.port.emit("alert", "message from the add-on"); }); tabs.open("http://www.mozilla.org"); // content-script.js self.port.on("alert", function(message) { window.alert(message); }); the context-menu module doesn't use the communication model described here.
page-worker - Archive of obsolete content
e page to the add-on: var script = "var elements = document.queryselectorall('h2 > span'); " + "for (var i = 0; i < elements.length; i++) { " + " postmessage(elements[i].textcontent) " + "}"; // create a page worker that loads wikipedia: pageworkers.page({ contenturl: "http://en.wikipedia.org/wiki/internet", contentscript: script, contentscriptwhen: "
ready", onmessage: function(message) { console.log(message); } }); for conciseness, this example creates the content script as a string and uses the contentscript property.
... scripting trusted page content we've al
ready seen that you can package html files in your add-on's data directory and load them using page-worker.
...this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "
ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this property is optional and defaults to "end".
...this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "
ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property.
panel - Archive of obsolete content
opening a panel will close any panel created by the panel() constructor that is al
ready open, even if that panel was opened by a different add-on sdk based extension.
... we've al
ready seen that you can package html files in your add-on's data directory and use them to define the panel's content.
...this may take one of the following values: "start": load content scripts immediately after the document element for the panel is inserted into the dom, but before the dom content itself has been loaded "
ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the panel has been loaded, at the time the window.onload event fires this property is optional and defaults to "end".
...this may have one of the following values: "start": load content scripts immediately after the document element for the panel is inserted into the dom, but before the dom content itself has been loaded "
ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the panel has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under addon.options property.
frame/hidden-frame - Archive of obsolete content
the following code creates a hidden frame, loads a web page into it, and then logs its title: var hiddenframes = require("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ on
ready: function() { this.element.contentwindow.location = "http://www.mozilla.org/"; let self = this; this.element.addeventlistener("domcontentloaded", function() { console.log(self.element.contentdocument.title); }, true, true); } })); see the panel module for a real-world example of usage of this module.
... parameters options : object required options: name type on
ready function,array functions to call when the frame is
ready to load content.
... you must specify an on
ready callback and refrain from using the hidden frame until the callback gets called, because hidden frames are not always
ready to load content the moment they are added.
... events
ready this event is emitted when the dom for a hidden frame content is
ready.
io/text-streams - Archive of obsolete content
it must al
ready be opened.
...it must al
ready be opened.
...if the stream is al
ready closed, an exception is thrown.
...if the stream is al
ready closed, an exception is thrown immediately.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
this popup is al
ready part of the main window, so it doesn't need to be implemented again.
...we've al
ready mentioned this before, and if you follow our recommendations, then you shouldn't have many problems making your toolbar compatible with the customize toolbars dialog.
... remember to validate if your button is al
ready present, to prevent duplicates.
... it's also a good idea to set a preference that indicates that you added your button al
ready, so that it can be removed permanently if the user chooses to.
Setting up an extension development environment - Archive of obsolete content
as we are specifically defining the user profile dev, if you don't have the dev profile al
ready created, the profile selection window opens, where you can create it.
... in the following example, the described command starts a new instance of firefox, with a profile called dev; even if an instance of firefox is al
ready running.
...if you are al
ready running a firefox instance without -no-remote, and you attempt to start another instance with -p profilename (but without the -no-remote parameter), that second invocation would ignore its -p profilename parameter, instead opening a new window for the al
ready running instance; sharing all its profile, sessions etc.
... note: if you al
ready installed the extension via xpi, you should uninstall it first before creating the pointer file.
Search Extension Tutorial (Draft) - Archive of obsolete content
// an engine with this name must al
ready exist.
... selectsearch = firstrun || reason == addon_enable; // only add the engine if it doesn't al
ready exist.
...var selectsearch = false; function removeobserver() { try { services.obs.removeobserver(searchobserver, engine_added); } // if we've al
ready removed this observer, ignore the error.
... selectsearch = firstrun || reason == addon_enable; // only add the engine if it doesn't al
ready exist.
Space Manager Detailed Design - Archive of obsolete content
must not be null * @param aunavailablespace the bounding rect of the unavailable space * @return ns_ok if successful * ns_error_failure if there is al
ready a region tagged with aframe */ nsresult addrectregion(nsiframe* aframe, const nsrect& aunavailablespace); /** * resize the rectangular region associated with aframe by the specified * deltas.
...must not be null * @param aunavailablespace the bounding rect of the unavailable space * @return ns_ok if successful * ns_error_failure if there is al
ready a region tagged with aframe */ nsresult addrectregion(nsiframe* aframe, const nsrect& aunavailablespace); /** * resize the rectangular region associated with aframe by the specified * deltas.
...if it is found, return an error since the frame is al
ready associated with a region in the spacemanager.
...insert the part that is totally above the bandrect before the current bandrect, as in case #1 above, and adjust the other band rect to exclude the part al
ready added.
Binding Attachment and Detachment - Archive of obsolete content
when a binding is attached using the dom, it inherits from the current most derived binding that may al
ready be attached to the element.
... if a binding is attached and it al
ready specifies an inherited binding using the extends attribute, then the base binding at the end of the inheritance chain is the one that will inherit from the most derived binding that is al
ready attached.
... for example, given a binding d1, with an explicit inheritance chain of d1 -> d2 -> d3 if this element is attached to an element using element.style.mozbinding that al
ready has a binding chain of s1 -> s2 -> s3 the resulting binding chain following the addition of the binding is d1 -> d2 -> d3 -> s1 -> s2 -> s3 the inheritance between d3 and s1 is implicit, meaning that there is no connection in the xbl documents between the two bindings.
...therefore if all the bindings in a chain come from binding documents that have al
ready been loaded by the bound document, then the attachment of a binding (either through css or through the dom) is guaranteed to be synchronous.
listbox - Archive of obsolete content
most of the features of the list box are al
ready available directly in the listbox, so you will rarely have need to use this box object directly.
...refix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata additemtoselection( item ) return type: no return value selects the given item, without deselecting any other items that are al
ready selected.
...if the item is al
ready visible, no scrolling occurs.
...if the item is al
ready visible, no scrolling occurs.
NPN_RequestRead - Archive of obsolete content
this initiates a read operation; the actual data is received through subsequent calls to npp_write
ready() and npp_write().
...these requests result in subsequent calls to npp_write
ready() and npp_write().
...if the plug-in requests multiple ranges (either through a list of npbyterange objects in a single call to npn_requestread(), or multiple calls to npn_requestread()), the browser can write individual ranges in any order, and with any number of npp_write
ready() and npp_write() calls.
...see also npp_newstream() npp_write
ready() npp_write() npstream ...
Using SSH to connect to CVS - Archive of obsolete content
this document assumes that you al
ready have a write-access cvs account to cvs.mozilla.org.
...most linux, bsd, and osx distributions come with it installed al
ready.
... setting up cvs to use ssh in your system's environment, make sure thatcvs_rsh is set to whatever your ssh binary is called; a full path is not necessary if ssh is al
ready in your path.
...if you don't al
ready run ssh-agent on your computer, it's probably easiest to start it up whenever you set up your environment to checkout and build mozilla.
Index - Game development
16 building up a basic demo with a-frame 3d, a-frame, vr, virtual reality, web, webgl the webxr and webgl apis al
ready enable us to start creating virtual reality (vr) experiences inside web browsers, but the community is still waiting for tools and libraries to appear, to make this easier.
... 62 collision detection beginner, canvas, games, javascript, tutorial, collision, detection we have the bricks appearing on the screen al
ready, but the game still isn't that interesting as the ball goes through them.
...we have al
ready added keyboard controls, but we could easily add mouse controls too.
... 67 move the ball 2d, beginner, canvas, games, javascript, loop, tutorial, movement you al
ready know how to draw a ball from working through the previous article, so now let's make it move.
Building up a basic demo with Babylon.js - Game development
if you have al
ready worked through our building up a basic demo series with three.js, playcanvas or a-frame (or you are familiar with other 3d libraries) you'll notice that babylon.js works on similar concepts: camera, light and objects.
...there is one helper variable al
ready included, which will store a reference to the <canvas> element.
... more shapes we have a box on the scene al
ready; now let's try adding more shapes.
... animation we al
ready used position and rotation to adjust the position of the shapes; we could also scale them.
Building up a basic demo with Three.js - Game development
there are two helper variables al
ready included, which store the window's width and height.
... rendering the scene everything is
ready, but we still can't see anything.
... our material is now
ready, what next?
... animation we al
ready used rotation, to adjust the position of the cube.
Index - MDN Web Docs Glossary: Definitions of Web-related terms
with variables, on the other hand, the programmer can assign a new value to a variable name al
ready in use.
...for example, the selector a:visited applies styles only to links that the user has al
ready followed.
... 416 shim codingscripting, glossary a shim is a piece of code used to correct the behavior of code that al
ready exists, usually by adding new api that works around the problem.
...the upside is that when a speculation succeeds, there's no need to reparse the part of the incoming file that was al
ready scanned for scripts, style sheets and images.
Accessible multimedia - Learn web development
simple images we al
ready covered simple text alternatives for html images in our html: a good basis for accessibility article — you can refer back to there for the full details.
...in some cases it is not so bad, for example: if you are embedding audio content using a plugin technology like flash or silverlight, you can probably just provide an audio transcript in the same manner as we al
ready showed above in the transcript examples section.
... we've not written a new set of assessments for this article, because there are al
ready assessments available in our html multimedia and embedding module that test your knowledge of the information presented here.
... if you haven't al
ready, go and try out the assessments at test your skills: html images and test your skills: multimedia and embedding.
What software do I need to build a website? - Learn web development
prerequisites: you should al
ready know the difference between webpages, websites, web servers, and search engines.
... (all unix) gedit (gnome) kate (kde) leafpad (xfce) emacs vim visual studio code brackets shiftedit sublime text chrome os shiftedit here is a screenshot of an advanced text editor: here is a screenshot of an online text editor: uploading files on the web when your website is
ready for public viewing, you'll have to upload your webpages to your web server.
...c (s)ftp clients: operating system ftp software windows winscp moba xterm filezilla (all os) linux nautilus/files (gnome) dolphin (kde) mac os cyberduck chrome os shiftedit (all os) browsing websites as you al
ready know, you need a web browser to view websites.
...(if you're going that route, microsoft has some tools for developers including a
ready-to-use virtual machine at modern.ie.) by all means run some tests on a real device, especially on real mobile devices.
How to build custom form controls - Learn web development
we didn't implement this in our example, but it would be easy to do so, as the mechanism has al
ready been implemented for the click event.
... .select .option { padding: .2em .3em; /* 2px 3px */ } .select .highlight { background: #000; color: #ffffff; } so here's the result with our three states: basic state active state open state check out the source code bringing your control to life with javascript now that our design and structure are
ready, we can write the javascript code to make the control actually work.
... // and we deactivate the custom control itself select.classlist.remove('active'); } // this function will be used each time the user wants to (de)activate the control // it takes two parameters: // select : the dom node with the `select` class to activate // selectlist : the list of all the dom nodes with the `select` class function activeselect(select, selectlist) { // if the control is al
ready active there is nothing to do if (select.classlist.contains('active')) return; // we have to turn off the active state on all custom controls // because the deactivateselect function fulfills all the requirements of the // foreach callback function, we use it directly without using an intermediate // anonymous function.
... as seen previously, we al
ready use a native select control as a fallback for accessibility reasons; we can simply synchronize its value with that of our custom control: // this function updates the displayed value and synchronizes it with the native control.
Test your skills: Advanced styling - Learn web development
we've al
ready provided you with a basic reset to build upon.
... we've al
ready provided you with a basic reset to build upon.
... advanced form styling 3 in our final task for this assessment series, we provide you with a feedback form that is al
ready nicely-styled — you've al
ready seen something similar if you've worked through our ui pseudo-classes article, and now we want you to come up with your own solution.
... details of what you have al
ready tried, and what you would like us to do, e.g.
Graceful asynchronous programming with Promises - Learn web development
even if the handlecallbutton() function has al
ready returned to the code that called it, when getusermedia() has finished working, it calls the handler you provide.
...pings) { return placeorder(toppings); }) .then(function(order) { return collectorder(order); }) .then(function(pizza) { eatpizza(pizza); }) .catch(failurecallback); this is much better — it is easier to see what is going on, we only need a single .catch() block to handle all the errors, it doesn't block the main thread (so we can keep playing video games while we wait for the pizza to be
ready to collect), and each operation is guaranteed to wait for previous operations to complete before running.
... building your own custom promises the good news is that, in a way, you've al
ready built your own promises.
... when you've chained multiple promises together with .then() blocks, or otherwise combined them to create custom functionality, you are al
ready making your own custom async promise-based functions.
Image gallery - Learn web development
prerequisites: before attempting this assessment you should have al
ready worked through all the articles in this module.
... looping through the images we've al
ready provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbbar, create a new <img> element, set its src attribute to a placeholder value xxx, and append this new <img> element inside thumbbar.
... writing a handler that runs the darken/lighten button that just leaves our darken/lighten <button> — we've al
ready provided a line that stores a reference to the <button> in a constant called btn.
... details of what you have al
ready tried, and what you would like us to do, e.g.
Introduction to web APIs - Learn web development
note: if you are not al
ready familiar with how objects work, you should go back and work through our javascript objects module before continuing.
... they use events to handle changes in state we al
ready discussed events earlier on in the course in our introduction to events article, which looks in detail at what client-side web events are and how they are used in your code.
... if you are not al
ready familiar with how client-side web api events work, you should go and read this article first before continuing.
... we al
ready saw a number of event handlers in use in our web audio api example above.
Third-party APIs - Learn web development
if you've al
ready cloned the examples repository, you'll al
ready have a copy of this file, which you can find in the javascript/apis/third-party-apis/mapquest directory.
...if you've al
ready cloned the examples repository, you'll al
ready have a copy of these files, which you can find in the javascript/apis/third-party-apis/nytimes directory.
... the second function works nearly exactly the same way in reverse, but we also have to take the extra step of checking that pagenumber is not al
ready zero before decrementing it — if the fetch request runs with a minus page url parameter, it could cause errors.
... if the pagenumber is al
ready 0, we simply return out of the function, to avoid wasting processing power (if we are al
ready at the first page, we don't need to load the same results again).
Deployment and next steps - Learn web development
code along with us git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/08-next-steps or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/08-next-steps remember to run npm install && npm run dev to start your app in development mode.
...if you haven't al
ready done it, make sure you go through the svelte interactive tutorial.
... we al
ready covered most of its content, so it won't take you much time to complete it — you should consider it as practise!
... if you prefer to read books, there's svelte and sapper in action by mark volkman, expected to be published in september 2020, but which you can al
ready preview online for free.
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
code along with us git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/05-advanced-concepts or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts remember to run npm install && npm run dev to start your app in development mode.
... like we al
ready saw, we could just tell svelte to update the variable with a self-assignment, like this: const checkalltodos = (completed) => { todos.foreach(t => t.completed = completed) todos = todos } this will solve the problem.
... so, how can you know when the component has al
ready been created and mounted on the dom?
... we've al
ready seen that svelte uses export let var = ...
Handling common accessibility problems - Learn web development
we've al
ready talked about other spheres such as responsive design and performance in other places in the module.
...we have al
ready mentioned a couple of accessibility tips involving css: use the correct semantic elements to mark up different content in html; if you want to create a different visual effect, use css — don't abuse an html element to get the look you want.
...we've al
ready hinted at some accessibility problems related to javascript, mainly in the area of semantic html — you should always use appropriate semantic html to implement functionality wherever it is available, for example use links and buttons as appropriate.
... nvda + space (when form is selected) enter form so individual items can be selected, or leave form if you are al
ready in it.
Handling common HTML and CSS problems - Learn web development
for example, you might use a css framework and find that one of the class names it uses clashes with one you've al
ready used for a different purpose.
... or you might find that html generated by some kind of third party api (generating ad banners, for example) includes a class name or id that you are al
ready using for a different purpose.
...to show you an example of how such plugins generally work: install atom (if you haven't got an up-to-date version al
ready installed) — download it from the atom page linked above.
...you are advised to look and see if there is an answer to your question al
ready, before posting a new question.
Introduction to cross browser testing - Learn web development
before you even get to cross browser issues, you should have al
ready fixed out bugs in your code (see debugging html, debugging css, and what went wrong?
...the client might al
ready have data about this from previous research they've done, e.g.
...it might have al
ready been fixed — for example if a bug is present in firefox release 49, but it is no longer there in firefox nightly (version 52), then they have fixed it.
...armed with this knowledge, you are now
ready to move on and start learning about cross browser testing strategies.
Deploying our app - Learn web development
instead of running the server with npx parcel src/index.html, we can run it with npx parcel build src/index.html and parcel will build everything
ready for production instead of just running it for development and testing purposes.
... the newly-created production code is placed in a new directory called dist, which contains all the files required to run the website,
ready for you to upload to a server.
... "build": "parcel build src/index.html" } note: if the scripts property al
ready has a command inside it, put a comma at the end of it.
... now we're
ready to push our code to github; run the following command now: git push github master at this point you'll be prompted to enter a username and password before git will allow the push to be sent.
Client-side tooling overview - Learn web development
you might even find yourself writing a piece of software to aid your own development process, to solve a specific problem that existing tools don’t al
ready seem to handle.
... bundlers/packagers these are tools that get your code
ready for production, for example by “tree-shaking” to make sure only the parts of your code libraries that you are actually using are put into your final production code, or "minifying" to remove all the whitespace in your production code, making it as small as possible before it is uploaded to a server.
...the knowledge about which are the best tools to use is a bit tribal, meaning that if you aren’t al
ready in the web community, it is hard to find out exactly which ones to go for!
...general web searches for front-end developer tools are generally useless unless you al
ready know the name of the tool you are searching for.
Command line options
firefox -createprofile "joeluser c:\internet\joelusers-moz-profile" note: profile_dir must not exist and you must not al
ready have a profile called profile_name.
...if a private browsing window is al
ready open, a new tab is opened in the existing window.
... execute the specified remote_command in an al
ready running application process.
...useful with those command-line arguments that open their own windows but don't al
ready prevent default windows from opening.
The Firefox codebase: CSS Guidelines
before adding more css it is good practice to check if the css that is being written is needed, it can be the case that a common component has been al
ready written could be reused with or without changes.
... most of the time, the common component al
ready follows the a11y/theme standards defined in this guide.
... colors for common areas of the firefox interface (panels, toolbar buttons, etc.), mozilla-central often comes with some useful css variables that are adjusted with the correct values for different platform configurations, so using those css variables can definitively save some testing time, as you can assume they al
ready work correctly.
... using the currentcolor keyword or inheriting is also good practice, because sometimes the needed value is al
ready in the color or on the parent element.
Eclipse CDT
(if you're thinking of adding tips, please first consider how widely useful they'll be before adding to this al
ready lengthy page.) for further documentation see the official eclipse user guide and eclipse cdt user guide.
...;-) to jump to the definition of a symbol (or the declaration of a symbol if al
ready at the definition), hover over the symbol, hold down the ctrl/cmd key, move the mouse slightly to linkify the symbol, then click on it.
...if you think we need our own documentation on mercurialeclipse, please consider adding a separate page for that tool since this page is al
ready pretty long.
...if you al
ready carried out the instructions in that section, then double check that your changes to eclipse's memory limits actually took effect and are present in eclipse/help > about eclipse > installation details > configuration.
Eclipse CDT Manual Setup
(this assumes that you al
ready have a copy of the mozilla source, and that you have also built the source so that you have a pre-existing object directory.
...owing two settings in the workspace preferences (window > preferences, or eclipse > preferences) before creating a project in that workspace: in "general > workspace", disable "build automatically" in "c/c++ > indexer", disable "automatically update the index" turning off automatic indexing prevents the cpu intensive indexer from running at various stages during the steps below before we're
ready.
...(see the headers are only parsed once section below to understand why this step is important for people who have their object directory outside their source tree.) getting code assistance working you're now
ready to get code assistance working.
... :-) build option discovery this section requires that you have al
ready built your mozilla source tree (so that you have an object directory for it), and it is strongly recommended that the object directory is up to date so that the just-print-mozilla-build.py script runs quickly.
AddonManager
state_downloaded an install that has finished downloading and is
ready to install.
...fromwebpage( in string mimetype, in nsidomwindow source, in nsiuri uri, in addoninstall installs[] ) parameters mimetype the mimetype of add-ons being installed source the nsidomwindow that started the installs uri the nsiuri that started the installs installs the array of addoninstalls to be installed addinstalllistener() adds a new installlistener if the listener is not al
ready registered.
... addaddonlistener() adds a new addonlistener if the listener is not al
ready registered.
... void removeaddonlistener( in addonlistener listener ) parameters listener the addonlistener to remove addtypelistener() adds a new typelistener if the listener is not al
ready registered.
DeferredTask.jsm
void arm(); disarm cancel any request for a delayed execution of the task, though the task itself cannot be canceled in case it is al
ready running.
...}, 2000); // the task is
ready, but will not be executed until requested.
... if the timer is al
ready armed when the "finalize" method is called, then the task is executed immediately.
... if the task was al
ready running at this point, then one last execution from start to finish will happen again, immediately after the current execution terminates.
Initial setup
you also need to determine if a localization effort al
ready exists for your locale.
... here's what you do: look through the existing localization community directory to see if one al
ready exists for your locale.
... if a community al
ready exists, reach out to them and ask how you can help.
... mozilla ldap you will need a mozilla ldap account once you're
ready to have your localization registered on the main mozilla repositories.
Python binding for NSS
programmers al
ready familiar with nss/nspr will be quite comfortable with python-nss.
...for example it is al
ready known there are some naming inconsistencies.
...some functionality and interface have al
ready been deprecated due to lessons learned.
... the following other non-ipv6 fixes were also made because they were discovered while doing the ipv6 work: move definition of type_
ready to py_nspr_common.h so it can be shared.
JSAPI User Guide
throwing and catching exceptions we have al
ready seen one example of how to throw an exception from a jsnative function.
...or a js object that mirrors data and functions that al
ready exist in the application may provide an object-oriented interface to c code that is not otherwise, strictly-speaking, object-oriented itself.
...upproperty js_lookupucproperty js_getproperty js_getucproperty js_getpropertyattributes js_getucpropertyattributes js_getpropertyattrsgetterandsetter js_getucpropertyattrsgetterandsetter js_setproperty js_setucproperty js_setpropertyattributes js_setucpropertyattributes js_deleteproperty2 js_deleteucproperty2 js_al
readyhasownproperty js_al
readyhasownucproperty unicode javascript source js_compilescript js_compileucscript js_compilescriptforprincipals js_compileucscriptforprincipals js_compilefunction js_compileucfunction js_compilefunctionforprincipals js_compileucfunctionforprincipals js_evaluatescript js_evaluateucscript js_ev...
...conversely, if you want to strip user a's administrator privileges, but you have al
ready given administrator functions to user a's scripts, that's even worse.
ContentIndex - Web APIs
// reference registration const registration = await navigator.serviceworker.
ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index.
...amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.
ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, b...
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.
ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entries) { const list...
... async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.
ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker.
Document - Web APIs
document.
readystateread only returns loading status of the document.
... document.on
readystatechange represents the event handling code for the
readystatechange event.
...
readystatechange fired when the
readystate attribute of a document has changed.
... also available via the on
readystatechange property.
EventSource - Web APIs
eventsource.
readystate read only a number representing the state of the connection.
... eventsource.close() closes the connection, if any, and sets the
readystate attribute to closed.
... if the connection is al
ready closed, the method does nothing.
...it, in turn, creates a new <li> element and writes the message's data into it, then appends the new element to the list element al
ready in the document.
FileSystemDirectoryEntry.getDirectory() - Web APIs
options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file al
ready exists.
... fileerror.path_exists_err the create and exclusive options were both true, indicating that the directory should be created but must not al
ready exist, but the directory does in fact al
ready exist.
...the parent directory must al
ready exist.
... values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path al
ready exists.
FileSystemDirectoryEntry.getFile() - Web APIs
options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file al
ready exists.
... fileerror.path_exists_err the create and exclusive options were both true, indicating that the file should be created but must not al
ready exist, but the file does in fact al
ready exist.
...the parent directory must al
ready exist.
... values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path al
ready exists.
HTMLMediaElement.load() - Web APIs
appropriate events will be sent to the media element itself as the load process proceeds: if the element is al
ready in the process of loading media, that load process is aborted and the abort event is sent.
... if the element has al
ready been initialized with media, the emptied event is sent.
... if resetting the playback position to the beginning of the media actually changes the playback position (that is, it was not al
ready at the beginning), a timeupdate event is sent.
... once media has been selected and loading is
ready to begin, the loadstart event is delivered.
Headers.append() - Web APIs
the append() method of the headers interface appends a new value onto an existing header inside a headers object, or adds the header if it does not al
ready exist.
... the difference between set() and append() is that if the specified header al
ready exists and accepts multiple values, set() will overwrite the existing value with the new one, whereas append() will append the new value onto the end of the set of values.
... example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using append(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' if the specified header al
ready exists, append() will change its value to the specified value.
... if the specified header al
ready exists and accepts multiple values, append() will append the new value to the end of the value set: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); myheaders.get('accept-encoding'); // returns 'deflate, gzip' to overwrite the old value with a new one, use headers.set.
Headers.set() - Web APIs
the set() method of the headers interface sets a new value for an existing header inside a headers object, or adds the header if it does not al
ready exist.
... the difference between set() and headers.append is that if the specified header al
ready exists and accepts multiple values, set() overwrites the existing value with the new one, whereas headers.append appends the new value to the end of the set of values.
... example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then set a new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not al
ready exist, set() will create it and set its value to the specified value.
... if the specified header does al
ready exist and does accept multiple values, set() will overwrite the existing value with the new one: myheaders.set('accept-encoding', 'deflate'); myheaders.set('accept-encoding', 'gzip'); myheaders.get('accept-encoding'); // returns 'gzip' you'd need headers.append to append the new value onto the values, not overwrite it.
MediaSource.addSourceBuffer() - Web APIs
invalidstateerror the mediasource is not in the "open"
readystate.
... notsupportederror the specified mimetype isn't supported by the user agent, or is not compatible with the mime types of other sourcebuffer objects that are al
ready included in the media source's sourcebuffers list.
...ew the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.
readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sour...
...cebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.
readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'addsourcebuffer()' in that specification.
PerformanceTiming - Web APIs
performancetiming.fetchstart read only when the browser is
ready to fetch the document using an http request.
... performancetiming.domloading read only when the parser started its work, that is when its document.
readystate changes to 'loading' and the corresponding
readystatechange event is thrown.
... performancetiming.dominteractive read only when the parser finished its work on the main document, that is when its document.
readystate changes to 'interactive' and the corresponding
readystatechange event is thrown.
... performancetiming.domcomplete read only when the parser finished its work on the main document, that is when its document.
readystate changes to 'complete' and the corresponding
readystatechange event is thrown.
RTCPeerConnection - Web APIs
also included is a list of any ice candidates that may al
ready have been generated by the ice agent since the offer or answer represented by the description was first instantiated.currentremotedescription read only the read-only property rtcpeerconnection.currentremotedescription returns an rtcsessiondescription object describing the remote end of the connection as it was most recently successfully negotiated since the last time the rtcpeerconnection finishe...
...also included is a list of any ice candidates that may al
ready have been generated by the ice agent since the offer or answer represented by the description was first instantiated.getdefaulticeservers() the getdefaulticeservers() method of the rtcpeerconnection interface returns an array of objects based on the rtciceserver dictionary, which indicates what, if any, ice servers the browser will use by default if none are provided to the rtcpeerconnection in its rtcconfiguration.
...the answer contains information about any media al
ready attached to the session, codecs and options supported by the browser, and any ice candidates al
ready gathered.
...if the negotiation al
ready happened, a new one will be needed for the remote peer to be able to use it.
Streams API concepts - Web APIs
the chunks placed in a stream are said to be enqueued — this means they are waiting in a queue
ready to be read.
... you can make use of
ready-made readable streams via mechanisms like a response.body from a fetch request, or roll your own streams using the readablestream() constructor.
...you can use whatever code you like to produce the chunks
ready for writing; the writer plus the associated code is called a producer.
...when a stream later in the chain is still busy and isn't yet
ready to accept more chunks, it sends a signal backwards through the chain to tell earlier transform streams (or the original source) to slow down delivery as appropriate so that you don't end up with a bottleneck anywhere.
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
if we al
ready have video coming in from the remote peer (which we can see if the remote view's <video> element's srcobject property al
ready has a value), we do nothing.
...since a peer can only accept offers when in the stable state, the peer has thus rescinded its offer and is
ready to receive the offer from the remote (impolite) peer.
...ch(err) { if (!ignoreoffer) { throw err; } } } } catch(err) { console.error(err); } }; since rollback works by postponing changes until the next negotiation (which will begin immediately after the current one is finished), the polite peer needs to know when it needs to throw away a received offer if it's currently waiting for a reply to an offer it's al
ready sent.
...if the received message is an offer and the local peer is the impolite peer, and a collision is occurring, we ignore the offer because we want to continue to try to use the offer that's al
ready in the process of being sent.
Writing WebSocket client applications - Web APIs
var examplesocket = new websocket("wss://www.example.com/socketserver", "protocolone"); on return, examplesocket.
readystate is connecting.
... the
readystate will become open once the connection is
ready to transfer data.
... if you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols: var examplesocket = new websocket("wss://www.example.com/socketserver", ["protocolone", "protocoltwo"]); once the connection is established (that is,
readystate is open), examplesocket.protocol will tell you which protocol the server selected.
... examplesocket.send(json.stringify(msg)); // blank the text input element,
ready to receive the next line of text from the user.
Movement, orientation, and motion: A WebXR example - Web APIs
async function onxrbuttonclick(event) { if (!xrsession) { navigator.xr.requestsession(session_type) .then(sessionstarted); } else { await xrsession.end(); if (xrsession) { sessionended(); } } } this begins by looking at the value of xrsession to see if we al
ready have a xrsession object representing an ongoing webxr session.
... if we al
ready have an ongoing session, on the other hand, we call its end() method to stop the session.
...then we let the session know we're
ready to draw a frame by calling its requestanimationframe() function.
...with webgl now configured to render to the xr device, we clear the frame to black and are
ready to begin rendering.
Using IIR filters - Web APIs
but what is this and how does it differ from the biquadfilternode we have al
ready?
...it's a commonly-used type and we al
ready have it as a node in the web audio api.
...and this is where the iir filter node is useful — you can create your own if none of the ala
ready available settings is right for what you want.
... if you want to play with the iir filter node and need some values to help along the way, there's a table of al
ready calculated values here; on pages 4 & 5 of the linked pdf the an values refer to the feedforward values and the bn values refer to the feedback.
Using the Web Storage API - Web APIs
refox e.code === 22 || // firefox e.code === 1014 || // test name field too, because code might not be present // everything except firefox e.name === 'quotaexceedederror' || // firefox e.name === 'ns_error_dom_quota_reached') && // acknowledge quotaexceedederror only if there's something al
ready stored (storage && storage.length !== 0); } } and here is how you would use it: if (storageavailable('localstorage')) { // yippee!
... testing whether your storage has been populated to start with, in main.js, we test whether the storage object has al
ready been populated (i.e., the page was previously accessed): if(!localstorage.getitem('bgcolor')) { populatestorage(); } else { setstyles(); } the storage.getitem() method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor item exists; if not, we run populatestorage() to add the existing customization values to the storage.
... if there are al
ready values there, we run setstyles() to update the page styling with the stored values.
... setting values in storage storage.setitem() is used both to create new data items, and (if the data item al
ready exists) update existing values.
XMLHttpRequest - Web APIs
xmlhttprequest.on
readystatechange an eventhandler that is called whenever the
readystate attribute changes.
... xmlhttprequest.
readystate read only returns an unsigned short, the state of the request.
... event handlers on
readystatechange as a property of the xmlhttprequest instance is supported in all browsers.
... methods xmlhttprequest.abort() aborts the request if it has al
ready been sent.
Media events - Developer guides
this corresponds to the have_future_data
readystate.
... canplaythrough sent when the
readystate changes to have_enough_data, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level.
... emptied the media has become empty; for example, this event is sent if the media has al
ready been loaded (or partially loaded), and the load() method is called to reload it.
... mozaudioavailable sent when an audio buffer is provided to the audio layer for processing; the buffer contains raw audio samples that may or may not al
ready have been played by the time you receive the event.
<input type="datetime-local"> - HTML: Hypertext Markup Language
for example, if you are creating a system where the user is likely to al
ready be logged in, with their locale al
ready set, you could provide the timezone in a hidden input type.
...exactly because you will al
ready be dead, so the companies using your software will be stuck using your software without any other coder who knows the system well enough to come in and fix it.
...ne'; fallbackpicker.style.display = 'block'; fallbacklabel.style.display = 'block'; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populatedays(monthselect.value); populateyears(); populatehours(); populateminutes(); } function populatedays(month) { // delete the current set of <option> elements out of the // day <select>,
ready for the next set to be injected while(dayselect.firstchild){ dayselect.removechild(dayselect.firstchild); } // create variable to hold new number of days to inject var daynum; // 31 or 30 days?
...daynum = 29 : daynum = 28; } // inject the right number of new <option> elements into the day <select> for(i = 1; i <= daynum; i++) { var option = document.createelement('option'); option.textcontent = i; dayselect.appendchild(option); } // if previous day has al
ready been set, set dayselect's value // to that day, to avoid the day jumping back to 1 when you // change the year if(previousday) { dayselect.value = previousday; // if the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g.
Cross-Origin Resource Sharing (CORS) - HTTP
note: these are the same kinds of cross-site requests that web content can al
ready issue, and no response data is released to the requester unless the server sends an appropriate header.
...code of this sort might be used in javascript deployed on foo.example: const xhr = new xmlhttprequest(); const url = 'https://bar.other/resources/public-data/'; xhr.open('get', url); xhr.on
readystatechange = somehandler; xhr.send(); this performs a simple exchange between the client and the server, using cors headers to handle the privileges: let's look at what the browser will send to the server in this case, and let's see how the server responds: get /resources/public-data/ http/1.1 host: bar.other user-agent: mozilla/5.0 (macintosh; intel mac os x 10.14; rv:71.0) gecko/20100101 ...
... the following is an example of a request that will be preflighted: const xhr = new xmlhttprequest(); xhr.open('post', 'https://bar.other/resources/post-here/'); xhr.setrequestheader('x-pingother', 'pingpong'); xhr.setrequestheader('content-type', 'application/xml'); xhr.on
readystatechange = handler; xhr.send('<person><name>arun</name></person>'); the example above creates an xml body to send with the post request.
...content on foo.example might contain javascript like this: const invocation = new xmlhttprequest(); const url = 'http://bar.other/resources/credentialed-content/'; function callotherdomain() { if (invocation) { invocation.open('get', url, true); invocation.withcredentials = true; invocation.on
readystatechange = handler; invocation.send(); } } line 7 shows the flag on xmlhttprequest that has to be set in order to make the invocation with cookies, namely the withcredentials boolean value.
JavaScript modules - JavaScript
most servers al
ready set the correct type for .js files, but not yet for .mjs files.
... servers that al
ready serve .mjs files correctly include github pages and http-server for node.js.
... this is ok if you are using such an environment al
ready, or if you aren't but you know what you are doing and have access (i.e.
... modules and classes as we hinted at earlier, you can also export and import classes; this is another option for avoiding conflicts in your code, and is especially useful if you've al
ready got your module code written in an object-oriented style.
Promise.all() - JavaScript
return value an al
ready resolved promise if the iterable passed is empty.
...note, google chrome 58 returns an al
ready resolved promise in this case.
... if an empty iterable is passed, then this method returns (synchronously) an al
ready resolved promise.
...logs // promise { <state>: "fulfilled", <value>: array[3] } // promise { <state>: "fulfilled", <value>: array[4] } // promise { <state>: "rejected", <reason>: 555 } asynchronicity or synchronicity of promise.all this following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of promise.all: // we are passing as argument an array of promises that are al
ready resolved, // to trigger promise.all as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.all(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log('the stack is now empty'); console.log(p); }); // logs, in or...
Navigation and resource timings - Web Performance
fetchstart when the browser is
ready to fetch the document using an http request.
... domloading when the parser started its work, that is when its document.
readystate changes to 'loading' and the corresponding
readystatechange event is thrown.
... dominteractive when the parser finished its work on the main document, that is when its document.
readystate changes to 'interactive' and the corresponding
readystatechange event is thrown.
... domcomplete when the parser finished its work on the main document, that is when its document.
readystate changes to 'complete' and the corresponding
readystatechange event is thrown.
The building blocks of responsive design - Progressive web apps (PWAs)
typical desktop layout in our example, we have a desktop layout, as we've al
ready seen.
...as mentioned above, we used mozilla brick, a collection of
ready-rolled mobile ui components, in the making of the mobile app layout.
...for more on using brick, read mozilla brick:
ready made ui components.
...but those solutions are definitely not
ready for production yet — both are in a very early stage of standardization, and have no support across browsers.
Interacting with page scripts - Archive of obsolete content
the "main.js" opens the local file "page.html" and attaches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.open({ url: self.data.url("page.html"), on
ready: attachscript }); function attachscript(tab) { tab.attach({ contentscriptfile: self.data.url("content-script.js") }); } the content script defines an object and assigns it to unsafewindow twice: the first time using cloneinto(), the second time using simple assignment: // content-script.js var contentscriptobject = {"greeting" : "hello from add-on"}; unsafewindow.clonedcontentscript...
...the "main.js" opens the local file "page.html" and attaches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.open({ url: self.data.url("page.html"), on
ready: attachscript }); function attachscript(tab) { tab.attach({ contentscriptfile: self.data.url("content-script.js") }); } the content script defines a function greetme() and exports it to the page script context.
...n.js" will create a page-mod that will attach "content-script.js" to the target web page, and will then load the target web page: var tabs = require("sdk/tabs"); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageurl = self.data.url("page.html") var pagemod = mod.pagemod({ include: pageurl, contentscriptfile: self.data.url("content-script.js"), contentscriptwhen: "
ready" }) tabs.open(pageurl); the target web page "page.html" includes a button and a page script: <html> <head> <meta charset="utf-8"> </head> <body> <input id="message" type="button" value="send a message"/> <script type="text/javascript" src="page-script.js"></script> </body> </html> the content script "content-script.js" adds an event listener to the button, that sends a cu...
/loader - Archive of obsolete content
provide an environment for loading commonjs style modules, which makes it possible to consume lots of interesting code that has al
ready been developed.
... to reuse module instances that are al
ready loaded.
...}) require() as al
ready mentioned in loading modules it's common to start execution by loading a main module.
platform/xpcom - Archive of obsolete content
if the factory or service is al
ready registered, this function throws components.results.ns_error_factory_exists.
... so if a factory is registered with the contract id "@me.org/mycomponent", and another factory is al
ready registered with that contract id, then: components.classes["@me.org/mycomponent"] will return the old factory, while: xpcom.factorybycontract("@me.org/mycomponent") will return the new one.
... if the object implements an interface that's al
ready defined in xpcom, you can pass that in here: var about = aboutfactory.createinstance(null, ci.nsiaboutmodule); // you can now access the nsiaboutmodule interface of the 'about' object if you will be getting the wrappedjsobject property from the returned object to access its javascript implementation, pass ci.nsisupports here: var custom = factory.createinstance(null, ci.nsisupports).wrappedjso...
How to convert an overlay extension to restartless - Archive of obsolete content
step 2a: load your jsm from chrome:// now with that preface out of the way, this part is easy: drop support for firefox 3.x if you haven't al
ready, move your jsm files to wherever you've got your chrome mapping to for your xul overlay and/or windows, import your files from that new chrome mapped path instead of the old resource one, and remove your "resource" line from your chrome.manifest file.
...in such cases, request.
readystate == 4, request.status == 0 and request.response will evaluate to true.
...if you were using input streams you al
ready had to deal with this because they weren't an option without extraction.
Tabbed browser - Archive of obsolete content
current: 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 al
ready displays the desired url--if one is al
ready open.
...the following code demonstrates how to re-use an existing tab that al
ready displays the desired url/uri.
....hasmoreelements()) { var browserwin = browserenumerator.getnext(); var tabbrowser = browserwin.gbrowser; // check each tab of this browser instance var numtabs = tabbrowser.browsers.length; for (var index = 0; index < numtabs; index++) { var currentbrowser = tabbrowser.getbrowseratindex(index); if (url == currentbrowser.currenturi.spec) { // the url is al
ready opened.
Localizing an extension - Archive of obsolete content
if you haven't al
ready created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension.
...we do this by creating a string bundle, using the following code: <stringbundleset id="stringbundleset"> <stringbundle id="string-bundle" src="chrome://stockwatcher2/locale/stockwatcher2.properties"/> </stringbundleset> this establishes a new string bundle, referenced by the id "string-bundle", whose keys and values are to be loaded from the stockwatcher2.properties file we've al
ready created.
...id="myextensionname-filename") update the javascript code now we're
ready to revise the javascript code to load the strings from the string bundle instead of using literal strings.
Mozilla Crypto FAQ - Archive of obsolete content
also note that mozilla support for pgp and other security schemes may also be made available by commercial security vendors or by independent developers, using the various public apis al
ready present in mozilla.
... however, in an advisory opinion issued in reference to the bernstein case, the bureau of export administration (bxa) has stated the following: "concerning the posting onto a mirror or archive site of al
ready-posted source code, notification is required only for the initial posting." bxa and nsa have al
ready been notified of the posting of encryption-related source code on the mozilla site, and in light of this opinion we have therefore decidednot to ask mirror sites to provide notification themselves.
...export controls on encryption software al
ready been ruled unconstitutional?
Frequently Asked Questions - Archive of obsolete content
to help us make the best use of our time, please first search in the svg component of our bug database to check that the issue hasn't al
ready been reported.
...however, mozilla's implementation al
ready supports some things that adobe's lacks, particularly parts of the xml and svg doms.
...if you don't have an irc client then install chatzilla into mozilla/mozilla firefox (note it may al
ready be built in).
Using gdb on wimpy computers - Archive of obsolete content
how do i see what libraries i al
ready have loaded?
... you can see what libraries you al
ready have loaded with the info sharedlibrary command: (gdb) info shar from to syms read shared object library 0x4044a000 0x4044d08c yes /lib/libdl.so.2 0x4044e000 0x4048ff90 yes /usr/lib/libstdc++-libc6.1-1.so.2 0x40491000 0x404ad9d8 yes /lib/libm.so.6 0x404ae000 0x405a285c yes /lib/libc.so.6 0x40000000 0x40013ed0 yes /lib/ld-linux.so.2 0x40607000 0x4061554c no /usr/lib/libz.so.1 0x40763000 0x4088af74 no /usr/lib/libgtk-1.2.so.0 0x4088b000 0x408c04d4 no /usr/lib/libgdk-1.2.so.0 [...] gdb is taking forever to load a shared library.
...versions of gdb earlier than 5 use a very slow algorithm for walking the list of al
ready loaded symbols as it adds symbols to its symbol table.
Venkman Introduction - Archive of obsolete content
even if you are al
ready using venkman, the features, procedures, and tips described here will make you a more confident web developer and debugger.
... if you don't al
ready have venkman or would like to upgrade, you can easily get the latest version from firefox add-ons.
...but the steps described here can give you a basic feel for the debugger if you haven't al
ready had some experience using it, and they provide the basis for the more interesting and practical examples in the articles that follow this one.
Anonymous Content - Archive of obsolete content
focus events should also be stopped if the bound element is al
ready focused.
... for example, if the user has al
ready focused the textfield within an html file upload control, then the file upload control is now also focused.
... if the user then focuses the button inside the file upload control, the focus event generated for the button is stopped before it reaches the file control, since the file control is al
ready focused.
Elements - Archive of obsolete content
if supported, in strongly typed languages the bound element can be referenced not only as any of the interfaces that the element might al
ready support (e.g., htmlelement) but also as any of the interfaces described by this attribute.
...so full access to anonymous nodes generated by the binding is al
ready possible.
... here are some examples of cases in which the behavior of your code may change due to this change in firefox 3: if you have two fields, one named a and one named b, and field a sets .b, the value of .b will depend on whether or not .a has al
ready been accessed.
Writing to Files - Archive of obsolete content
if this flag is not used, the data is written at the beginning of the file, overwriting what is al
ready there.
... nocreate if used, don't create a new file if it does not al
ready exist.
...in either case, if the file al
ready exists, it will be truncated to zero length.
MenuModification - Archive of obsolete content
the appenditem method will create a menupopup element if it doesn't al
ready exist.
... if the menu al
ready has a menupopup, the new menuitem will be appended to this existing one.
...the first time the function is called, the haschildnodes method will return false, however the second time, the method will return true as the items have al
ready been added to the menu.
OpenClose - Archive of obsolete content
these are: if the menu is al
ready open, or al
ready in the process of being opened.
... naturally, attempting to open a menu that is al
ready open doesn't have any effect.
... for example, you could use the state property to determine if a panel is al
ready open.
PopupEvents - Archive of obsolete content
the popupshown event the popupshown event is fired once a popup is al
ready visible.
...you also cannot cancel the hiding of a menupopup when a user has made a selection from a menu, as it is al
ready too late to do so.
... in this situation the command event has al
ready been sent to the selected menuitem and the operation al
ready carried out.
RDF Modifications - Archive of obsolete content
when parsing, any triples that al
ready exist are not added again.
...assuming that the 'obelisk' photo doesn't have a description al
ready, adding the triple listed above should cause a new result to be available for this photo.
...the only extra complication to deal with in the multiple query case is when a particular result's member resource al
ready matches a query, yet the new rdf triple would cause an earlier query to match.
XML - Archive of obsolete content
using a combination of xul's
ready-made widgets (e.g., menubar, scrollbar, progressmeter, and so on) and xul's incorporation of such standards as html4, dom1/2, and cascading stylesheets, you can design any interface that you can imagine, using any number of different features, tools, and methodologies.
...any familiarity you al
ready have with xml will help you quickly get up to speed developing with xul.
...like all really good technologies, xul and its xp cousins are al
ready being used in ways not imagined by their creators and growing propitiously out of control.
prefwindow - Archive of obsolete content
if a window with that type is al
ready open, this method will just switch that window to the front and focus it instead of opening another window.
... notes usage patterns opening/initializing a prefwindow note that you can define an initwithparams() function in your sub window - to handle parameters passed using openwindow() in case the window was al
ready open.
... initwithparams(window.arguments[0]); // we expect a single parameter to be passed to the window } function initwithparams(aparams) { // this will also get called when an al
ready open window is activated using openwindow() } closing a prefwindow sometimes you need to do things when the prefwindow is closed, such as things that can't (or shouldn't) be handled as preferences, such as saving passwords or updating sqlite data.
richlistbox - Archive of obsolete content
efix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata additemtoselection( item ) return type: no return value selects the given item, without deselecting any other items that are al
ready selected.
...if the item is al
ready visible, no scrolling occurs.
...if the item is al
ready visible, no scrolling occurs.
2006-10-27 - Archive of obsolete content
he has al
ready built firefox 1.5.0.7 on the same machine with no problems.
... discussions final ff release al
ready announced october 23rd: axel hecht posted an answer to cédric corazza posting.
... cédric's posting was about a french site which had al
ready announced the availablity of ff 2.0 final release and provided download links, even though the release was on october 24.
Reference - Archive of obsolete content
this will impact the presentation of future examples if it hasn't al
ready.
...--jonnyq i've al
ready added those methods in the methods listing, but i haven't defined them yet.
...--davidcary 06:42, 31 january 2007 (pst) we al
ready discussed this.
Game distribution - Game development
self-hosting if you are a front-end developer, you may al
ready know what to do.
... the chrome web store is also an attractive option — again, having a manifest file
ready, zipping your game and filling in the online submission form is about all that's required.
...native stores are al
ready filled with established devs selling great games, so you have to be talented and lucky to get noticed.
Building up a basic demo with PlayCanvas editor - Game development
when you are
ready to continue with our tutorial, go to your canvas homepage — for example mine is https://playcanvas.com/end3r.
...even though it's a blank new project we don't have to start entirely from scratch — the camera and directional light are prepared al
ready, so you don't have to worry about them.
...as you can see, the file contains some boilerplate code al
ready: pc.script.create('boxanimation', function (app) { // creates a new boxanimation instance var boxanimation = function (entity) { this.entity = entity; }; boxanimation.prototype = { // called once after all resources are loaded and before the first update initialize: function () { }, // called every frame, dt is time in seconds since last ...
Building up a basic demo with the PlayCanvas engine - Game development
if you have al
ready worked through our building up a basic demo with three.js article (or you are familiar with other 3d libraries) you'll notice that playcanvas works on similar concepts: camera, light and objects.
...there is one helper variable al
ready included, which will store a reference to the <canvas> element.
... animation we al
ready used translate or rotate to adjust the position of the shapes; we could also change their positions directly with setposition, or scale them.
Unconventional controls - Game development
there's al
ready a gamepad api working on the desktop computers, so we can imitate the experience, but we can go even further.
...captain rogers had the keyboard controls implemented al
ready: this.cursors = this.input.keyboard.createcursorkeys(); //...
...the last value is grabstrength, which is a float between 0 and 1 — when reaching 1 (fist fully clenched), we show an alert for now (in a full game this could be replaced with the shooting logic.) that's it — everything you needed for a working leap motion example in javascript is here al
ready.
WAI-ARIA basics - Learn web development
let's look at an example — our website-no-roles example (see it live) has the following structure: <header> <h1>...</h1> <nav> <ul>...</ul> <form> <!-- search form --> </form> </nav> </header> <main> <article>...</article> <aside>...</aside> </main> <footer>...</footer> if you try testing the example with a screenreader in a modern browser, you'll al
ready get some useful information.
...we al
ready talked about using the aria-label property to provide a label where we don't want the label to be visible to sighted users (see the signposts/landmarks section, above).
...enabled; use it to tell us what you play.'; } else { instruitem.input.disabled = true; instruitem.label.style.color = '#999'; instruitem.input.setattribute('aria-disabled', 'true'); instruitem.input.removeattribute('aria-label'); hiddenalert.textcontent = 'instruments played field now disabled.'; } } describing non-semantic buttons as buttons a few times in this course al
ready, we've mentioned the native accessibilty of (and the accessibility issues behind using other elements to fake) buttons, links, or form elements (see ui controls in the html accessibility article, and enhancing keyboard accessibility, above).
Grids - Learn web development
>seven</div> </div> .container { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); grid-auto-rows: minmax(100px, auto); grid-gap: 20px; } this works because grid is creating as many 200 pixel columns as will fit into the container, then sharing whatever space is leftover between all of the columns — the maximum is 1fr which, as we al
ready know, distributes space evenly between tracks.
...it has a grid defined al
ready, and a simple article outlined.
... a css grid, grid framework grid "frameworks" tend to be based around 12 or 16 column grids and with css grid, you don’t need any third party tool to give you such a framework — it's al
ready there in the spec.
Legacy layout methods - Learn web development
there are many flexbox-based grid systems available and flexbox can solve many of the issues that we’ve al
ready discovered when creating our grid above.
...class="col">8</div> <div class="col">9</div> <div class="col">10</div> <div class="col">11</div> <div class="col">12</div> </div> <div class="row"> <div class="col">13</div> <div class="col">14</div> <div class="col">15</div> <div class="col">16</div> </div> </div> to start using skeleton we need to give the wrapper <div> a class of container — this is al
ready included in our html.
...we've done this al
ready as well.
CSS layout - Learn web development
at this point we've al
ready looked at css fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside.
... get started prerequisites before starting this module, you should al
ready: have basic familiarity with html, as discussed in the introduction to html module.
... introduction to css layout this article will recap some of the css layout features we've al
ready touched upon in previous modules — such as different display values — and introduce some of the concepts we'll be covering throughout this module.
Fundamental text and font styling - Learn web development
as you'll have al
ready experienced in your work with html and css, text inside an element is laid out inside the element's content box.
... text-decoration: sets/unsets text decorations on fonts (you'll mainly use this to unset the default underline on links when styling them.) available values are: none: unsets any text decorations al
ready present.
... you've reached the end of this article, and al
ready did some skill testing in our active learning section, but can you remember the most important information going forward?
What are browser developer tools? - Learn web development
if the tools are al
ready displayed, click on the debugger tab.
...(opera works the same way.) edge and internet explorer 11: press f12 and then, ctrl + 3, or if the tools are al
ready displayed, click on the debugger tab.
...to access the console in any browser: if the developer tools are al
ready open, click or press the console tab.
What is a Domain Name? - Learn web development
ed domain status: clientupdateprohibited registrant id:mmr-33684 registrant name:dns admin registrant organization:mozilla foundation registrant street: 650 castro st ste 300 registrant city:mountain view registrant state/province:ca registrant postal code:94041 registrant country:us registrant phone:+1.6509030800 as you can see, i can't register mozilla.org because the mozilla foundation has al
ready registered it.
... as we al
ready saw, when you want to display a webpage in your browser it's easier to type a domain name than an ip address.
... your browser asks your computer if it al
ready recognizes the ip address identified by this domain name (using a local dns cache).
Basic native form controls - Learn web development
you've al
ready met some form elements, including <form>, <fieldset>, <legend>, <textarea>, <label>, <button>, and <input>.
...they are a very convenient way to let the user enter any kind of data, and we've al
ready seen a few simple examples.
...you've met some of these al
ready, but below is a list of those common attributes, for your reference: attribute name default value description autofocus false this boolean attribute lets you specify that the element should automatically have input focus when the page loads.
HTML basics - Learn web development
an attribute should always have the following: a space between it and the element name (or the previous attribute, if the element al
ready has one or more attributes).
...take the <img> element that we al
ready have in our html page: <img src="images/firefox-icon.png" alt="my test image"> this contains two attributes, but there is no closing </img> tag and no inner content.
... add a link to your page now, if you haven't al
ready done so.
Installing basic software - Learn web development
a library tends to be an existing javascript or css file that provides
ready-rolled functionality for you to make use of in your code.
... installing a text editor you probably al
ready have a basic text editor on your computer.
... before going on, you should install at least two of these browsers and have them
ready for testing.
JavaScript basics - Learn web development
-, *, / 9 - 3; 8 * 2; // multiply in js is an asterisk 9 / 3; assignment as you've seen al
ready: this assigns a value to a variable.
...you have al
ready seen some uses of functions previously.
... if it isn't (meaning it must al
ready have changed), the src value swaps back to the original image path, to the original state.
Structuring a page of content - Learn web development
previous overview: introduction to html structuring a page of content
ready for laying it out using css is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.
... prerequisites: before attempting this assessment you should have al
ready worked through the rest of the course, with a particular emphasis on document and website structure.
... details of what you have al
ready tried, and what you would like us to do, e.g.
Mozilla splash page - Learn web development
prerequisites: before attempting this assessment you should have al
ready worked through the rest of the multimedia and embedding module.
...then save pattern.png in the same directory (right click on the image to get an option to save it.) access the different images in the originals directory and save them in the same way; you'll want to save them in a different directory for now, as you'll need to manipulate (some of) them using a graphics editor before they're
ready to be used.
... details of what you would like us to do — for example what you have al
ready tried, if you are stuck and need help,.
Looping code - Learn web development
we al
ready met this in the previous article when we looked at switch statements — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves onto the code after it.
... we store the value entered into the text input in a variable called searchname, before then emptying the text input and focusing it again,
ready for the next search.
... we've al
ready provided you with: let i = 0; — your initializer.
Video and Audio APIs - Learn web development
implementing the javascript we've got a fairly complete html and css interface al
ready; now we just need to wire up all the buttons to get the controls working.
...regardless of whether the video was paused or playing when the stop button is pressed, you want it to be
ready to play afterwards.
... we use an if statement to check whether the active class has been set on the rwd button, indicating that it has al
ready been pressed.
Arrays - Learn web development
if we had 10 items to add to the invoice it would al
ready be annoying, but what about 100 items, or 1000?
...if you've not al
ready followed that section, create the array first in your console: let myarray = ['manchester', 'london', 'liverpool', 'birmingham', 'leeds', 'carlisle']; first of all, to add or remove an item at the end of an array we can use push() and pop() respectively.
... in the list for (let i = 0; i < myhistory.length; i++) { itemtext = myhistory[i]; const listitem = document.createelement('li'); listitem.textcontent = itemtext; list.appendchild(listitem); } // if the array length is 5 or more, remove the oldest search term if (myhistory.length >= 5) { // number 2 } // empty the search input and focus it,
ready for the next term to be entered searchinput.value = ''; searchinput.focus(); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; ...
Adding features to our bouncing balls demo - Learn web development
prerequisites: before attempting this assessment you should have al
ready worked through all the articles in this module.
...if it doesn't exist, it has al
ready been eaten by the evil circle, so there is no need to check it again.
... details of what you have al
ready tried, and what you would like us to do, e.g.
JavaScript object basics - Learn web development
overview: objects next in this article, we'll look at fundamental javascript object syntax, and revisit some javascript features that we've al
ready seen earlier in the course, reiterating the fact that many of the features you've al
ready dealt with are objects.
...while working with this example you should have your developer tools javascript console open and
ready to type in some commands.
...try entering the following line below the javascript code that's al
ready in your file, then saving and refreshing: const person = {}; now open your browser's javascript console, enter person into it, and press enter/return.
Working with Svelte stores - Learn web development
code along with us git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/06-stores or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/06-stores remember to run npm install && npm run dev to start your app in development mode.
... repl to code along with us using the repl, start at https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2 dealing with our app state we have al
ready seen how our components can communicate with each other using props, two-way data binding, and events.
...if you’ve al
ready worked with redux or vuex, then you'll be familiar with how this kind of store works.
What to do and what not to do in Bugzilla
resolving bugs as duplicate in general newer bugs should be marked as duplicates of older bugs, except when the newer bug contains more information (bug description clearer, patch al
ready attached, lots of people al
ready cc'ed, etc.).
...reports of problems with specific websites that result from bad coding practices al
ready determined to be “tech evangelism” cases by the module owner or peer, or problems that result from the use of proprietary technology, should be be moved to the tech evangelism product rather than being resolved as invalid.
...this isn't mandatory, but can help prevent accidental filing of duplicates of a bug that's al
ready been fixed.
Frame script loading and lifetime
passing allowdelayedload is a way to ensure that the script is loaded correctly, in case the tab is not
ready when making the call.
... disable any frame scripts al
ready loaded.
... there is no mechanism to unload frame scripts which are al
ready loaded.
Following the Android Toasts Tutorial from a JNI Perspective
this is the template that will follow our object of signatures: var my_jenv = null; try { my_jenv = jni.getforthread(); // do the jni work here } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } the reason we choose my_jenv for a variable name, and not jenv, is because the global privileged window scope of firefox for android has a variable jenv al
ready, and we don't want to mix.
... declare constructors, methods, and fields now that the sig's and java environment is
ready, it is now possible to declare the constructors, methods, and fields.
...we will add this to our sig object in slash notation: geckoappshell: 'lorg/mozilla/gecko/geckoappshell;' we then instantiate the geckoappshell class in jni and declare the getcontext method; dxr showed that this method accepted no arguments and returns a context, and we al
ready had the sig for context in our sig object.
Deferred
if the associated promise has al
ready been resolved, either to a value, a rejection, or another promise, this method does nothing.
... note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is al
ready resolved to the pending promise value as its resolution.
...if the promise has al
ready been resolved, either to a value, a rejection, or another promise, this method does nothing.
SVN for Localizers
if you're al
ready familiar with this information, skip ahead to mozilla's svn repositories.
...if you al
ready installed cygwin but it didn't include the svn package, run the cygwin installer again and be sure to check the box beside subversion package.
... note: if you do not al
ready have access to svn, visit this wiki page on how to get set up with an svn account before proceeding.
Mozilla Web Developer FAQ
however, it turns out mozilla is doing that al
ready.
... mozilla’s standards mode is, obviously, al
ready compatible with other browsers that implement the same standards reasonably correctly.
... on the other hand, mozilla’s quirks mode al
ready accommodates common non-standardisms that are due to the behaviors of common legacy browsers.
Profiling with the Firefox Profiler
this is ideal for a responsive application to be
ready to service incoming events.
... it's a good idea to search bugzilla before filing a bug about a performance problem in firefox but sometimes it's hard to find issues that have al
ready been reported.
...nightly builds are al
ready built with the appropriate flags.
NSPR Poll Method
the prototype of the poll method is print16 poll_method(prfiledesc *fd, print16 in_flags, print16 *out_flags); the purpose of the poll method is to allow a layer to modify that flags that will ultimately be used in the call to the underlying network transport's select (or equivalent) function, and to indicate that a layer is al
ready able to make progress in the manner suggested by the polling flags.
... for pr_recv, you should pass pr_poll_read as the in_flags argument to the poll method for pr_send, you should pass pr_poll_write as the in_flags argument to the poll method out_flags [output argument] if an i/o layer is
ready to satisfy the i/o request defined by in_flags without involving the underlying network transport, its poll method sets the corresponding event in *out_flags on return.
...if the caller wishes to test for read
ready (that is, pr_poll_read is set in in_flags) and the layer has input data buffered, the poll method would set the pr_poll_read event in *out_flags.
PR_MkDir
all the path components up to but not including the leaf component must al
ready exist.
...all the path components up to but not including the leaf component must al
ready exist.
... for example, if the pathname of the directory to be created is a/b/c/d, the directory a/b/c must al
ready exist.
PR_OpenSharedMemory
syntax #include <prshm.h> nspr_api( prsharedmemory * ) pr_opensharedmemory( const char *name, prsize size, printn flags, printn mode ); /* define values for pr_opensharememory(...,create) */ #define pr_shm_create 0x1 /* create if not exist */ #define pr_shm_excl 0x2 /* fail if al
ready exists */ parameters the function has the following parameters: name the name of the shared memory segment.
...when parameter create is (pr_shm_excl | pr_shm_create) and the shared memory al
ready exists, the function returns null with the error set to pr_file_exists_error.
... when parameter create is pr_shm_create and the shared memory al
ready exists, a handle to that memory segment is returned.
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
rv = secsuccess; prarenapool *arena = null; void *exthandle = null; prfiledesc *outfile = null; certsubjectpublickeyinfo *spki = null; certcertificaterequest *cr = null; secitem *encoding = null; /* if the certificate request file al
ready exists, delete it */ if (pr_access(certreqfilename, pr_access_exists) == pr_success) { pr_delete(certreqfilename); } /* open the certificate request file to write */ outfile = pr_open(certreqfilename, pr_create_file | pr_rdwr | pr_truncate, 00660); if (!outfile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing (%ld, %ld).\n...
... const char *nicknamestr, prbool sigverify) { secstatus rv = secsuccess; prfiledesc *headerfile = null; certcertificate *cert = null; headertype htype = certenc; /* if the intermediate header file al
ready exists, delete it */ if (pr_access(headerfilename, pr_access_exists) == pr_success) { pr_delete(headerfilename); } headerfile = pr_open(headerfilename, pr_create_file | pr_rdwr | pr_truncate, 00660); if (!headerfile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing (%ld, %ld).\n", headerfilename, pr_geterror(), pr_getoserror()); ...
... unsigned char ptext[modblocksize]; unsigned char encbuf[modblocksize]; unsigned int ptextlen; int index; unsigned int nwritten; unsigned int pad[1]; secitem paditem; unsigned int paddinglength = 0; seckeypublickey *pubkey = null; /* if the intermediate encrypted file al
ready exists, delete it*/ if (pr_access(encryptedfilename, pr_access_exists) == pr_success) { pr_delete(encryptedfilename); } /* read certificate from header file */ rv = readfromheaderfile(headerfilename, certenc, &data, pr_true); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not read certificate from header file\n"); goto cleanup; } ...
sample2
ytype keytype, secoidtag hashalgtag, certname *subject, prbool ascii, const char *certreqfilename) { secoidtag signalgtag; secitem result; print32 numbytes; secstatus rv = secsuccess; prarenapool *arena = null; void *exthandle = null; prfiledesc *outfile = null; certsubjectpublickeyinfo *spki = null; certcertificaterequest *cr = null; secitem *encoding = null; /* if the certificate request file al
ready exists, delete it */ if (pr_access(certreqfilename, pr_access_exists) == pr_success) { pr_delete(certreqfilename); } /* open the certificate request file to write */ outfile = pr_open(certreqfilename, pr_create_file | pr_rdwr | pr_truncate, 00660); if (!outfile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing (%ld, %ld).\n", certreqfilename, pr_geterror(), pr_getoserror()); goto cleanu...
...inds the certificate using nickname and saves it to the header file */ secstatus addcertificatetoheader(pk11slotinfo *slot, secupwdata *pwdata, const char *headerfilename, certcertdbhandle *certhandle, const char *nicknamestr, prbool sigverify) { secstatus rv = secsuccess; prfiledesc *headerfile = null; certcertificate *cert = null; headertype htype = certenc; /* if the intermediate header file al
ready exists, delete it */ if (pr_access(headerfilename, pr_access_exists) == pr_success) { pr_delete(headerfilename); } headerfile = pr_open(headerfilename, pr_create_file | pr_rdwr | pr_truncate, 00660); if (!headerfile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing (%ld, %ld).\n", headerfilename, pr_geterror(), pr_getoserror()); rv = secfailure; goto cleanup; } cert = cert_findcertbynic...
...prfiledesc *headerfile = null; prfiledesc *encfile = null; prfiledesc *infile = null; certcertificate *cert = null; secitem data; unsigned char ptext[modblocksize]; unsigned char encbuf[modblocksize]; unsigned int ptextlen; int index; unsigned int nwritten; unsigned int pad[1]; secitem paditem; unsigned int paddinglength = 0; seckeypublickey *pubkey = null; /* if the intermediate encrypted file al
ready exists, delete it*/ if (pr_access(encryptedfilename, pr_access_exists) == pr_success) { pr_delete(encryptedfilename); } /* read certificate from header file */ rv = readfromheaderfile(headerfilename, certenc, &data, pr_true); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not read certificate from header file\n"); goto cleanup; } /* read in an ascii cert and return a certcertificate */ cert...
FC_Login
the nss cryptographic module doesn't allow the so to log in if the normal user's pin is al
ready initialized.
... ckr_user_al
ready_logged_in: the user is al
ready logged in.
... usertype is cku_so and the normal user's pin is al
ready initialized.
NSC_Login
the nss cryptographic module doesn't allow the so to log in if the normal user's pin is al
ready initialized.
... ckr_user_al
ready_logged_in: the user is al
ready logged in.
... usertype is cku_so and the normal user's pin is al
ready initialized.
Hacking Tips
in lldb, if the allocation failure number shown is 1500, run `continue -i 1498` (subtracted 2 because we've al
ready hit it once and don't want to skip the last).
... but in this case you may have to call cx->recoverfromoutofmemory() if something further down the stack has al
ready reported the failure.
...// but if a different bit changes (either set or cleared), you may still stop // execution if the $mask bit happened to al
ready be set.
Exact Stack Rooting
storing a gcpointer in a gcthing storing your gcpointer inside of a gcthing that is al
ready in the liveset is the easiest way to keep a gcthing to the liveset.
...by using js::handlet in the interface instead of direct gcpointers, we ensure that the gcthing is al
ready rooted on some previous stack frame, freeing us from having to worry about rooting the gcthing for the duration of the call.
...if you think you do need to do one of these, ask on one of spidermonkey's support forums: maybe we've al
ready solved your problem using a different mechanism.
Thread Sanitizer
adjusting the build configuration create the build configuration file .mozconfig with the following content in your mozilla-central directory: mk_add_options moz_objdir=@topsrcdir@/objdir-ff-tsan mk_add_options moz_make_flags=-j12 # enable llvm specific code and build workarounds ac_add_options --enable-thread-sanitizer # if clang is al
ready in your $path, then these can simply be: # export cc=clang # export cxx=clang++ export cc="/path/to/clang" export cxx="/path/to/clang++" # llvm-symbolizer displays much more complete backtraces when data races are detected.
... # if it's not al
ready in your $path, then uncomment this next line: #export llvm_symbolizer="/path/to/llvm-symbolizer" # add tsan to our compiler flags export cflags="-fsanitize=thread -fpic -pie" export cxxflags="-fsanitize=thread -fpic -pie" # additionally, we need the tsan flag during linking.
.../bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then echo "directory $1 al
ready exists" else autoconf2.13 mkdir $1 cd $1 llvm_root="/path/to/llvm" cc="$llvm_root/build/bin/clang" \ cxx="$llvm_root/build/bin/clang++" \ cflags="-fsanitize=thread -fpic -pie" \ cxxflags="-fsanitize=thread -fpic -pie" \ ldflags="-fsanitize=thread -fpic -pie" \ ../configure --disable-debug --enable-optimize="-o2 -gline-tables-only" --enable-llvm-hack...
Places utilities for JavaScript
these just take in the node, as the interface is al
ready defined: asvisit(anode) asfullvisit(anode) ascontainer(anode) asquery(anode) annotations a few annotation names are defined here.
...der to get access to the bookmarks service, you have to run something like: components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); with places utils all you need to write is: placesutils.bookmarks this should save on the number of references to the service that are needed, and can help clean up interfaces that are al
ready fairly cluttered.
...information like keywords, descriptions, and post data is al
ready stored as annotations by firefox, but you can create additional ones.
Building the WebLock UI
notice also that when it's clicked, the button executes a javascript function called addthissite(), which we've al
ready defined in the weblock.js file in client code overview above.
...once it's installed and registered, the weblock component itself is
ready to go: xpcom finds it and adds it to the list of registered components, and then weblock observes the xpcom startup event and initializes itself.
...this id is the same one used by the <statusbar/> in navigator.xul, which means that the overlay mechanism will merge the new ui here (i.e., the weblock statusbarpanel) and the ui al
ready defined within that browser <statusbar/> at runtime.
Component Internals
once registration is complete and the notifications have fired, xpcom is
ready to be used by the application.
... the shutdown process when the application is
ready to shutdown xpcom, it calls ns_shutdownxpcom.
...instead of asking every developer to find and copy these various files into their own application, xpcom provides a single library of "not-
ready-to-freeze-but-really-helpful" classes that you can link into your application, as the following figure demonstrates.
Finishing the Component
the interfaces needed to block certain urls from loading are not frozen, and there is still some debate about how exactly this functionality should be exposed to embedders and component developers, so the apis are not
ready to be published.
...you have al
ready registered as a category to receive startup notification.
...a good place to get an nsiioservice is in the component's observe() method, which al
ready has a pointer to the service manager.
Preface
if you al
ready have a mozilla build or the source from mozilla 1.2 or later, then you can use the xpcom framework available there.
... if you don't al
ready have the mozilla source, then an even easier way to get and use xpcom is to download the gecko sdk, which is a collection of libraries and tools that features the xpcom component framework.
... whether you compile your code in the mozilla source tree or use the gecko sdk, you can build your own components which leverage components that al
ready exist in gecko.
Using XPCOM Utilities to Make Things Easier
« previousnext » this chapter goes back over the code you've al
ready created in the first part of the tutorial (see weblock1.cpp in the previous chapter) and uses xpcom tools that make coding a lot easier and more efficient.
...to avoid these kinds of redundancies, to regulate the way generic code is written, and to save typing, xpcom providesgeneric module macros that expand into the module code you've al
ready seen.
...for weblock, where the string classes need to be only wrappers around al
ready existing string data, trading advanced functionality for a much smaller footprint is the right way to go.
mozIStorageStatement
state long the current state defined by mozistoragestatement.moz_storage_statement_invalid, mozistoragestatement.moz_storage_statement_
ready, or mozistoragestatement.moz_storage_statement_executing.
... moz_storage_statement_
ready 1 the sql statement is
ready to be executed.
... clone() creates a copy of the statement whose state will be mozistoragestatement.moz_storage_statement_
ready.
nsIDOMOfflineResourceList
onupdate
ready nsidomeventlistener an event listener to be called when a resource update is
ready; this event is not currently used since versioned application caches aren't supported yet.
... update
ready 4 there is a new version of the application cache available.
...this means al
ready loaded resources should only update after a page refresh.
nsIDocShell
if session storage object does not al
ready exist, a new one will be created.
...if the timers are al
ready running, this has no effect.
...if the timers are al
ready suspended, this has no effect.
nsIFaviconService
if the icon data al
ready exists, we won't normally try to re-load the icon from the net (or more likely the cache).
...this will make the notifications more efficient since the icon will al
ready have data when the set favicon observer messages goes out.
...this will make the notifications more efficient since the icon will al
ready have data when the set favicon observer messages goes out.
nsIGeolocationProvider
method overview boolean is
ready(); obsolete since gecko 1.9.2 void shutdown(); void startup(); void watch(in nsigeolocationupdate callback); methods is
ready() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) reports whether or not the device is
ready and has a position.
... boolean is
ready(); parameters none.
... return value true if the device is
ready and has a position available to return; otherwise false.
nsIScriptableIO
the file does not have to exist al
ready; this method simply creates the file reference which may then be passed to the newinputstream() or newoutputstream() method to open the file for reading or writing.
... nocreate: if the file doesn't al
ready exist, don't create a new file.
... notruncate: if the file al
ready exists, overwrite the existing content instead of resetting the file size to 0 bytes.
nsIServiceManager
return value true if the service has al
ready been created.
... return value true if the service has al
ready been created.
... because services are instantiated lazily, methods are provided to test whether or not a service has al
ready been instantiated.
nsITextInputProcessor
this means that the clause is al
ready converted.
...this means that the clause is al
ready converted and is selected to convert.
... if the instance has a composition al
ready, this throws an exception.
nsIWindowWatcher
note: this method may dispatch a "toplevel-window-
ready" notification via nsiobserverservice if the window did not al
ready exist.
...must al
ready be escaped, if applicable.
...if a window with this name al
ready exists, the openwindow call may just load aurl in it (if aurl is not null) and return it.
nsIXULTemplateQueryProcessor
only fatal errors should be thrown, or ns_error_unexpected if generateresults() has al
ready been called.
... exceptions thrown ns_error_unexpected if generateresults() has al
ready been called.
...ns_error_unexpected if generateresults() has al
ready been called.
Using the clipboard
// import the services module for future use, if we're not in // a browser window where it's al
ready loaded.
...the transferable object will hold all of the data that you want until you're
ready to put it on the clipboard.
...call setdata only when you're
ready to copy to the system clipboard.
Gloda examples
a) show all messages in a conversation regardless of the folder in which they are stored, b) search messages by subject assuming that you have a message (glodamessage) in the conversation al
ready, this is straight forward using glodamessage.conversation.getmessagescollection() alistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items that are al
ready in our collection get re-indexed */ onitemsmodified: function _onitemsmodified(aitems, acollection) { }, /* called when items ...
... searches for all messages within a date range id_q=gloda.newquery(gloda.noun_message); // define a date range form yesterday to now id_q.daterange([new date() - 86400000, new date()]); var mylistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items that are al
ready in our collection get re-indexed */ onitemsmodified: function _onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function _onitemsremoved(aitems, acollection) { }, /* called when our database query completes */ onquerycompleted: function _onquerycompleted(acollection) { var it...
...y(gloda.noun_message) msg_q.involves(id) msg_q.getcollection({ /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items that are al
ready in our collection get re-indexed */ onitemsmodified: function _onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function _onitemsremoved(aitems, acollection) { }, ...
Working with windows in chrome code
it contains tips and example code on opening new windows, finding an al
ready opened window, and passing data between different windows.
... finding al
ready opened windows the window mediator xpcom component (nsiwindowmediator interface) provides information about existing windows.
...=== example: opening a window only if it's not opened al
ready === xxx tbd passing data between windows when working with multiple windows, you often need to pass information from one window to another.
Mozilla
this guide provides information that will not only help you get started as a mozilla contributor, but that you'll find useful to refer to even if you are al
ready an experienced contributor.
... mozilla svg project since you have come this far, you probably al
ready know that svg stands for scalable vector graphics, and that it is an xml language for sophisticated 2-dimensional graphics.
...it contains tips and example code on opening new windows, finding an al
ready opened window, and passing data between different windows.
about:debugging (before Firefox 68) - Firefox Developer Tools
note that this feature isn't that immediately useful to debugging desktop tabs — you can open up a toolbox to debug a tab easily enough al
ready — but this will become far more useful when about:debugging starts to support remote debugging, and this page can begin to list tabs available for debugging on mobile device browsers, simulators, etc.
... debugging workers for a service worker, if it is al
ready running, you'll see two buttons next to it, labeled "debug" and "push".
... if it's not al
ready running, you'll see one button, labeled "start": click this to start the service worker.
Document: DOMContentLoaded event - Web APIs
</script> checking whether loading is al
ready complete domcontentloaded may fire before your script has a chance to run, so it is wise to check before adding a listener.
... function dosomething() { console.info('dom loaded'); } if (document.
readystate === 'loading') { // loading hasn't finished yet document.addeventlistener('domcontentloaded', dosomething); } else { // `domcontentloaded` has al
ready fired dosomething(); } live example html <div class="controls"> <button id="reload" type="button">reload</button> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload {...
...t: 2rem; } js const log = document.queryselector('.event-log-contents'); const reload = document.queryselector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('
readystatechange', (event) => { log.textcontent = log.textcontent + `
readystate: ${document.
readystate}\n`; }); document.addeventlistener('domcontentloaded', (event) => { log.textcontent = log.textcontent + `domcontentloaded\n`; }); result specifications specification status comment html living standardthe definition of 'domcontentloaded' in that specification.
EventTarget.addEventListener() - Web APIs
simply because by the time the event listener would execute, the scope in which it was defined would have al
ready finished executing.
...ure (will be ignored) */) { var self=this; var wrapper=function(e) { e.target=e.srcelement; e.currenttarget=self; if (typeof listener.handleevent != 'undefined') { listener.handleevent(e); } else { listener.call(self,e); } }; if (type=="domcontentloaded") { var wrapper2=function(e) { if (document.
readystate=="complete") { wrapper(e); } }; document.attachevent("on
readystatechange",wrapper2); eventlisteners.push({object:this,type:type,listener:listener,wrapper:wrapper2}); if (document.
readystate=="complete") { var e=new event(); e.srcelement=window; wrapper2(e); } } else { this.attachevent("...
... } }; var removeeventlistener=function(type,listener /*, usecapture (will be ignored) */) { var counter=0; while (counter<eventlisteners.length) { var eventlistener=eventlisteners[counter]; if (eventlistener.object==this && eventlistener.type==type && eventlistener.listener==listener) { if (type=="domcontentloaded") { this.detachevent("on
readystatechange",eventlistener.wrapper); } else { this.detachevent("on"+type,eventlistener.wrapper); } eventlisteners.splice(counter, 1); break; } ++counter; } }; element.prototype.addeventlistener=addeventlistener; element.prototype.removeeventlistener=removeeventlistener; if (htmldocument) { htmldocument.
FileSystemFlags - Web APIs
methods which accept an options parameter of this type may specify zero or more of these flags as fields in an object, like this: datadirectoryentry.getdirectory("workspace", { create: true }, function(entry) { }); here, we see that the create property is provided, with a value of true, indicating that the directory should be created if it's not al
ready there.
...the parent directory must al
ready exist.
... values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path al
ready exists.
HTMLMediaElement - Web APIs
htmlmediaelement.
readystate read only returns a unsigned short (enumeration) indicating the readiness state of the media.
... emptied fired when the media has become empty; for example, when the media has al
ready been loaded (or partially loaded), and the htmlmediaelement.load() method is called to reload it.
... play fired when the paused property is changed from true to false, as a result of the htmlmediaelement.play() method, or the autoplay attribute playing fired when playback is
ready to start after having been paused or delayed due to lack of data progress fired periodically as the browser loads a resource.
Headers - Web APIs
methods headers.append() appends a new value onto an existing header inside a headers object, or adds the header if it does not al
ready exist.
... headers.set() sets a new value for an existing header inside a headers object, or adds the header if it does not al
ready exist.
... note: to be clear, the difference between headers.set() and headers.append() is that if the specified header does al
ready exist and does accept multiple values, headers.set() will overwrite the existing value with the new one, whereas headers.append() will append the new value onto the end of the set of values.
IDBDatabase: error event - Web APIs
bubbles yes cancelable no interface event event handler property onerror examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle al
ready exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours'...
...); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (eve...
...{ unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.onerror = () => { console.log(`error adding new item: ${newitem.tasktitle}`); }; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(newitem); }; ...
IDBDatabaseException - Web APIs
for example, an object, such as an object store or index, al
ready exists and a request attempted to create a new one.
... transaction_inactive_err 7 a request was made against a transaction that is either not currently active or is al
ready finished.
... ver_err 12 a request to open a database with a version lower than the one it al
ready has.
IDBObjectStore.add() - Web APIs
if a record al
ready exists in the object store with the key parameter as its key, then an error constrainerror event is fired on the returned request object.
... constrainterror an insert operation failed because the primary key constraint was violated (due to an al
ready existing record with the same primary key value).
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(e...
IDBRequest: error event - Web APIs
bubbles yes cancelable no interface event event handler property onerror examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle al
ready exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.addeventlistener('upgradeneeded', event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data i...
...e: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); dbopenrequest.addeventlistener('success', event => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.addeventlistener('error', () => { console.log(`error adding new ite...
... 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.onerror = () => { console.log(`error adding new item: ${newitem.tas...
IDBTransaction: error event - Web APIs
bubbles yes cancelable no interface event event handler property onerror examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle al
ready exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours'...
..., { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = obje...
...hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.onerror = () => { console.log(`error adding new item: ${newitem.tasktitle}`); }; const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add...
IDBTransactionSync - Web APIs
void abort( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following code: non_transient_err if this transaction has al
ready been committed or aborted.
... void commit( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if this transaction has al
ready been committed or aborted.
... objectstore() returns an object store that has al
ready been added to the scope of this transaction.
Key Values - Web APIs
appcommand_media_pause gdk_key_audiopause (0x1008ff31) qt::key_mediapause (0x1000085) keycode_media_pause (127) "mediaplay" starts or continues playing media at normal speed, if not al
ready doing so.
...has no effect if the media is currently stopped al
ready.
... in part form a number of consumer electronics technical specifications: dtv application software environment (part of the atsc specification) open cable application platform 1.1.3 ansi/cea-2014-b: web-based protocol and framework for remote user interface on upnp™ networks and the internet android keyevent key code values note: remote controls typically include keys whose values are al
ready defined elsewhere, such as under multimedia keys or audio control keys.
LockManager.request() - Web APIs
ifavailable optional: if true, the lock request will only be granted if it is not al
ready held.
... signal optional: an abortsignal (the signal property of an abortcontroller); if specified and the abortcontroller is aborted, the lock request is dropped if it was not al
ready granted.
... }); } ifavailable example to grab a lock only if it isn't al
ready being held, use the ifavailable option.
MediaSource.endOfStream() - Web APIs
return value undefined exceptions exception explanation invalidstateerror mediasource.
readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e.
...ew the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.
readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sour...
...cebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.
readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'endofstream()' in that specification.
MediaSource - Web APIs
mediasource.
readystate read only returns an enum representing the state of the current mediasource, whether it is not currently attached to a media element (closed), attached and
ready to receive sourcebuffer objects (open), or attached but the stream has been ended via mediasource.endofstream() (ended.) mediasource.duration gets and sets the duration of the current media being presented.
...r further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.
readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sour...
...cebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.
readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); }; specifications specification status comment media source extensionsthe definition of 'mediasource' in that specification.
Using the MediaStream Recording API - Web APIs
checkbox hack for showing/hiding this is fairly well documented al
ready, but we thought we'd give a mention to the checkbox hack, which abuses the fact that you can click on the <label> of a checkbox to toggle it checked/unchecked.
...this is your entry point into using the mediarecorder api — the stream is now
ready to be captured into a blob, in the default encoding format of your browser.
... lastly, we use the mediarecorder.stop() method to stop the recording when the stop button is pressed, and finalize the blob
ready for use somewhere else in our application.
MediaStream Recording API - Web APIs
the data is delivered by a series of dataavailable events, al
ready in the format you specify when creating the mediarecorder.
... once the source media is playing and you've reached the point where you're
ready to record video, call mediarecorder.start() to begin recording.
... your dataavailable event handler gets called every time there's data
ready for you to do with as you will; the event has a data attribute whose value is a blob that contains the media data.
Transcoding assets for Media Source Extensions - Web APIs
because the audio codec in the mov container is al
ready aac and the video codec is h.264, we can instruct ffmpeg not to perform transcoding.
... fragmenting if you have an asset that is not al
ready an mp4, ffmpeg can handle emitting a properly fragmented mp4 during the transcode process, with the -movflags frag_keyframe+empty_moov command line flag: $ ffmpeg -i trailer_1080p.mov -c:v copy -c:a copy -movflags frag_keyframe+empty_moov bunny_fragmented.mp4 if you al
ready have an mp4, but it's not properly fragmented, you can again use ffmpeg: $ ffmpeg -i non_fragmented.mp4 -movflags frag_ke...
... summary with your video properly encoded and adaptive bitrate media generated, you're now
ready to begin adaptive bitrate streaming on the web using dash and mse.
PaymentRequest.show() - Web APIs
if your architecture doesn't necessarily have all of the data
ready to go at the moment it instantiates the payment interface by calling show(), specify the detailspromise parameter, providing a promise that is fulfilled once the data is
ready.
... exceptions aborterror the returned promise rejects with an aborterror if the user agent is al
ready showing a payment panel.
... invalidstateerror the promise rejects with an invalidstateerror if the same payment has al
ready been shown for this request (its state is interactive because it is being shown al
ready).
Using the Permissions API - Web APIs
depending on the value of the state property of the permissionstatus object returned when the promise resolves, it reacts differently: "granted" the "enable geolocation" button is hidden, as it isn't needed if geolocation is al
ready active.
... "denied" the "enable geolocation" button is revealed (this code needs to be here too, in case the permission state is al
ready set to denied for this origin when the page is first loaded).
... conclusion and future work at the moment this doesn't offer much more than what we had al
ready.
RTCPeerConnection.addTrack() - Web APIs
the specified track doesn't necessarily have to al
ready be part of any of the specified streams.
... exceptions invalidaccesserror the specified track (or all of its underlying streams) is al
ready part of the rtcpeerconnection.
...compatible reusable rtcrtpsender instances meet these criteria: there is no track al
ready associated with the sender.
RTCPeerConnection.setConfiguration() - Web APIs
you cannot change the identity information for a connection once it's al
ready been set.
... invalidmodificationerror the configuration includes changed identity information, but the connection al
ready has identity information specified.
... example in this example, it has al
ready been determined that ice restart is needed, and that negotiation needs to be done using a different ice server.
Storage Access API - Web APIs
the storage access api is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the document.requeststorageaccess() method, and check whether it al
ready has access via the document.hasstorageaccess() method.
...specifics regarding the lifetime of a storage grant and the circumstances under which the browser may decide to inform the user are currently being worked through and will be announced once
ready.
...design properties unique to firefox are summarized here: if the embedded origin tracker.example has al
ready obtained first-party storage access on the top-level origin foo.example, and the user visits a page from foo.example embedding a page from tracker.example again in less than 30 days, the embedded origin will have storage access immediately when loading.
WebGLRenderingContext.makeXRCompatible() - Web APIs
the webglrenderingcontext method makexrcompatible() ensures that the rendering context described by the webglrenderingcontext is
ready to render the scene for the immersive webxr device on which it will be displayed.
... if necessary, the webgl layer may reconfigure the context to be
ready to render to a different device than it originally was.
... return value a promise which successfully resolves once the webgl context is
ready to be used for rendering webxr content.
Using textures in WebGL - Web APIs
// function loadtexture(gl, url) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because images have to be download over the internet // they might take a moment until they are
ready.
... // load texture const texture = loadtexture(gl, 'cubetexture.png'); mapping the texture onto the faces at this point, the texture is loaded and
ready to use.
... once we've set up the texture mapping array, we pass the array into the buffer, so that webgl has that data
ready for its use.
A simple RTCDataChannel sample - Web APIs
they make it very easy to chain the steps of the connection process together; if you haven't al
ready read up on this functionality of ecmascript 2015, you should read up on them.
... when the local peer experiences an open or close event, the handlesendchannelstatuschange() method is called: function handlesendchannelstatuschange(event) { if (sendchannel) { var state = sendchannel.
readystate; if (state === "open") { messageinputbox.disabled = false; messageinputbox.focus(); sendbutton.disabled = false; disconnectbutton.disabled = false; connectbutton.disabled = true; } else { messageinputbox.disabled = true; sendbutton.disabled = true; connectbutton.disabled = false; disconnectbutton.disabled = ...
... our example's remote peer, on the other hand, ignores the status change events, except for logging the event to the console: function handlereceivechannelstatuschange(event) { if (receivechannel) { console.log("receive channel's status has changed to " + receivechannel.
readystate); } } the handlereceivechannelstatuschange() method receives as an input parameter the event which occurred; this will be an rtcdatachannelevent.
Writing WebSocket servers - Web APIs
this article assumes you're al
ready familiar with how http works, and that you have a moderate level of programming experience.
...in many common setups, a reverse proxy has al
ready dealt with them.
... keeping track of clients this doesn't directly relate to the websocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have al
ready completed the handshake.
Inputs and input sources - Web APIs
picking up an object involves first looking to see if the hand represented by dropping any object al
ready being held in the hand represented by avatar.heldobject[hand].
... if an object is al
ready held in that hand, it's dropped by calling the dropobject() function.
...since we're al
ready rendering the scene on a schedule, we can just add the code to apply these changes there, along with preparing and drawing the scene.
Advanced techniques: Creating and sequencing audio - Web APIs
let bandpass = audioctx.createbiquadfilter(); bandpass.type = 'bandpass'; bandpass.frequency.value = bandhz; // connect our graph noise.connect(bandpass).connect(audioctx.destination); noise.start(); } "dial up" — loading a sound sample it's straightforward enough to emulate phone dial (dtmf) sounds, by playing a couple of oscillators together using the methods we've al
ready looked at, however, in this section, we'll load in a sample file instead so we can take a look at what's involved.
...}); when the sample is
ready to play, the program sets up the ui so it is
ready to go.
... we could schedule our voices to play within a for loop, however the biggest problem with this is updating whilst it is playing, and we've al
ready implemented ui controls to do so.
Example and tutorial: Simple synth keyboard - Web APIs
osclist is set up to be
ready to contain a list of all currently-playing oscillators.
... finally, the oscillator list is initialized to ensure that it's
ready to receive information identifiying which oscillators are associated with which keys.
...we look for a data-pressed attribute; if there isn't one (which indicates that the note isn't al
ready playing), we call playtone() to start playing the note, passing in the value of the element's data-frequency attribute.
Background audio processing using AudioWorklet - Web APIs
it also handles creating the audio context if it hasn't al
ready been done.
... in order to ensure the context is usable, this starts by creating the context if it's not al
ready available, then adds the module containing the processor to the worklet.
... you can then create a new audio processor node by simply doing this: let newprocessornode = createmyaudioprocessor(); if the returned value, newprocessornode, is non-null, we have a valid audio context with its hiss processor node in place and
ready to use.
Window: popstate event - Web APIs
note: when writing functions that process popstate event it is important to take into account that properties like window.location will al
ready reflect the state change (if it affected the current url), but document might still not.
... if the goal is to catch the moment when the new document state is al
ready fully in place, a zero-delay settimeout() method call should be used to effectively put its inner callback function that does the processing at the end of the browser event loop: window.onpopstate = () => settimeout(dosomething, 0); when popstate is sent when the transition occurs, either due to the user triggering the browser's "back" button or otherwise, the popstate event is near the end of the process to transition to the new location.
... if new-entry's document is al
ready fully loaded and
ready—that is, its
readystate is complete—and the document is not al
ready visible, it's made visible and the pageshow event is fired at the document with the pagetransitionevent's persisted attribute set to true.
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
exceptions typeerror the provided stream value is not a writablestream, or it is locked to another writer al
ready.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += dec...
WritableStreamDefaultWriter - Web APIs
writablestreamdefaultwriter.
readyread only returns a promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listi...
Synchronous and asynchronous requests - Web APIs
var xhr = new xmlhttprequest(); xhr.open("get", "/bar/foo.txt", true); xhr.onload = function (e) { if (xhr.
readystate === 4) { if (xhr.status === 200) { console.log(xhr.responsetext); } else { console.error(xhr.statustext); } } }; xhr.onerror = function (e) { console.error(xhr.statustext); }; xhr.send(null); line 2 specifies true for its third parameter to indicate that the request should be handled asynchronously.
...this handler looks at the request's
readystate to see if the transaction is complete in line 4; if it is, and the http status is 200, the handler dumps the received content.
...s done by setting the value of the timeout property on the xmlhttprequest object, as shown in the code below: function loadfile(url, timeout, callback) { var args = array.prototype.slice.call(arguments, 3); var xhr = new xmlhttprequest(); xhr.ontimeout = function () { console.error("the request for " + url + " timed out."); }; xhr.onload = function() { if (xhr.
readystate === 4) { if (xhr.status === 200) { callback.apply(xhr, args); } else { console.error(xhr.statustext); } } }; xhr.open("get", url, true); xhr.timeout = timeout; xhr.send(null); } notice the addition of code to handle the "timeout" event by setting the ontimeout handler.
XMLHttpRequest.response - Web APIs
the value is null if the request is not yet complete or was unsuccessful, with the exception that when reading text data using a responsetype of "text" or the empty string (""), the response can contain the response so far while the request is still in the loading
readystate (3).
...it works by creating an xmlhttprequest object and creating a listener for
readystatechange events such that that when
readystate changes to done (4), the response is obtained and passed into the callback function provided to load().
... var url = 'somepage.html'; //a local page function load(url, callback) { var xhr = new xmlhttprequest(); xhr.on
readystatechange = function() { if (xhr.
readystate === 4) { callback(xhr.response); } } xhr.open('get', url, true); xhr.send(''); } specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.send() - Web APIs
exceptions exception description invalidstateerror send() has al
ready been invoked for the request, and/or the request is complete.
...}; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.on
readystatechange = function() { // call a function when the state changes.
... if (this.
readystate === xmlhttprequest.done && this.status === 200) { // request finished.
XRSystem - Web APIs
onsessionstarted(xrsession); }); } else { // shut down the al
ready running xrsession xrsession.end() .then(() => xrsession = null); } } this code starts by checking to see if webxr is available by looking for the navigator.xr property.
... the onbuttonclicked() function checks to see if there's al
ready a session running.
... if, on the other hand, there is al
ready an ongoing xr session, we instead call end() to end the current session.
Using the alert role - Accessibility
if the element was al
ready in the original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title.
...alert.appendchild(myalerttext); document.body.appendchild(myalert); note: the same result can be achieved with less code when using a script library like jquery: $("<p role='alert'>you must agree with our terms of service to create an account.</p>").appendto(document.body); example 3: adding alert role to an existing element sometimes it's useful to add an alert role to an element that is al
ready visible on the page rather than creating a new element.
...the pseudo code snippet below illustrates this approach: <p id="forminstruction">you must select at least 3 options</p> // when the user tries to submit the form with less than 3 checkboxes selected: document.getelementbyid("forminstruction").setattribute("role", "alert"); example 4: making an element with an alert role visible if an element al
ready has role="alert" and is initially hidden using css, making it visible will cause the alert to fire as if it was just added to the page.
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
in these guides, i have al
ready touched on an important feature of grid layout: the support for different writing modes that is built into the specification.
... auto-placement and writing modes in the example al
ready shown, you can see how writing mode changes the direction in which items place themselves onto the grid.
...firefox has al
ready implemented these, so you can try them out right now in firefox.
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
in this guide, i will explain how a grid fits together with other techniques you may al
ready be using.
...the two specifications share some common features, however, and if you have al
ready learned how to use flexbox, the similarities should help you get to grips with grid.
...-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3,1fr); align-items: end; grid-auto-rows: 200px; } .box1 { align-self: stretch; } .box2 { align-self: start; } the fr unit and flex-basis we have al
ready seen how the fr unit works to assign a proportion of available space in the grid container to our grid tracks.
Writing forward-compatible websites - Developer guides
this has happened multiple times to various sites al
ready during the evolution of html5.
...or, conversely, that they don't have support for some other feature (e.g., don't assume that a browser that supports onload on script elements will never support on
readystatechange on them).
...if you have a single code path that works in all the top engines, it means that you are either using features where browser behavior has al
ready converged or, if the behavior hasn't quite converged yet, your code works regardless of which engine's behavior standards turn out to uphold.
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
events event name fired when audioprocess the input buffer of a scriptprocessornode is
ready to be processed.
... emptied the media has become empty; for example, this event is sent if the media has al
ready been loaded (or partially loaded), and the load() method is called to reload it.
... playing playback is
ready to start after having been paused or delayed due to lack of data.
<input type="number"> - HTML: Hypertext Markup Language
validation we have al
ready mentioned a number of validation features of number inputs, but let's review them now: <input type="number"> elements automatically invalidate any entry that isn't a number (or empty, unless required is specified).
... examples we've al
ready covered the fact that by default, the increment is 1, and you can use the step attribute to allow decimal inputs.
...inches">inches:</label> <input id="inches" type="number" name="inches" min="0" max="11" step="1"> <span class="validity"></span> </div> <div> <input type="button" class="meters" value="enter height in feet and inches"> </div> <div> <input type="submit" value="submit form"> </div> </form> you'll see that we are using many of the attributes we've al
ready looked at in the article earlier on.
<video>: The Video Embed element - HTML: Hypertext Markup Language
events event name fired when audioprocess the input buffer of a scriptprocessornode is
ready to be processed.
... emptied the media has become empty; for example, this event is sent if the media has al
ready been loaded (or partially loaded), and the load() method is called to reload it.
... playing playback is
ready to start after having been paused or delayed due to lack of data.
HTTP Index - HTTP
218 100 continue http, informational, status code the http 100 continue informational status response code indicates that everything so far is ok and that the client should continue with the request or ignore it if it is al
ready finished.
... 264 503 service unavailable 503 error, http, server error, status code the hypertext transfer protocol (http) 503 service unavailable server error response code indicates that the server is not
ready to handle the request.
... 272 protocol upgrade mechanism guide, http, http/2, networking, protocols, upgrade, websocket, websockets the http/1.1 protocol provides a special mechanism that can be used to upgrade an al
ready established connection to a different protocol, using the upgrade header field.
HTTP Public Key Pinning (HPKP) - HTTP
when the client visits the server again, it expects at least one certificate in the certificate chain to contain a public key whose fingerprint is al
ready known via hpkp.
...this allows for changing the server's public key without breaking accessibility for clients that have al
ready noted the pins.
... setenv.add-response-header = ( "public-key-pins" => "pin-sha256=\"base64+primary==\"; pin-sha256=\"base64+backup==\"; max-age=5184000; includesubdomains") note: this requires the mod_setenv server.module loaded which can be included by the following if not al
ready loaded.
HTTP response status codes - HTTP
information responses 100 continue this interim response indicates that everything so far is ok and that the client should continue the request, or ignore the response if the request is al
ready finished.
... 208 al
ready reported (webdav) used inside a <dav:propstat> response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
... 503 service unavailable the server is not
ready to handle the request.
Promise.race() - JavaScript
if the iterable contains one or more non-promise value and/or an al
ready settled promise, then promise.race will resolve to the first of these values found in the iterable.
... examples asynchronicity of promise.race this following example demonstrates the asynchronicity of promise.race: // we are passing as argument an array of promises that are al
ready resolved, // to trigger promise.race as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.race(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function(){ console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 33 } an empty iterable causes the returned promise to be forever pending: var foreverpendingpromise = promise...
....race([]); console.log(foreverpendingpromise); settimeout(function(){ console.log('the stack is now empty'); console.log(foreverpendingpromise); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "pending" } if the iterable contains one or more non-promise value and/or an al
ready settled promise, then promise.race will resolve to the first of these values found in the array: var foreverpendingpromise = promise.race([]); var al
readyfulfilledprom = promise.resolve(100); var arr = [foreverpendingpromise, al
readyfulfilledprom, "non-promise value"]; var arr2 = [foreverpendingpromise, "non-promise value", promise.resolve(100)]; var p = promise.race(arr); var p2 = promise.race(arr2); console.log(p); console.log(p2); settimeout(functio...
async function - JavaScript
this runs 2 seconds after 1., immediately after 2., since fast is al
ready resolved } function concurrentpromise() { console.log('==concurrent start with promise.all==') return promise.all([resolveafter2seconds(), resolveafter1second()]).then((messages) => { console.log(messages[0]) // slow console.log(messages[1]) // fast }) } async function parallel() { console.log('==parallel with await promise.all==') // start 2 "jobs" in parallel and wait for b...
...the second timer is not created until the first has al
ready fired, so the code finishes after 3 seconds.
...ows: async function getprocesseddata(url) { let v try { v = await downloaddata(url) } catch(e) { v = await downloadfallbackdata(url) } return processdatainworker(v) } in the above example, notice there is no await statement after the return keyword, although that would be valid too: the return value of an async function is implicitly wrapped in promise.resolve - if it's not al
ready a promise itself (as in this example).
Performance fundamentals - Web Performance
then when the data is needed later, hopefully it's al
ready available and the application doesn't have to wait.
...this in turn means they "start up" faster (since they are al
ready running) and have better upp.
...this waits until the browser is actually
ready to start building the next frame of your animation, and won't bother if the hardware isn't going to actually draw anything.
Add to Home screen - Progressive web apps (PWAs)
how do you make an app a2hs-
ready?
...you could also decide to include different types of icons so devices can use the best one they are able to (e.g., chrome al
ready supports the webp format).
... if the user selects install, the app is installed (available as standalone desktop app), and the install button no longer shows (the onbeforeinstallprompt event no longer fires if the app is al
ready installed).
Mobile first - Progressive web apps (PWAs)
mobile constraints we have al
ready mentioned the fact that mobiles generally have less memory, processing power and bandwidth than other devices (although bear in mind that smart tvs are also generally pretty low powered.) they also have less viewport size available.
...i installed the volo automation tool by running the following on the command line sudo npm install -g volo (you'll also need to get node.js too if you don't al
ready have it) i then created my sample project using volo create myapp mozilla/mortar-app-stub this creates a sample project inside a directory called myapp.
... volo build: builds a minified code version of your app,
ready for production deployment, in a www-built folder.
Using templates and slots - Web Components
al quick example: <template id="my-paragraph"> <p>my paragraph</p> </template> this won't appear in your page until you grab a reference to it with javascript and then append it to the dom, using something like the following: let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; document.body.appendchild(templatecontent); although trivial, you can al
ready start to see how this could be useful.
...however, it is generally more practical to add slots within a <template> element, since you are unlikely to need to define a pattern based on an al
ready-rendered element.
... in addition, even if it is not al
ready rendered, the purpose of the container as a template should be more semantically clear when using the <template>.
Loading Content Scripts - Archive of obsolete content
the constructors for content-script-using objects such as panel and page-mod define a group of options for loading content scripts: contentscript string, array contentscriptfile string, array contentscriptwhen string contentscriptoptions object we have al
ready seen the contentscript option, which enables you to pass in the text of the script itself as a string literal.
... "
ready" loads the scripts after the dom for the page has been loaded: that is, at the point the domcontentloaded event fires.
Communicating using "port" - Archive of obsolete content
here's a simple add-on that sends a message to a content script using port: var tabs = require("sdk/tabs"); var alertcontentscript = "self.port.on('alert', function(message) {" + " window.alert(message);" + "})"; tabs.on("
ready", function(tab) { worker = tab.attach({ contentscript: alertcontentscript }); worker.port.emit("alert", "message from the add-on"); }); tabs.open("http://www.mozilla.org"); in total, the port object defines four functions: emit(): emit a message.
... due to bug 816272 the page-mod's removelistener() function does not prevent the listener from receiving messages that are al
ready queued.
context-menu - Archive of obsolete content
if the item is al
ready contained in another menu or in the top-level context menu, it's automatically removed first.
... if the item is al
ready contained in this menu it will just be moved to the end of the menu.
simple-storage - Archive of obsolete content
for example, this add-on tries to store the urls of pages the user visits: var ss = require("sdk/simple-storage"); ss.storage.pages = []; require("sdk/tabs").on("
ready", function(tab) { ss.storage.pages.push(tab.url); }); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: function() { console.log(ss.storage.pages); } }); but this isn't going to work, because it empties the array each time the add-on runs (for example, each time firefox is started).
... line 2 needs to be made conditional, so the array is only constructed if it does not al
ready exist: if (!ss.storage.pages) ss.storage.pages = []; deleting data you can delete properties using the delete operator.
content/loader - Archive of obsolete content
e/hidden-frame"); var { loader } = require("sdk/content/content"); var pageloader = loader.compose({ constructor: function pageloader(options) { options = options || {}; if (options.contenturl) this.contenturl = options.contenturl; this.on('propertychange', this._onchange = this._onchange.bind(this)); let self = this; hiddenframes.add(hiddenframes.hiddenframe({ on
ready: function on
ready() { let frame = self._frame = this.element; self._emit('propertychange', { contenturl: self.contenturl }); } })); }, _onchange: function _onchange(e) { if ('contenturl' in e) this._frame.setattribute('src', this._contenturl); } }); loader properties contentscriptfile the local file urls of content scripts to load.
...this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "
ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property.
content/symbiont - Archive of obsolete content
this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "
ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this property is optional and defaults to "end".
...this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "
ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property.
jpm - Archive of obsolete content
you can sign an xpi you've al
ready generated by passing the xpi file in the --xpi argument, like this: jpm sign --api-key ${jwt_issuer} --api-secret ${jwt_secret} --xpi <xpi file> alternatively, you can omit the --xpi argument, in which case jpm sign will generate an xpi from the current directory (or --addon-dir).
... your add-on at this exact version number al
ready exists, so it was not signed.
Creating annotations - Archive of obsolete content
updating main.js go back to main.js and add the code to create the selector into the main function: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: '
ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('selector.js')], onattach: function(worker) { worker.postmessage(annotatorison); selectors.push(worker); worker.port.on('show', function(data) { console.log(data); }); worker.on('detach', function () { detachworker(this, selectors); }); } }); make sure the name you use ...
...so edit the message handler assigned to the selector so that on receiving the show message we assign the content of the message to the panel using a new property annotationanchor, and show the panel: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: '
ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('selector.js')], onattach: function(worker) { worker.postmessage(annotatorison); selectors.push(worker); worker.port.on('show', function(data) { annotationeditor.annotationanchor = data; annotationeditor.show(); }); worker.on('detach', function () { detachworker(this, se...
Storing annotations - Archive of obsolete content
var annotationlist = panels.panel({ width: 420, height: 200, contenturl: data.url('list/annotation-list.html'), contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('list/annotation-list.js')], contentscriptwhen: '
ready', onshow: function() { this.postmessage(simplestorage.storage.annotations); }, onmessage: function(message) { require('sdk/tabs').open(message); } }); since this panel's content script uses jquery we will pass that in too: again, make sure the name of it matches the version of jquery you downloaded.
... finally we need to connect this to the widget's right-click message: var widget = widgets.widget({ id: 'toggle-switch', label: 'annotator', contenturl: data.url('widget/pencil-off.png'), contentscriptwhen: '
ready', contentscriptfile: data.url('widget/widget.js') }); widget.port.on('left-click', function() { console.log('activate/deactivate'); widget.contenturl = toggleactivation() ?
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".
... packaging the add-on when you've finished the add-on and are
ready to distribute it, you'll need to package it as an xpi file.
Listen for Page Load - Archive of obsolete content
the following add-on listens to the tab's built-in
ready event and just logs the url of each tab as the user loads it: require("sdk/tabs").on("
ready", logurl); function logurl(tab) { console.log(tab.url); } you will find this console output in the browser console, not the web console.
...the script adds a red border to the tab's document: require("sdk/tabs").on("
ready", runscript); function runscript(tab) { tab.attach({ contentscript: "if (document.body) document.body.style.border = '5px solid red';" }); } (this example is only to show the idea: to implement something like this, you should instead use page-mod, and specify "*" as the match-pattern.) learning more to learn more about working with tabs in the sdk, see the tabs api reference.
Open a Web Page - Archive of obsolete content
the callback is assigned to the on
ready property, and will be passed the tab as an argument: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", on
ready: function on
ready(tab) { console.log(tab.title); } }); even then, you don't get direct access to any content hosted in the tab.
...this add-on loads a page, then attaches a script to the page which adds a red border to it: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", on
ready: runscript }); function runscript(tab) { tab.attach({ contentscript: "document.body.style.border = '5px solid red';" }); } learning more to learn more about working with tabs in the sdk, see the tabs api reference.
Bookmarks - Archive of obsolete content
checking to see if a uri is bookmarked if you want to see if a given uri is al
ready bookmarked -- for example, to avoid creating a new bookmark for a site that's al
ready bookmarked -- you can use the nsinavbookmarksservice.isbookmarked() method.
... var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://mozilla.com/", null, null); if (!bmsvc.isbookmarked(uri)) { bmsvc.insertbookmark(bmsvc.toolbarfolder, uri, bmsvc.default_index, "mozilla"); } this example looks to see if the user al
ready has a bookmark for the mozilla web site, and, if not, creates one, adding it to the user's bookmarks toolbar.
JavaScript Daemons Management - Archive of obsolete content
onstart.call(this.owner, this.index, this.length, this.backw); } this.synchronize(); return true; }; daemon.prototype.stop = function () { this.pause(); if (this.onstop) { this.onstop.call(this.owner, this.index, this.length, this.backw); } delete this.index; delete this.backw; delete this.reversals; }; /******************************* * daemon is now
ready!
...n; } cleartimeout(this.session); this.session = settimeout(daemon.safe.forcecall, this.rate, this); }; daemon.safe.prototype.pause = function () { cleartimeout(this.session); this.paused = true; }; /* system not required daemon.safe instances methods */ /* [inherited from daemon.prototype] */ /**************************************** * the safe-daemon is now
ready!
Toolbar - Archive of obsolete content
adding a toolbar button there are two tutorials available: an elaborate step by step tutorial for beginners: custom toolbar button a tutorial describing the steps needed to add a toolbar button assuming you al
ready have a working extension and know the basics of extension development: creating toolbar buttons adding button by default when you create and deploy your extension and include a toolbar button for it by overlaying the customize toolbarpalette, it is not available by default.
... /** * installs the toolbar button with the given id into the given * toolbar, if it is not al
ready present in the document.
Extension Etiquette - Archive of obsolete content
it assumes that you are al
ready familiar with building an extension.
... theming if you have xul buttons in your extension that do functions similar to ones that al
ready exist in a browser — for example, a feed reader that reloads and stops — use icons from the browser's theme.
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
this.stack = new array(); }, push: function(val) { this.stack.push(number(val)); }, _letfunc: function(func) { a = this.pop(); b = this.pop(); this.push(func(a, b)); }, plus: function() { return this._letfunc(this._plus); }, _plus: function(a, b) { return a + b; }, pop: function() { return this.stack.pop(); } } check for errors now you’re
ready for your first test.
... in initwithpath, the nsilocalfile object gets initialized, and any information al
ready in it gets reset.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
closures will ensure the code is still valid, even if your outer function al
ready returned from execution.
... someexistingobject.someproperty = "abc"; // we al
ready demonstrated with with functions in a previous example alternative: object.defineproperty() for most objects it is possible to (re-)define properties with the object.defineproperty() api, which allows to not override values, but also lets you define getters and setters.
XPCOM Objects - Archive of obsolete content
the getservice and createinstance methods allow you to get the component al
ready set to an interface.
... const cc = components.classes; const ci = components.interfaces; const cr = components.results; const ce = components.exception; you should be familiar with this al
ready, although there are a couple of additions, components.results and components.exception.
Firefox addons developer guide - Archive of obsolete content
there should be some introductory text on the table of contents page at https://developer.mozilla.org/en/firefox_addons_developer_guide obviously there are a number of fixme items in the content that need dealing with, but those are al
ready known.
...there al
ready is a tutorial for beginners: building an extension.
JXON - Archive of obsolete content
if you have al
ready have a dom tree from using xmlhttprequest, skip to the next paragraph.
...ng(omyhtmldoc)): <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>my html document</title> <script type="text/javascript"> alert("welcome!"); </script> <style> p:first-letter { font: italic bold 30px georgia, serif; } </style> </head> <body> <h1>my html document</h1> <p>hello world!!</p> </body> </html> note: as we al
ready said in the note within code considerations, despite the bidirectional conversion between xml and json is lossless regarding the whole content and the structure of an xml document, it is not lossless regarding the ordering of elements, which for some xml dialects (like xhtml) is part of the information.
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
$ export nspr_log_modules=mcd:5 $ export nspr_log_file=/tmp/thunderbird-log.txt when thunderbird has started, you should read: $ cat /tmp/thunderbird-log.txt -1209403040[808a788]: general.config.filename = thunderbird.cfg -1209403040[808a788]: evaluating .cfg file thunderbird.cfg with obscurevalue 0 clean then, to be sure to start with a fresh thunderbird account, don't do this if you al
ready have one and want to preserve your emails and preferences!
...beware that in windows, that file is al
ready there, so it must be saved before being replaced by ours, in order to come back to a normal state in case of problem.
Developing New Mozilla Features - Archive of obsolete content
life will be much easier if your team has one or more members who are al
ready familiar with and to the mozilla world.
... if it is not possible to submit your feature in manageable size patches and you submit a 500k patch, be prepared for several months of review and revision before the patch is
ready to be checked in it may not take this long.
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
if your code cannot find the gre and keeps throwing filenotfoundexceptions during the getgrepathwithproperties(...) call, check whether you al
ready registered the gre on your system: gre registration the initembedding method kicks off the embedding process, allowing the java application to work with xpcom and mozilla.
... another example: (taken from rayh.co.uk) // note, on linux, gtk has to be al
ready initialized for this code to work mozilla moz = mozilla.getinstance(); // now we need to start an xul application, so we get an instance of the xpcom service manager nsiservicemanager servicemanager = moz.getservicemanager(); // now we need to get the @mozilla.org/toolkit/app-startup;1 service: nsiappstartup appstartup = (nsiappstartup)servicemanager.getservicebycontrac...
Layout System Overview - Archive of obsolete content
in the normal in-flow case this is quite natural because the sequential addition of new content results in sequential addition of new frames, and because everything is in-flow, the new frames do not influence the geometry of the frames that have al
ready been formatted.
...sometimes a content element comes in incrementally, and invalidates the formatting of some of the frames that precede it, frame that have al
ready been formatted.
importUserCertificates - Archive of obsolete content
however, if this certificate has the same dn as one or more certificates that al
ready exist in the user's certificate store, the nickname associated with the certificate(s) of the same dn in the certificate store is used, and the <tt>"nicknamestring"</tt> parameter is ignored.
...the private key for the certificates must al
ready reside in the user's personal private key database.
Twitter - Archive of obsolete content
when you call a method that requires authentication -- such as jetpack.lib.twitter.statuses.update() -- without providing a username or password, firefox will prompt the user for them if she is not al
ready authenticated with twitter.
... example usage tweeting jetpack.lib.twitter.statuses.update({ status: "o frabjous day!" }); firefox will prompt for a username and password if the user is not al
ready authenticated with twitter.
Tabs - Archive of obsolete content
blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring on
ready()when the inherited document is fully loaded.
...tp://www.example.com/"); blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring on
ready()when the inherited document is fully loaded.
slideBar - Archive of obsolete content
jetpack.future.import("slidebar"); methods append(iconurihtmlhtml/xmlurluriwidthintpersistboolautoreloadboolonclickfunctiononselectfunctionon
readyfunction)this is a list of options to specify modifications to your slidebar instance.
...iconhref oficon to show in the slidebaruri htmlhtml content for the featurehtml/xml urlurl to load content for the featureuri widthwidth of the content area and the selected slide sizeint persistdefault slide behavior when being selectedbool autoreloadautomatically reload content on selectbool onclickcallback when the icon is clickedfunction onselectcallback when the feature is selectedfunction on
readycallback when featured is loadedfunction an example: jetpack.slidebar.append({ url: "http://mozilla.com", width: 150, onclick: function(slide){ slide.icon.src = "chrome://branding/content/icon48.png"; }}); ...
statusBar - Archive of obsolete content
on
ready (event) occurs when the item was loaded onunload (event) triggers when the item was removed.
... example jetpack.statusbar.append({ html: 'hello <i>world</i>!', on
ready: function(widget){ $(widget).click(function(){ jetpack.tabs.open("http://www.jogkey.de"); }); } }); ...
Running Tamarin acceptance tests - Archive of obsolete content
if you've correctly edited and run the android-vars.sh script mentioned on the tamarin build documentation page you should al
ready be pathed to the adb executable in the public sdk/ndk, but if not it exists at /android-public/android-sdk-mac_86/platform-tools.
...the shell can be named variously in the build but on the phone the executable must be 'avmshell' $ adb shell 'mkdir /data/local/tamarin' $ adb push avmshell /data/local/tamarin/avmshell $ adb shell 'chmod 777 /data/local/tamarin/avmshell' copy android_runner.sh, if it doesn't al
ready exist on the phone in /data/local/tamarin $ adb push tamarin-redux/platform/android/android_runner.sh /data/local/tamarin/android_runner.sh $ adb shell 'chmod 777 /data/loca/android_runner.sh' test it out with a simple .abc or no args for usage (should return exitcode=0) $ tamarin-redux/platform/android/android_shell.py hello.abc hello exitcode=0 test it out by retrieving the version information...
Running Tamarin performance tests - Archive of obsolete content
if you've correctly edited and run the android-vars.sh script mentioned on the tamarin build documentation page you should al
ready be pathed to the adb executable in the public sdk/ndk, but if not it exists at /android-public/android-sdk-mac_86/platform-tools.
...the shell can be named variously in the build but on the phone the executable must be 'avmshell' $ adb push avmshell /data/app/avmshell $ adb shell chmod 777 /data/app/avmshell copy android_runner.sh, if it doesn't al
ready exist on the phone in /data/app $ adb push tamarin-redux/platform/android/android_runner.sh /data/app/android_runner.s $ adb shell chmod 777 /data/app/android_runner.sh test it out with a simple .abc or no args for usage (should return exitcode=0) $ tamarin-redux/platform/android/android_shell.h hello.abc hello exitcode=0 running performance tests to run performance tests on android you don't nee...
URIs and URLs - Archive of obsolete content
it also might be necessary to implement a new urlparser for a new protocol but that might not be necessary because necko al
ready provides uri implementations that can deal with a number of schemes, by implementing the generic urlparser defined in rfc 2396.
...necko will not escape an al
ready escaped character unless forced by a special mask that can be used if it is known that a string is not escaped.
Using cross commit - Archive of obsolete content
getting the script "make -f client.mk pull_all" from a working copy of the trunk now pulls cross-commit, and that'll work on the 1.8 branch soon, too, so you might al
ready have the script.
...ommon ways to use cross-commit: land something simultaneously on the trunk and mozilla_1_8_branch # modify the files (probably by applying the patch) patch -p0 < ~/caret.patch # commit on trunk and branch at once # make sure to use -m "commit message" when doing so tools/cross-commit -m "fix some sort of security bug" layout/base/nscaret.h land something on two other branches that has al
ready landed on the trunk # update to the first branch you want to land on cvs update -rmozilla_1_8_branch layout/base/nscaret.h # modify the files (probably by applying the patch) patch -p0 < ~/caret.patch # commit on all the branches at once # make sure to use -m "commit message" when doing so tools/cross-commit --moz18 --branch mozilla_1_8_0_branch -m "fix some sort of security bug" layout...
Install script template - Archive of obsolete content
* you should not stop the install process because the function failed, * you still have a chance to install the plugin for the al
ready * installed gecko browsers.
... * you should not stop the install process because the function failed, * you still have a chance to install the plugin for the al
ready * installed gecko browsers.
Return Codes - Archive of obsolete content
filename_al
ready_used -226 same filename being used in install install_cancelled -227 raised when installation is cancelled in medias res.
... download_error -228 problem with download script_error -229 error in the script al
ready_exists -230 file al
ready exists locally is_file -231 expected target directoy and got file source_does_not_exist -232 source file/dir not found source_is_directory -233 expected source file and got directory source_is_file -234 expected source directory and got file insufficient_disk_space -235 not enough disk space for install filename_too_long -236 unable_to_locate_lib_function -237 unable_to_load_library ...
Index - Archive of obsolete content
web developers al
ready familiar with dynamic html (dhtml) will learn xul quickly and can start building applications right away.
... 1028 features of a window guide, tutorials, xul, xul tutorial we've al
ready seen some features of windows.
Introduction to XUL - Archive of obsolete content
we intend to provide a subset of cross-platform functionality suitable for building network applications like browsers, leveraging the cross-platform functionality al
ready built into gecko, mozilla's html layout engine.
... "xul" al
ready introduced, is an application of xml used to describe the layout of most windows in the mozilla browser, including and especially the main, browser window.
Introduction - Archive of obsolete content
if the datasource is al
ready loaded and cached, the template builder can begin work right away.
...if the datasource is al
ready loaded, the builder can construct content all in one step, although even this isn't completely true as we'll see later.
Multiple Queries - Archive of obsolete content
how multiple queries are processed we al
ready know that a query generates a set of results.
...that is, the canal.jpg generated by the second query is removed, since an earlier query (the first query) al
ready generated a match for that result.
Static Content - Archive of obsolete content
instead, it looks to see if a menupopup al
ready exists in the location where it would be generated.
...the builder will treat the element as al
ready present as long as some element with the same tag name exists.
The Joy of XUL - Archive of obsolete content
web developers al
ready familiar with dynamic html (dhtml) will learn xul quickly and can start building applications right away.
... fortunately, an implementation of the libical library was al
ready available for macintosh so, with the cross platform nature of xpcom, a macintosh calendar implementation was working within a few days.
Commands - Archive of obsolete content
in addition, text fields and other widgets have a number of commands which they al
ready support that you can invoke.
...you will probably want to use the same id if a command is al
ready being used, however, for your own commands, you can use any command id you wish.
Creating a Skin - Archive of obsolete content
some of the rules conflict with those al
ready in the global stylesheets.
... for example, rules are al
ready defined for buttons and tabs and so on and we defined additional rules for them.
Modifying a XUL Interface - Archive of obsolete content
note that for all these functions, the object referred to by the variable referencechild or the variables newchild and oldchild must al
ready exist or an error occurs.
... likewise the object referred to by the variable child which is to be removed must al
ready exist or an error occurs.
Tree Box Objects - Archive of obsolete content
redrawing the tree we al
ready saw the rowcountchanged() function of the tree box object in the previous section.
... the ensurerowisvisible() function will scroll to a row just as scrolltorow() does, but does not scroll if the row is al
ready visible.
XUL accessibility guidelines - Archive of obsolete content
when creating an extension (for firefox or another xul application), make sure the keyboard shortcuts you assign do not interfere with those al
ready defined by the base application.
... other issues custom widgets avoid re-creating functionality that al
ready exists.
XUL accessibility tool - Archive of obsolete content
be aware that the report might take a little while to be
ready depending on the complexity of the application being analyzed and the speed of your machine.
... future work the following things have been suggested or are planned for a future version of the tool: new tests: (aaronlev) warning: hardcoded color and pixel sizings (aaronlev) error: duplicate accesskey in a dialog (al
ready have this for menus) (aaronlev) error: form control without accesskey (aaronlev) warning: accesskey as lowercase letter with descender (underlined g,j,y,q,p are hard to read, not recommended) (aaronandy) list of things to check manually, such as a list oftrees in the document (make sure they have accessible column picker equivs) or a list of toolbarbuttons (make sure they have accessible alternatives).
XULRunner FAQ - Archive of obsolete content
it is al
ready possible to run firefox on xulrunner now though and certain linux distributions al
ready do this.
...please search to make sure that your bug has not al
ready been reported.
MacFAQ - Archive of obsolete content
here's how to implement command-line trapping when the app is al
ready running, without getting into appleevents or c++ code.
... taking advantage of the core code "openurl" from "nscommandlineservicemac.cpp", you'll see that it looks for "browser.chromeurl" before defaulting to navigator.xul, and this is called when an xulrunner app is al
ready running, so: create a default preference of "browser.chromeurl" that points to your new "hiddenwindow" as such: "chrome://myxul/content/hiddenwindow.xul" next take the code below and drop it in, to create the hiddenwindow.xul (note: the debug function and nsicommandline try/catch can be removed, all you need is the window.arguments[0]) <?xml version="1.0"?> <window xmlns="http://www.mozilla.org/keymaster/g...
2006-10-06 - Archive of obsolete content
ffx 2 rc2 testing today l10n builds were completed was completed and
ready for test.
... calendar localization update rc1 for sunbird 0.3 is out now and
ready for testing.
NPN_GetURL - Archive of obsolete content
the default is _self, if the plug-in instance's document is al
ready at the top.
...if target is null, the application creates a new stream and delivers the data to the plug-in instance, through calls to npp_newstream(), npp_write
ready() and npp_write(), and npp_destroystream().
NPAPI plugin reference - Archive of obsolete content
this initiates a read operation; the actual data is received through subsequent calls to npp_write
ready() and npp_write().
...(remark: hence the name "npp_write" is misleading - just think of:"data_arrived") npp_write
ready determines maximum number of bytes that the plug-in can consume.
Introduction to Public-Key Cryptography - Archive of obsolete content
figure 4 assumes the following: the user has al
ready decided to trust the server, either without authentication or on the basis of server authentication via ssl.
... like figure 4, figure 5 assumes that the user has al
ready decided to trust the server and has requested a resource, and that the server has requested client authentication in the process of evaluating whether to grant access to the requested resource.
Writing JavaScript for XHTML - Archive of obsolete content
this will ensure that documents in html will compare correctly and will do no harm in xhtml where the names are al
ready lower case.
... we found out al
ready, that the document object in xml files is different from the ones in html files.
Building Mozilla XForms - Archive of obsolete content
firefox 3.5 and up: get the source code if you want to build xforms for firefox up to 3.0, you al
ready have the required source code, it's part of your cvs checkout.
...$topsrcdir/browser/config/mozconfig mk_add_options moz_co_project=browser mk_add_options moz_objdir=@topsrcdir@/obj-@config_guess@ ac_add_options --enable-extensions="default,xforms" ac_add_options --enable-debug ac_add_options --disable-optimize ac_add_options --disable-tests building now that you have everything
ready, you can rebuild mozilla with the same command you used before to build firefox without xforms.
Implementation Status - Archive of obsolete content
278448; 338146; 4.2 initialization events supported 4.2.1 xforms-model-construct supported 4.2.2 xforms-model-construct-done supported 4.2.3 xforms-
ready supported 4.2.4 xforms-model-destruct supported 4.3.1 xforms-rebuild supported 4.3.2 xforms-recalculate supported 4.3.3 xforms-revalidate supported 4.3.4 xforms-refresh supp...
...xpath expressions in xforms section title status notes bugs 7.1 xpath datatypes supported 7.2 evaluation context partial 7.3 references, dependencies, and dynamic dependencies partial we probably al
ready do most of it due to our 1.0 work, but we haven't verified we meet the 1.1 standards, yet 7.4 expression categories supported 7.4.2 model binding expressions and computed expressions supported 7.4.3 expressions in actions and submissions partial ...
Anatomy of a video game - Game development
before we discuss ways to change it, let us discuss what it al
ready does well.
... sleep (unless an event interrupts the browser's nap) until the monitor is
ready for your image (vsync) and repeat.
WebVR — Virtual Reality for the Web - Game development
vr devices with the popularity of oculus rift and a lot of other devices in production coming soon to the market, the future looks bright — we al
ready have sufficient technology to make the vr experience "good enough" for playing games.
... the future of webvr it's happening — consumer devices are reaching the market right now, and we al
ready have javascript apis to support them on the web.
Audio for Web games - Game development
the advantage is that we can prime one piece of audio and have our sprites
ready to go.
...loading synchronously might mean parts of your music are
ready earlier and you can start playing them while others load.
Implementing controls using the Gamepad API - Game development
api status and browser support the gamepad api is still at the working draft stage in the w3c process, which means its implementation might still change, but saying that the browser support is al
ready quite good.
... if(gamepadapi.buttonsstatus[i] == button) { // set the boolean variable to true newpress = true; // if we want to check the single press if(!hold) { // loop through the cached states from the previous frame for(var j=0,p=gamepadapi.buttonscache.length; j<p; j++) { // if the button was al
ready pressed, ignore new press if(gamepadapi.buttonscache[j] == button) { newpress = false; } } } } } return newpress; }, there are two types of action to consider for a button: a single press and a hold.
asm.js - Game development
this subset of javascript is al
ready highly optimized in many javascript engines using fancy just-in-time (jit) compiling techniques.
... using a subset of javascript asm.js is al
ready supported by major web browsers.
Collision detection - Game development
we have the bricks appearing on the screen al
ready, but the game still isn't that interesting as the ball goes through them.
...we have to figure out a way to get rid of the ones we've al
ready hit with the ball.
Initialize the framework - Game development
the id of the <canvas> to use for rendering if one al
ready exists on the page (we've specified null because we want phaser to create its own.) the names to use for phaser's three key functions that load and start the game, and update the game loop on every frame; we will use the same names to keep it clean.
... preload takes care of preloading the assets create is executed once when everything is loaded and
ready update is executed on every frame.
2D breakout game using Phaser - Game development
to get the most out of this series of articles you should al
ready have basic to intermediate javascript knowledge.
...if you are not al
ready familiar with pure javascript game development, we would suggest that you first work through this series' counterpart, 2d breakout game using pure javascript.
2D maze game with device orientation - Game development
the create function holds some basic configuration: we're setting up the scaling and alignment of the canvas, and moving on to the preload state when everything's
ready.
... controlling the ball it’s cool to have the ball
ready to be thrown around in the play area, but it’s also important to be able to actually move it!
Visual typescript game engine - Game development
al
ready implemented: -video chat webrtc (sip) chat and data communication.
... -run services database server (locally and leave it alive to develop process): npm run dataserver looks like this : mongod --dbpath ./server/database/data fix: "failed: address al
ready in use" : netstat -ano | findstr :27017 taskkill /pid typeyourpidhere /f also important "run visual studio code as administrator".
Gecko FAQ - Gecko Redirect 1
hich is only used in hebrew and arabic (ibm has begun work to add bidi support in a future release) style sheets css 1 - full support, except for: the application of styles to html column elements the ability to turn off author styles the names of certain mozilla extension pseudo-classes lack the moz- prefix css 2 - partial support is expected and has al
ready been built into gecko, including support for css2 positioning, but no commitment has been made to achieve a specific level of support dom level 0 level 1 core: full support making entityreferences available through dom1; per a provision of the dom1 spec for xml implementations, entities will be automatically expanded inline and therefore not available through dom1; our im...
...plementation extrapolates this provision to apply to entityreferences as well for more information, see the dom in mozilla level 1 html dom 2 - most of it has al
ready been implemented in gecko, including support for dom 2 events, the dom 2 style, and the dom2 core.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
// example 1 // only y is hoisted x = 1; // initialize x, and if not al
ready declared, declare it - but no hoisting as there is no var in the statement.
... console.log(x + " " + y); // '1 undefined' // this prints value of y as undefined as javascript only hoists declarations var y = 2; // declare and initialize y // example 2 // no hoisting, but since initialization also causes declaration (if not al
ready declared), variables are available.
A cool-looking box - Learn web development
prerequisites: before attempting this assessment, you should have al
ready worked through all the articles in this module.
... details of what you have al
ready tried, and what you would like us to do, e.g.
Handling different text directions - Learn web development
writing modes and block and inline layout we have al
ready discussed block and inline layout, and the fact that some things display as block elements and others as inline elements.
... logical properties and values the reason to talk about writing modes and direction at this point in your learning however, is because of the fact we have al
ready looked at a lot of properties which are tied to the physical dimensions of the screen, and make most sense when in a horizontal writing mode.
Organizing your CSS - Learn web development
if spaces, how many spaces?) having a set of rules you always follow reduces the amount of mental overhead needed when writing css, as some of the decisions are al
ready made.
... css methodologies instead of needing to come up with your own rules for writing css, you may benefit from adopting one of the approaches al
ready designed by the community and tested across many projects.
The box model - Learn web development
margins, padding, and borders you've al
ready seen the margin, padding, and border properties at work in the example above.
... an element with display: inline-block does a subset of the block things we al
ready know about: the width and height properties are respected.
Responsive design - Learn web development
the first was the idea of fluid grids, something which was al
ready being explored by gillenwater, and can be read up on in marcotte's article, fluid grids (published in 2009 on a list apart).
...the media queries level 3 specification became a candidate recommendation in 2009, meaning that it was deemed
ready for implementation in browsers.
Getting started with CSS - Learn web development
styling html elements by making our heading red we have al
ready demonstrated that we can target and style an html element.
...however you now al
ready know enough to style text, apply css based on different ways of targeting elements in the document, and look up properties and values in the mdn documentation.
Styling links - Learn web development
visited: a link when it has al
ready been visited (exists in the browser's history), styled using the :visited pseudo class.
... you've reached the end of this article, and al
ready did some skill testing in our active learning sections, but can you remember the most important information going forward?
How does the Internet work? - Learn web development
well, there are al
ready cables linked to your house, for example, electric power and telephone.
... the telephone infrastructure al
ready connects your house with anyone in the world so it is the perfect wire we need.
Sending forms through JavaScript - Learn web development
= { dom : document.getelementbyid( "thefile" ), binary : null }; // use the filereader api to access file content const reader = new filereader(); // because filereader is asynchronous, store its // result when it finishes to read the file reader.addeventlistener( "load", function () { file.binary = reader.result; } ); // at page load, if a file is al
ready selected, read it.
... file.dom.addeventlistener( "change", function () { if( reader.
readystate === filereader.loading ) { reader.abort(); } reader.readasbinarystring( file.dom.files[0] ); } ); // senddata is our main function function senddata() { // if there is a selected file, wait it is read // if there is not, delay the execution of the function if( !file.binary && file.dom.files.length > 0 ) { settimeout( senddata, 10 ); return; } // to construct our multipart form data request, // we need an xmlhttprequest instance const xhr = new xmlhttprequest(); // we need a separator to define each part of the req...
UI pseudo-classes - Learn web development
ntent: " "; width: 10px; height: 10px; border-radius: 6px; background-color: red; font-size: 1.2em; transform: translate(3px, 3px) scale(0); transform-origin: center; transition: all 0.3s ease-in; } input[type="radio"]:checked::before { transform: translate(3px, 3px) scale(1); transition: all 0.3s cubic-bezier(0.25, 0.25, 0.56, 2); } this is really useful — screenreaders al
ready let their users know when a radio button or checkbox they encounter is checked/selected, so you don't want them to read out another dom element that indicates selection — that could be confusing.
... note: we've used ::before to add these labels, as we were al
ready using ::after for the "required" labels.
Add a hitmap on top of an image - Learn web development
prerequisites: you should al
ready know how to create a basic html document and how to add accessible images to a webpage.
... you may write alt="" if the href attribute is blank and the entire image al
ready has an alt attribute.
Marking up a letter - Learn web development
prerequisites: before attempting this assessment you should have al
ready worked through getting started with html, what's in the head?
... details of what you have al
ready tried, and what you would like us to do (if you are stuck and need help, or if you want an assessment).
Test your skills: HTML images - Learn web development
html images 2 in this task you al
ready have a full-featured image, but we'd like you to add a tooltip that appears when the image is moused over.
... details of what you have al
ready tried, and what you would like us to do, e.g.
Responsive images - Learn web development
prerequisites: you should al
ready know the basics of html and how to add static images to a web page.
...by then, the original image would al
ready have been loaded, and you would load the small image as well, which is even worse in responsive image terms.
Video and audio content - Learn web development
ovps even usually offer
ready-made code for embedding video/audio in your webpages; if you use that route, you can avoid some of the difficulties we discuss in this article.
... the embedded video will look something like this: you can try the example live here (see also the source code.) using multiple source formats to improve compatibility there's a problem with the above example, which you may have noticed al
ready if you've tried to access the live link above with an older browser like internet explorer or even an older version of safari.
HTML table basics - Learn web development
place the four cells you've al
ready created inside <tr> tags, like so: <tr> <td>hi, i'm your first cell.</td> <td>i'm your second cell.</td> <td>i'm your third cell.</td> <td>i'm your fourth cell.</td> </tr> now you've made one row, have a go at making one or two more — each row needs to be wrapped in an additional <tr> element, with each cell contained in a <td>.
... we have al
ready partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better.
Introduction to events - Learn web development
you've al
ready seen events and event handlers used in many of the examples, but let's recap just to cement our knowledge.
...it's just a copy of the simple random color example we've played with al
ready.
Manipulating documents - Learn web development
the input should be emptied and focused
ready for you to enter another item.
... finally, use the focus() method to focus the input element
ready for entering the next shopping list item.
Silly story generator - Learn web development
prerequisites: before attempting this assessment you should have al
ready worked through all the articles in this module.
... details of what you have al
ready tried, and what you would like us to do, e.g.
Test your skills: Math - Learn web development
math 2 in the second task you are al
ready provided with two calculations, with the results stored in the variables result and result2.
... details of what you have al
ready tried, and what you would like us to do, e.g.
Test your skills: Strings - Learn web development
you al
ready have half of a famous quote inside a variable called quotestart; we would like you to: look up the other half of the quote, and add it to the example inside a variable called quoteend.
... details of what you have al
ready tried, and what you would like us to do, e.g.
What is JavaScript? - Learn web development
apis are
ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement.
... they do the same thing for programming that
ready-made furniture kits do for home building — it is much easier to take
ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and then put them together to make a bookshelf.
Aprender y obtener ayuda - Learn web development
using mdn the site you are al
ready on has a wealth of information available to you — both reference material for looking up code syntax, and guides/tutorials for learning techniques.
... other online resources we al
ready mentioned stack overflow, but there are other online resources that can help.
Learning area release notes - Learn web development
learn why frameworks exist, when you should use one (and when you shouldn't), what kinds of features are common to all frameworks, and how they relate to the vanilla javascript you may al
ready know.
...this is in addition to the longer assessment articles that you'll find in some of the learning modules al
ready.
Server-side web frameworks - Learn web development
if you are part of a development team that al
ready has significant experience with a particular web framework or programming language, then it makes sense to stick with that.
...frameworks that include everything are often easier to get started with because you al
ready have everything you need, and the chances are that it is well integrated and well documented.
Routing in Ember - Learn web development
at the moment, we al
ready have the "all" page, as we are currently not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "active" and "completed" todos.
...it al
ready contains a getter that returns all todos, and a getter that returns incomplete todos.
Introduction to client-side frameworks - Learn web development
by this point, it had al
ready been using react to solve many of its problems internally.
...there are a number of advantages of this approach, mostly around performance (your user's device isn’t building the page with javascript; it's al
ready complete) and security (static pages have fewer attack vectors).
Componentizing our React app - Learn web development
let's try the following instead of what we have al
ready: const tasklist = props.tasks.map(task => <todo />); look again at your app; now our tasks look more like they used to, but they’re missing the names of the tasks themselves.
...p stack-exception"> <filterbutton /> <filterbutton /> <filterbutton /> </div> <h2 id="list-heading">3 tasks remaining</h2> <ul role="list" classname="todo-list stack-large stack-exception" aria-labelledby="list-heading" > {tasklist} </ul> </div> ); } export default app; with this in place, we’re almost
ready to tackle some interactivity in our react app!
React interactivity: Events and state - Learn web development
there are a couple of other things to note: the camel-cased nature of onclick is important — jsx will not recognize onclick (again, it is al
ready used in javascript for a specific purpose, which is related but different — standard onclick handler properties).
...o-input" classname="input input__lg" name="text" autocomplete="off" value={name} onchange={handlechange} /> <button type="submit" classname="btn btn__primary btn__lg"> add </button> </form> ); } export default form; putting it all together: adding a task now that we've practiced with events, callback props, and hooks we're
ready to write functionality that will allow a user to add a new task from their browser.
Focus management with Vue refs - Learn web development
you don't have to use $nexttick here because the component has al
ready been added to the dom when mounted() is called.
... we're al
ready tracking the number of elements in our list heading — the <h2> in app.vue — and it's associated with our list of to-do items.
Rendering a list of Vue components - Learn web development
previous overview: client-side javascript frameworks next at this point we've got a fully working component; we're now
ready to add multiple todoitem components to our app.
...while this isn't strictly necessary, it makes it easier for us to manage since we al
ready need to create a unique id for each todo item anyway.
Implementing feature detection - Learn web development
javascript we al
ready saw an example of a javascript feature detection test earlier on.
... when you are using modernizr in production, you can go to the download page you've al
ready visited and click the plus buttons for only the features you need feature detects for.
Setting up your own test automation environment - Learn web development
to do this, you need to: install the node sauce labs wrapper using the following command (if you've not al
ready done it for this project): npm install saucelabs --save-dev require saucelabs — put this at the top of your sauce_google_test.js file, just below the previous variable declarations: const saucelabs = require('saucelabs'); create a new instance of saucelabs, by adding the following just below that: let saucelabs = new saucelabs({ username : "your-user-name", password : "your-...
...if you've not al
ready added the location to your path, do so now (see the setting up selenium in node section).
Learn web development
beyond the basics: if you have a bit of knowledge al
ready, the next step is to learn html and css in detail: start with our introduction to html module and move on to our css first steps module.
... moving onto scripting: if you are comfortable with html and css al
ready, or you are mainly interested in coding, you'll want to move on to javascript or server-side development.
Accessibility Features in Firefox
have announced they are al
ready working with the technology their new richer interfaces accessible with this new technology.
...thanks to sun's efforts we al
ready have excellent support for the gnome onscreen keyboard (gok).
CSUN Firefox Materials
have announced they are al
ready working with the technology their new richer interfaces accessible with this new technology.
...thanks to sun's efforts we al
ready have excellent support for the gok onscreen keyboard.
Embedding API for Accessibility
mozilla al
ready supports some of these options.
... this document lays out what we al
ready have, and what we'll need later, in the embedding api to support accessibility.
Gecko info for Windows accessibility vendors
once the new page is
ready to be displayed and traversed via its iaccessible tree, the old content window is destroyed, and a new window is created.
...if placetopleft is false, the document will only be scrolled if the element is not al
ready visible, or the document will be scrolled the minimum amount to make the element visible anywhere within the current window.
Adding a new word to the en-US dictionary
the process is pretty straight-forward: get a clone of uxp, if you don't al
ready have one, and make sure you can build it successfully.
...the script only works if you have the environment variable editor set to the executable of an editor program; if you don't have it set, you can do editor=vim sh edit-dictionary to edit using vim (or you can substitute some other editor), or you can just do sh edit-dictionary if you have an editor al
ready specified.
Application cache implementation overview
processnexturi then invokes it self asynchronously via dispatch to a main thread when not al
ready on the concurrency limit of 15 loads.
... when the manifest is identical, the cache is activated, onupdate
ready event is invoked and the update 'finishes'.
Testopia
despite bugzilla 5.0 has al
ready been released a few months ago, we don't plan to release a fix for testopia immediately, because it's currently under heavy work to make testopia a fully self-contained extension, which means that all tr_*.cgi scripts which are currently in the bugzilla/ root directory are being moved into extensions/testopia/lib/.
... the good news is that the current code in the git repository al
ready works with bugzilla 5.0, and so if you upgraded to 5.0 al
ready, and if you don't mind having a work-in-progress extension on your machine, you can decide to pull the code from the git repository.
Creating a Language Pack
$ make langpack-x-testing locale_mergedir=$(pwd)/mergedir now go to the dist directory to find your langpack
ready to use!
... mv -f "../../dist/l10n-stage/firefox-3.6b5pre.x-testing.mac.dmg" "../../dist/firefox-3.6b5pre.x-testing.mac.dmg" repackaging done now go to the dist directory to find your repackaged binary
ready to be installed!
Creating a spell check dictionary add-on
if you are creating a new dictionary, as opposed to updating an existing one, please make sure that there is not al
ready a dictionary available for your locale.
... if there al
ready is one, try contacting the author to get it updated, or contact amo editors if the author does not respond.
Creating reftest-based unit tests
step 3 create a file named foo.html with the following: <html><head><title>reftest0001</title> <body><strong>hello!</strong></body> </html> step 4 create a file named bar.html with the following: <html><head><title>reftest0001</title> <body><b>hello!</b></body> </html> step 5 create a file named reftest.list with the following: == foo.html bar.html you are now
ready to run the test (but first you must go back to the root of firefox's source code tree): $ ./mach reftest path/to/reftest.list 2>&1 | grep reftest reftest pass: file:///users/ray/mozilla-central/path/to/foo.html $ congratulations!
...third, you need to remove 'reftest-wait' from the root element's 'class' attribute to tell the reftest framework that the test is now
ready to have its rendering tested.
Capturing a minidump
if firefox is not al
ready running, then open windbg from the start menu (start->all programs->debugging tools for windows->windbg).
... if firefox is al
ready running, open windbg from the start menu (start->all programs->debugging tools for windows->windbg).
Debugging Table Reflow
leaving assignnonpctcolwidths shows that al
ready to all columns a width of 360 twips has been assigned assignnonpctcolwidths ex ***start table dump*** mcolwidths=360 360 360 360 col frame cache -> 0=00b93138 1=00b931f0 2=024dd728 3=024dd780 **start col dump** colindex=0 isanonymous=0 constraint=0 widths=360 540 1230 -1 -1 -1 -1 -1 -1 360 **end col dump** **start col dump** colindex=1 isanonymous=0 constraint=0 widths=360 540 -1 -1 -1 ...
...-1 -1 -1 -1 360 **end col dump** **start col dump** colindex=2 isanonymous=0 constraint=3 widths=360 540 -1 -1 -1 -1 -1 -1 540 360 **end col dump** **start col dump** colindex=3 isanonymous=0 constraint=0 widths=360 540 -1 -1 -1 -1 -1 -1 -1 360 **end col dump** ***end table dump*** the first column has al
ready the minimum content width, the table column can't shrink below that, the desired content width of 540 twips, that's the space to layout cell 1 without wrapping the text and the 1230 which correspond to the style="width:80px" at the first cell.
Debugging on Mac OS X
# therefore setting `settings set target.load-cwd-lldbinit true` can't help us # without xcode providing that functionality.) # # the following works by setting a one-shot breakpoint to break on a function # that we know will both run early (which we want when we start first start the # app) and run frequently (which we want so that it will trigger asap if we # attach to an al
ready running app).
... now you're
ready to start debugging: from the "product" menu, ensure the scheme you created above is selected under "scheme" click the "run" button.
HTTP logging
windows if firefox is al
ready running, exit out of it.
... here is an example for the windows platform, on other platforms we accept the same form of the arguments: if firefox is al
ready running, exit out of it.
Working with Mozilla source code
getting a pre-configured mozilla build system virtual machine this is the easiest way to get started: use a virtualbox virtual machine which is al
ready configured with a complete build environment for you to use.
... getting commit access to the source code feel
ready to join the few, the proud, the committers?
Multiple Firefox profiles
from profile manager inside firefox if you al
ready have firefox instance running, you can open another profile from the integrated profile manager on any platform: type about:profiles into the browser url search bar.
... linux if firefox is al
ready included in your linux distribution, or if you have installed firefox with the package manager of your linux distribution: open a terminal emulator or your shell’s command prompt: alt-f2 if you use gnome shell or kde plasma, consult your desktop environment documentation for other environments.
Cross Process Object Wrappers
but if the chrome process then tries to use a cpow, the chrome process will block until the content process is
ready to respond.
... suddenly, what looked like a simple property access could block the ui for a noticeable amount of time: there is one scenario, though, in which this is not a problem: when the content process is al
ready blocking on a synchronous message it sent to the chrome process.
Storage access policy: Block cookies from trackers
the above heuristics will also serve to extend the lifetime of a third-party storage permission on origins that have al
ready been granted access.
... if the preference al
ready exists, edit the preference value.
Gecko Keypress Event
xul application developers should use key elements for handling accel keys, so as to make use of the handling logic al
ready provided for these elements.
...it is better to use the logic al
ready in nscontentutils::getaccelkeycandidates() for accel key handling, and nscontentutils::getaccesskeycandidates() for access key handling (see nscontentutils.h and nscontentutils.cpp).
How to get a stacktrace with WinDbg
debugging to begin debugging, ensure that firefox is not al
ready running and open windbg from the start menu.
... .logopen /t c:\temp\firefox-debug.log .childdbg 1 .tlist sxn gp lm if you see firefox.exe listed in the output from .tlist more than once, then you are al
ready running the application and need to close the running instance first before you start debugging, otherwise you won't get useful results.
IME handling guide
eselectedrawclause converted clause by ime selection_ime_convertedtext eimeconvertedclause econvertedclause selected clause by the user or ime and also converted by ime selection_ime_selectedconvertedtext eimeselectedclause eselectedclause note that typically, "selected clause of raw text typed by the user" isn't used because when composition string is al
ready separated to multiple clauses, that means that the composition string has al
ready been converted by ime at least once.
...if all sent widgetcompositionevents and widgetselectionevents are al
ready handled in the remote process, contentcacheinparent sending the notifications to widget.
Implementing QueryInterface
calling an inherited queryinterface sometimes you are just adding one or two new interfaces to an implementation that al
ready supports many other interfaces.
... this technique works because nsbaseimplementation is al
ready a complete class that could have been used on its own.
JavaScript-DOM Prototypes in Mozilla
this means that the next time the name of a class constructor is resolved in the same scope, say htmlanchorelement, the code will resolve the name htmlanchorelement, find the parent name, which is htmlelement, and resolve that, but since we've al
ready resolved htmlelement as a result of resolving the name htmlimageelement earlier, the recursion will stop right there.
...obj.__proto__.__proto__) has been set up al
ready, if it has, then there's nothing left to do in nsdomclassinfo::postcreate().
Add-on Repository
results passed to the searchcallback object only include add-ons that are compatible with the current application and are not al
ready installed or in the process of being installed.
...a new search will immediately fail if the addonrepository is al
ready handling another search request.
DownloadList
if the download was al
ready removed, this method has no effect.
...the newly added view will receive ondownloadadded notifications for all the downloads that are al
ready in the list.
Using JavaScript code modules
if you're writing an extension for firefox 4 and al
ready have a chrome.manifest with a content instruction in it, you can put the code module in your content folder and reference it like your other content files via chrome://<yourextension>/content/<yourmodule>.jsm.
...for example: // import services.jsm unless in a scope where it's al
ready been imported components.utils.import("resource://gre/modules/services.jsm"); var resprot = services.io.getprotocolhandler("resource") .queryinterface(components.interfaces.nsiresprotocolhandler); var aliasfile = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); aliasfile.initwithpath("/some/absol...
Bootstrapping a new locale
this is why you need to do hg push, which sends the al
ready made commits to the remote repository (http://bitbucket.org/mozillal10n/ab-cd/ in the example above).
... after you have committed and pushed your initial translation, email the l10n-drivers team to let us know it's
ready.
Localizing without a specialized tool
with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is
ready for installation.
...you are now
ready to start translating!
QA phase
enter the following command to perform the configuration: $ ./mach configure once your command-line finishes spitting out the config command's output, navigate to the newly created directory: $ cd ../firefox-build/browser/locales now you're
ready to build!
... now you're
ready to proceed to the release phase!
Localization sign-off reviews
overview you've done some localization work and are
ready for it to be released.
...so before you request your sign-off review, be sure that it is as
ready as it can be.
Fonts for Mozilla 2.0's MathML engine
on mac os x lion (10.7) and higher versions, stix fonts are al
ready installed and can be used for mathml.
...all the fonts mentioned above may al
ready be installed by default on your system or can easily be installed via your software manager.
Mozilla Style System Documentation
for frames: const nsstyledisplay *display; ::getstyledata(frame, &display); or for style contexts: const nsstyledisplay *display; ::getstyledata(sc, &display); these functions cause an appropriate struct to be computed if it hasn't been computed al
ready and then fill in the struct pointer.
...it uses the appropriate declaration struct and has each rule fill in any properties specified by that rule that are not filled in al
ready.
Profiling with Xperf
it might al
ready be installed by the windows sdk.
... check if c:\program files\microsoft windows performance toolkit al
ready exists.
McCoy
https://fireclipse.svn.sourceforge.net/svnroot/fireclipse/trunk/fireclipseextensions/chromebug/mccoy/signontheline/ bug 396525 - patch to mccoy https://bugzilla.mozilla.org/show_bug.cgi?id=396525 signing update manifests before you release your add-on in order to verify the update manifests applications need to al
ready have information from you for how to verify it.
... releasing an update once you are
ready to release an updated version of your add-on you must create yourself an update.rdf file.
Creating a Cookie Log
linux start a command shell (these instructions are for bash, if you use something else, you probably know how to modify these instructions al
ready).
... run firefox by typing "./firefox" and pressing enter mac os x open terminal.app, which is located in the /applications/utilities folder (these instructions are for bash, the default shell in mac os x 10.3 and higher; if you use something else, you probably know how to modify these instructions al
ready).
PR_Initialized
syntax #include <prinit.h> prbool pr_initialized(void); returns the function returns one of the following values: if pr_init has al
ready been called, pr_true.
... if pr_init has not al
ready been called, pr_false.
PR_NotifyAll
promotes all threads waiting on a specified monitor to a
ready state.
... description a call to pr_notifyall causes all of the threads waiting on the monitor to be scheduled to be promoted to a
ready state.
PR_Sleep
if you have al
ready created such structures, it is more efficient to use them directly.
... calling pr_sleep with the value of ticks set to pr_interval_no_wait simply surrenders the processor to
ready threads of the same priority.
An overview of NSS Internals
a trust anchor is just another x.509 certificate that is al
ready known and has been deliberately marked as trusted by a software vendor, administrators inside an organizational infrastructure, or the software user.
...when using an ssl network connection, you'll al
ready have two layers, the basic nspr layer and an ssl library layer.
FIPS Mode - an explanation
(note: mozilla does not distribute a "fips mode"-
ready nss with firefox.) this page attempts to provide an informal explanation of what it is, who would use it, and why.
...some third-parties distribute firefox
ready for fips mode, a partial list can be found at the nss wiki.
HTTP delegation
instead, the parameters are a server session object (that carries host and port information al
ready) and the request path.
...(when issueing get requests, the "?query-string=data" portion should al
ready be appended to the request path) after creation, nss might call functions to provide additional details of the http request (e.g.
HTTP delegation
instead, the parameters are a server session object (that carries host and port information al
ready) and the request path.
...(when issuing get requests, the "?query-string=data" portion should al
ready be appended to the request path) after creation, nss might call functions to provide additional details of the http request (e.g.
Encrypt Decrypt_MAC_Using Token
strcpy(headerfilename, infilename); strcat(headerfilename, ".header"); /* for intermediate encrypted file, choose filename as inputfile name with extension ".enc" */ strcpy(encryptedfilename, infilename); strcat(encryptedfilename, ".enc"); pr_init(pr_user_thread, pr_priority_normal, 0); switch (cmd) { case encrypt: /* if the intermediate header file al
ready exists, delete it.
... */ if (pr_access(headerfilename, pr_access_exists) == pr_success) { pr_delete(headerfilename); } /* if the intermediate encrypted al
ready exists, delete it.
NSS Sample Code Sample1
rappedenckey) secitem_freeitem(mwrappedenckey, pr_true); if (mwrappedmackey) secitem_freeitem(mwrappedmackey, pr_true); if (menckey) pk11_freesymkey(menckey); if (mmackey) pk11_freesymkey(mmackey); } int server::init() { int rv = 0; seckeyprivatekey *prvkey = 0; seckeypublickey *pubkey = 0; pk11slotinfo *slot = 0; pk11rsagenparams rsaparams; secstatus s; // see if there is al
ready a private key with this name.
... rv = server1->generatekeys(); if (rv) { cout << "generatekeys failed" << endl; goto done; } // now that everything is
ready, start server1.
NSS Sample Code sample6
should succeed on first run on a fresh db, * should fail on successive runs because key with that id al
ready exists */ genkey(1); /* generate a key with id 2.
... should succeed on first run on a fresh db, * should fail on successive runs because key with that id al
ready exists */ genkey(2); /* generate a key with id 1 - this will fail because key with that id * al
ready exists */ genkey(1); } void genkey(int id) { pk11slotinfo* slot = null; pk11symkey* key = null; secitem keyiditem; int keyid[1]; ck_mechanism_type ciphermech; /* using ckm_aes_cbc_pad mechanism for example */ ciphermech = ckm_aes_cbc_pad; slot = pk11_getinternalkeyslot(); /* slot = pk11_getbestslot(ciphermech, null); didn't work.
PKCS #11 Module Specs
ciphers - comma separated list of ciphers this token will enable that isn't al
ready enabled by the library (currently only fortezza is defined) (case-insensitive).
...at init time nss, will try to look for a default root cert device if one has not al
ready been loaded.
NSS tools : certutil
the certificate database should al
ready exist; if one is not present, this command option will initialize one by default.
...the key database should al
ready exist; if one is not present, this option will initialize one by default.
ssltyp.html
when an application makes a copy of a particular certificate structure that al
ready exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
...when an application makes a copy of a particular key structure that al
ready exists in memory, ssl makes a deep copy--that is, it makes a whole new copy of that object.
NSS Tools certutil
the key database should al
ready exist; if one is not present, this option will initialize one by default.
...the certificate database should al
ready exist; if one is not present, this option will initialize one by default.
certutil
the certificate database should al
ready exist; if one is not present, this option will initialize one by default.
... the key database should al
ready exist; if one is not present, this option will initialize one by default.
NSS tools : signtool
when testing is finished and you are
ready to disitribute your software, you should obtain an object-signing certificate from one of two kinds of sources: * an independent certificate authority (ca) that authenticates your identity and charges you a fee.
...if the certificate authority's certificate isn't al
ready installed in your copy of communicator, you typically install it by clicking the appropriate link on the certificate authority's web site, for example on the page from which you initiated enrollment for your signing certificate.
JSObjectOps.getRequiredSlot
the jsobjectops.getrequiredslot and setrequiredslot callbacks get and set a required slot—one that should al
ready have been allocated.
... description get and set a required slot, one that should al
ready have been allocated.
JS_ConvertArguments
variables for optional parameters must al
ready be initialized, because if an optional parameter is not in argv, js_convertarguments does not modify the corresponding variable.
...instead, use jsval_is_object and js_objectisfunction() to check whether a value is al
ready a function, or use js_convertvalue() to convert a value to jstype_function safely.
JS_EnumerateResolvedStandardClasses
enumerate any al
ready-resolved standard class ids.
... syntax jsidarray * js_enumerateresolvedstandardclasses(jscontext *cx, jsobject *obj, jsidarray *ida); name type description description js_enumerateresolvedstandardclasses enumerates any al
ready-resolved standard class ids into ida, or into a new jsidarray if ida is null.
JS_SetGCCallback
but the javascript engine will then detect that gc is al
ready happening and will not actually do a nested gc cycle in this case.
...if a thread that is not in an active request calls js_gc while gc is al
ready happening on another thread).
Handling Mozilla Security Bugs
the bugzilla administrators will technically be in the mozilla security bug group as well, mainly because they al
ready have visibility into all bugzilla data hosted through mozilla.org.
... the criteria for membership in the mozilla security bug group are as follows: the applicant must be trusted by those al
ready in the group.
Setting up an update server
most likely, a different maintenance service is al
ready installed, probably at c:\program files (x86)\mozilla maintenance service\maintenanceservice.exe.
... 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!
Manipulating bookmarks using Places
checking to see if a uri is bookmarked if you want to see if a given uri is al
ready bookmarked -- for example, to avoid creating a new bookmark for a site that's al
ready bookmarked -- you can use the nsinavbookmarksservice.isbookmarked() method.
... var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://mozilla.com/", null, null); if (!bmsvc.isbookmarked(uri)) { bmsvc.insertbookmark(bmsvc.toolbarfolder, uri, bmsvc.default_index, "mozilla"); } this example looks to see if the user al
ready has a bookmark for the mozilla web site, and, if not, creates one, adding it to the user's bookmarks toolbar.
Creating the Component Code
since xpcom al
ready knows internally what kind of file it has just loaded and called registerself on, passing this value to the registration methods is a shortcut for determining what kind of component is being registered.
...xpcom then loads the component library associated with the cid if it isn't loaded al
ready.
Mozilla internal string guide
if there's a need to request a different capacity before you are
ready to call finish(), you can call restartbulkwrite() on the handle.
... // modify the url and pass to addpage(const char16_t* url) void addmodifiedpage(const nsastring& url) { constexpr auto httpprefix = u"http://"_ns; const nsastring& modifiedurl = httpprefix + url; // creates a temporary buffer addpage(promiseflatstring(modifiedurl).get()); } promiseflatstring() is smart when handed a string that is al
ready null-terminated.
XPCOM Stream Guide
stream listeners a stream listener is an object you build to let you know when there is data in a stream
ready for you to consume.
... (xxx nsiunicharinputstream interface) (xxx nsiunicharlineinputstream interface) (xxx nsisearchableinputstream interface) stream converters (tbd: @mozilla.org/streamconverters;1) forcing an input stream to be read suppose you al
ready have an input stream, and something to read from that input stream...but the reader doesn't do anything with the stream.
Components.utils.importGlobalProperties
therefore
readystate must be checked, if it is not complete, then a load listener must be attached.
... once
readystate is complete then the objects can be used.
imgIContainer
flag_decode_no_premultiply_alpha: do not premultiply alpha if it is not al
ready premultiplied in the image data.
...if the image is locked or has al
ready been discarded, do nothing.
imgIRequest
aobserver will be notified synchronously (before the clone call returns) with all the notifications that have al
ready been dispatched for this image load.
...calling requestdecode on the imgirequest simply forwards along the request if the container al
ready exists, or calls it once it gets onstartcontainer if the container does not yet exist.
nsIAnnotationService
if the destination al
ready has an annotation with the same name as one on the source, it will be overwritten if aoverwritedest is set.
...if the destination al
ready has an annotation with the same name as one on the source, it will be overwritten if aoverwritedest is set.
nsIApplicationCacheChannel
exceptions thrown ns_error_al
ready_opened if set after calling asyncopen() on the channel.
...exceptions thrown ns_error_al
ready_opened if set after calling asyncopen() on the channel.
nsIBrowserSearchService
init() initialize the service, or if the service is al
ready initialized, do nothing.
... void init( [optional] in nsibrowsersearchinitobserver observer ); parameters observer if specified, a callback called once initialization is complete, or immediately, if the service has al
ready been initialized.
nsICategoryManager
exceptions thrown ns_error_invalid_arg this error is returned if areplace is false and the category entry al
ready has a value, or if apersist is true.
... var content_type = 'application/pdf'; // update the category manager in case the plugins are al
ready loaded.
nsICompositionStringSynthesizer
this means that the clause is al
ready converted.
...this means that the clause is al
ready converted and is selected to convert.
nsIContentSecurityPolicy
isinitialized boolean set to true when the content security policy has been read in and parsed and is
ready to enforce.
... this is a barrier for the nsdocument so it doesn't load any sub-content until either it knows that a content security policy is
ready or will not be used.
nsICookieManager2
cookieexists() returns whether or not a matching cookie al
ready exists.
... findmatchingcookie() obsolete since gecko 1.9 (firefox 3) find whether a matching cookie al
ready exists, and how many cookies a given host has al
ready set.
nsIDOMStorage
if the key does not al
ready exist, a new key is added, associated with the specified value.
... if the key al
ready exists, the existing value is replaced with the specified value.
nsIDOMStorage2
if the key does not al
ready exist, a new key is added, associated with the specified value.
... if the key al
ready exists, the existing value is replaced with the specified value.
nsIDOMWindowInternal
pagexoffset long returns the number of pixels that the document has al
ready been scrolled horizontally.
... pageyoffset long returns the number of pixels that the document has al
ready been scrolled vertically.
nsIFrameLoaderOwner
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview [noscript, notxpcom] al
readyaddrefed_nsframeloader getframeloader(); void swapframeloaders(in nsiframeloaderowner aotherowner); attributes attribute type description frameloader nsiframeloader the frame loader owned by this nsiframeloaderowner.
...[noscript, notxpcom] al
readyaddrefed_nsframeloader getframeloader(); parameters none.
nsIInputStreamCallback
inherits from: nsisupports last changed in gecko 1.7 method overview void oninputstream
ready(in nsiasyncinputstream astream); methods oninputstream
ready() called to indicate that the stream is either readable or closed.
... void oninputstream
ready( in nsiasyncinputstream astream ); parameters astream the stream whose nsiasyncinputstream.asyncwait() method was called.
nsIMsgHeaderParser
addresses are removed if they are al
ready in either addrs or other_addrs.
... that argument is for passing in addresses that were al
ready mentioned in other header fields.) addresses are considered to be the same if they contain the same mailbox part (case-insensitive.) real names and other comments are not compared.
nsINavBookmarksService
if this item al
ready exists in the given folder, it will be moved to the new position.
...this method does not change the indices of any other items in the same folder, so ensure that the new index does not al
ready exist, or change the index of other items accordingly, otherwise the indices will become corrupted.
nsIOutputStreamCallback
inherits from: nsisupports last changed in gecko 1.7 method overview void onoutputstream
ready(in nsiasyncoutputstream astream); methods onoutputstream
ready() called to indicate that the stream is either writable or closed.
... void onoutputstream
ready( in nsiasyncoutputstream astream ); parameters astream the stream whose nsiasyncoutputstream.asyncwait() method was called.
nsIPermissionManager
if the permission al
ready exists for a given type, it will be modified.
...if the permission al
ready exists for a given type, it will be modified.
nsIRequest
validate_once_per_session 1 << 13 disables validation of expired content, provided it has al
ready been validated (at least once) since the start of this session.
... note: some implementations are unable to immediately suspend, and may continue to deliver events al
ready posted to an event queue.
nsIServerSocket
the listener will be passed a reference to an al
ready connected socket transport (nsisockettransport).
...this does not affect al
ready connected client sockets (i.e., the nsisockettransport instances created from this server socket).
nsISocketTransportService
this will fail with the error code ns_error_not_available if the maximum number of sockets is al
ready reached.
... ahandler socket handler that will receive notifications when the socket is
ready or detached.
nsIStyleSheetService
sheets added via this api take effect on all documents, including al
ready-loaded ones, immediately.
...the removal takes effect immediately, even for al
ready-loaded documents.
nsIThread
exceptions thrown ns_error_unexpected shutdown() was erroneously called from within the thread itself, the thread was not created with the thread manager's nsithreadmanager.newthread() method, or the thread is al
ready in the process of being shut down.
... haspendingevents() determines whether or not the thread has events that are
ready to be processed.
nsIUpdatePrompt
if the app.update.silent preference is true or the user interface is al
ready displayed the call will be a no-op.
...if the app.update.silent preference is true, the app.update.showinstalledui preference is false, or the user interface is al
ready displayed the call will be a no-op.
nsIUploadChannel
history here is that we need to support both streams that al
ready have headers (for example, content-type and content-length) information prepended to the stream (by plugins) as well as clients (composer, uploading application) that want to upload data streams without any knowledge of protocol specifications.
...acontenttype if acontenttype is empty, the protocol will assume that no content headers are to be added to the uploaded stream and that any required headers are al
ready encoded in the stream.
Setting HTTP request headers
in the case your code initiates the request, you probably al
ready have one.
...the second line of code in the if block should al
ready be familiar to you.
Storage
note: the database engine does not support nested transactions, so attempting to start a transaction when one is al
ready active will throw an exception.
...if a transaction is al
ready in progress, no transaction is obtained.
XPCOM
this article will show you how to use the available interfaces in several mozilla products.aggregating the in-memory datasourceal
ready_addrefedal
ready_addrefed in association with nscomptr allows you to assign in a pointer without addrefing it.binary compatibilityif mozilla decides to upgrade to a compiler that does not have the same abi as the current version, any built component may fail.
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).creating a python xpcom componentcreating applications with mozilla al
ready provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
Creating a gloda message query
let mylistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function mylistener_onitemsadded(aitems, acollection) { }, /* called when items that are al
ready in our collection get re-indexed */ onitemsmodified: function mylistener_onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function mylistener_onitemsremoved(aitems, acollection) { }, /* called when our database query completes */ onquerycompleted: function mylistener_onquerycompleted(acollection) ...
... want a glodamessage when you al
ready have an nsimsgdbhdr?
Index
if the user al
ready has an email account, the user can switch to the original account setup wizard.
...it assumes you are al
ready familiar with configuring preferences for deployed builds in addition to setting up thunderbird to use an ldap directory.
Add to iPhoto
choose it, and iphoto will start up (if it's not al
ready running) and import the image.
...then we call createunique() to create a unique file by that name (or a derivative thereof if the name is al
ready in use), and download the contents of the image file to that local file.
Working with data
if the original value is al
ready a cdata object, the original object is simply duplicated directly into the new one.
... if type is an array type of unspecified length, the following steps are taken: if the value is a size value, a new array of that length is created, with its cells
ready to accept values of the same type as those in the specified array.
Plug-in Basics - Plugins
the following stages outline the life of a plug-in from loading to deletion: when gecko encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it dynamically loads the plug-in code into memory, if it hasn't been loaded al
ready, and it creates a new instance of the plug-in.
... value="http://www.macromedia.com/shockwave/download/index.cgi?p1_prod_version=shockwaveflash"/> </object> </object> </object> </p></body> </html> the outermost object element defines the classid; the first nested object uses the type value application/x-shockwave-flash to load the adobe flash plug-in, and the innermost object exposes a download page for users that do not al
ready have the necessary plug-in.
URLs - Plugins
if the target parameter is set to null, the application creates a new stream and delivers the data to the plug-in instance, through calls to npp_newstream, npp_write
ready and npp_write, and npp_destroystream.
...the default is _self, if the plug-in instance document is al
ready at the top.
Introduction to DOM Inspector - Firefox Developer Tools
a browser window and the dom inspector are likely be al
ready open and displayed in this list.
...the dom inspector not only presents all this information about pages in a clear and structured way, it gives you way to find and update those structures, and it's simple to access via shortcuts and menus al
ready available in the mozilla browser.
Dominators view - Firefox Developer Tools
if you al
ready know what shallow size, retained size, and dominators are, skip to the dominators ui section.
... taking a snapshot to see what it looks like in the dominators view: load the page enable the memory tool in the settings, if you haven't al
ready open the memory tool check "record call stacks" press the button labeled "make monsters!" take a snapshot switch to the "dominators" view analyzing the dominators tree you'll see the three arrays as the top three gc roots, each retaining about 23% of the total memory usage: if you expand an array, you'll see the objects (monsters) it contains.
Animation.updatePlaybackRate() - Web APIs
it will be updated once the animation's
ready promise is resolved.
... examples a speed selector component would benefit from smooth updating of updateplaybackrate(), as demonstrated below: speedselector.addeventlistener('input', evt => { cartoon.updateplaybackrate(parsefloat(evt.target.value)); cartoon.
ready.then(() => { console.log(`playback rate set to ${cartoon.playbackrate}`); }); }); specifications specification status comment web animationsthe definition of 'updateplaybackrate()' in that specification.
AudioWorkletProcessor.process - Web APIs
in other words, every time a new block of audio is
ready for your processor to manipulate, your process() function is invoked to do so.
...however, plans are al
ready in place to revise the specification to allow the size of the audio blocks to be changed depending on circumstances (for example, if the audio hardware or cpu utilization is more efficient with larger block sizes).
CustomEvent.initCustomEvent() - Web APIs
if the event has al
ready been dispatched, this method does nothing.
... living standard initial definition, but al
ready deprecated in favor of the use of a constructor, customevent() ...
CustomEvent - Web APIs
if the event has al
ready being dispatched, this method does nothing.
...if the event has al
ready been dispatched, this method does nothing.
Document.hasStorageAccess() - Web APIs
examples document.hasstorageaccess().then(hasaccess => { if (hasaccess) { // storage access has been granted al
ready.
... } else { // storage access hasn't been granted al
ready; // you may want to call requeststorageaccess().
Element.requestFullscreen() - Web APIs
function togglefullscreen() { let elem = document.queryselector("video"); if (!document.fullscreenelement) { elem.requestfullscreen().catch(err => { alert(`error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitfullscreen(); } } if the document isn't al
ready in full-screen mode—detected by looking to see if document.fullscreenelement has a value—we call the video's requestfullscreen() method.
... if, on the other hand, full-screen mode is al
ready in effect, we call document.exitfullscreen() to disable full-screen mode.
Element.scrollIntoViewIfNeeded() - Web APIs
the element.scrollintoviewifneeded() method scrolls the current element into the visible area of the browser window if it's not al
ready within the visible area of the browser window.
... if the element is al
ready within the visible area of the browser window, then no scrolling takes place.
Element.setAttributeNodeNS() - Web APIs
myns:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getelementbyid("one"); var d2 = document.getelementbyid("two"); var a = d1.getattributenodens(myns, "special-align"); d2.setattributenodens(a.clonenode(true)); alert(d2.attributes[1].value) // returns: `utterleft' notes if the specified attribute al
ready exists on the element, then that attribute is replaced with the new one and the replaced one is returned.
... note that if you try to set without cloning the node, mozilla gives an ns_error_dom_inuse_attribute_err "attribute al
ready in use" error, as the dom requires cloning for attr to be reused (unlike other nodes which can be moved).
EventSource.close() - Web APIs
the close() method of the eventsource interface closes the connection, if one is made, and sets the eventsource.
readystate attribute to 2 (closed).
... note: if the connection is al
ready closed, the method does nothing.
Using files from web applications - Web APIs
each time you call url.createobjecturl(), a unique object url is created even if you've created an object url for that file al
ready.
...><!doctype html> <html> <head> <title>dnd binary upload</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="application/javascript"> function sendfile(file) { const uri = "/index.php"; const xhr = new xmlhttprequest(); const fd = new formdata(); xhr.open("post", uri, true); xhr.on
readystatechange = function() { if (xhr.
readystate == 4 && xhr.status == 200) { alert(xhr.responsetext); // handle response.
FileException - Web APIs
when errors occur, forward them to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" al
ready exists.
... path_exists_err 12 the file or directory with the same path al
ready exists.
FileReader - Web APIs
filereader.
readystate read only a number indicating the state of the filereader.
...upon return, the
readystate will be done.
FileSystemFlags.exclusive - Web APIs
the exclusive property on the filesystemflags dictionary is used in tandem with the create property to determine whether or not it's acceptable to require that the file not al
ready exist when the reference to it is created by calling filesystemdirectoryentry.getfile() or filesystemdirectoryentry.getdirectory().
... syntax filesystemflags.exclusive = booleanvalue values the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path al
ready exists.
FormData.append() - Web APIs
the append() method of the formdata interface appends a new value onto an existing key inside a formdata object, or adds the key if it does not al
ready exist.
... the difference between formdata.set and append() is that if the specified key al
ready exists, formdata.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values.
FormData.set() - Web APIs
the set() method of the formdata interface sets a new value for an existing key inside a formdata object, or adds the key/value if it does not al
ready exist.
... the difference between set() and formdata.append is that if the specified key does al
ready exist, set() will overwrite all existing values with the new one, whereas formdata.append will append the new value onto the end of the existing set of values.
FormData - Web APIs
methods formdata.append() appends a new value onto an existing key inside a formdata object, or adds the key if it does not al
ready exist.
... formdata.set() sets a new value for an existing key inside a formdata object, or adds the key/value if it does not al
ready exist.
HTMLImageElement.decode() - Web APIs
return value a promise which is resolved once the image data is
ready to be used.
...l use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is
ready for use.
HTMLMediaElement: loadeddata event - Web APIs
the
readystate just increased to ' + 'have_current_data or greater for the first time.'); }); using the onloadeddata event handler property: const video = document.queryselector('video'); video.onloadeddata = (event) => { console.log('yay!
... the
readystate just increased to ' + 'have_current_data or greater for the first time.'); }; specifications specification status html living standardthe definition of 'loadeddata media event' in that specification.
HTMLTableCellElement - Web APIs
colgroup the header cell applies to all cells in the current column group that do not al
ready have a scope applied to them.
... rowgroup the header cell applies to all cells in the current row group that do not al
ready have a scope applied to them.
HTMLVideoElement.videoHeight - Web APIs
if the element's
readystate is htmlmediaelement.have_nothing, then the value of this property is 0, because neither video nor poster frame size information is yet available.
... if at any time the intrinsic size of the media changes and the element's
readystate isn't have_nothing, a resize event will be sent to the <video> element.
HTMLVideoElement.videoWidth - Web APIs
if the element's
readystate is htmlmediaelement.have_nothing, then the value of this property is 0, because neither video nor poster frame size information is yet available.
... if at any time the intrinsic size of the media changes and the element's
readystate isn't have_nothing, a resize event will be sent to the <video> element.
Dragging and Dropping Multiple Items - Web APIs
you should add them in order starting with 0 as you cannot add items at positions farther than the last item, however you can replace existing items by using indices you have al
ready added.
...you may wish to do both in case another listener has al
ready cancelled the event.
IDBDatabase: abort event - Web APIs
false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('abort', () => { console.log('transaction aborted'); }); // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // abort the transaction transaction.abort(); }; the same example, but assigning the event handler to the onabort property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objec...
...utes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.onabort = () => { console.log('transaction aborted'); }; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // abort the transaction transaction.abort(); }; ...
IDBDatabaseSync - Web APIs
exceptions this method can raise an idbdatabaseexception with the following code: constraint_err if an object store with the same name (based on case-sensitive comparison) al
ready exists in the connected database.
... exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if an object store with the given name (based on case-sensitive comparison) al
ready exists in the connected database.
IDBFactorySync - Web APIs
blocks the calling thread until the connection object is
ready to return.
... if there is al
ready a database with the specified name, it uses that one; otherwise, it creates the database using the specified name and description.
IDBIndexSync - Web APIs
if a record al
ready exists with the given key, an exception is raised.
...if a record al
ready exists with the given key, the record is overwritten.
IDBObjectStore.createIndex() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description constrainterror occurs if an index with the same name al
ready exists in the database.
... db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data al
ready in the idb displaydata(); }; // this handler fires when a new database is created and indicates // either that one has not been created before, or a new version // was submitted with window.indexeddb.open().
IDBObjectStore.name - Web APIs
constrainterror an object store is al
ready using the specified name.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(e...
IDBObjectStoreSync - Web APIs
if a record al
ready exists with the given key, an exception is raised.
...if a record al
ready exists with the given key, it is overwritten.
IDBRequest.error - Web APIs
you get this error, for example, if you try to add a new key that al
ready exists in the record.
... versionerror if you try to open a database with a version lower than the one it al
ready has.
IDBRequest - Web APIs
each request has a
readystate that is set to the 'pending' state; this changes to 'done' when the request is completed or fails.
... idbrequest.
readystate read only the state of the request.
IDBTransaction.abort() - Web APIs
syntax transaction.abort(); exceptions this method may raise a domexception of the following type: exception description invalidstateerror the transaction has al
ready been committed or aborted.
...this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
IDBTransaction: abort event - Web APIs
'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `abort` transaction.addeventlistener('abort', () => { console.log('transaction was aborted'); }); // abort the transaction transaction.abort(); }; the same example, but assigning the event handler to the onabort property: // open the database const dbopenrequest = window.i...
... 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `abort` transaction.onabort = (event) => { console.log('transaction was aborted'); }; // abort the transaction transaction.abort(); }; ...
IDBTransaction: complete event - Web APIs
'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.addeventlistener('complete', event => { console.log('transaction was competed'); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; cons...
... 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction,
ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.oncomplete = event => { console.log('transaction was competed'); }; const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequ...
IDBTransaction.objectStore() - Web APIs
the objectstore() method of the idbtransaction interface returns an object store that has al
ready been added to the scope of this transaction.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
Basic concepts - Web APIs
they also have
readystate, result, and errorcode properties that tell you the status of the request.
...so, for example, if a database connection al
ready has a writing transaction with a scope that just covers the flyingmonkey object store, you can start a second transaction with a scope of the unicorncentaur and unicornpegasus object stores.
Checking when a deadline is due - Web APIs
n (i have used the required attribute in my html to force validation, in those that do.) else { var newitem = [ { tasktitle: title.value, hours : hours.value, minutes : minutes.value, day : day.value, month : month.value, year : year.value, notified : "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction opened for task addition.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error.
... request.onsuccess = function(event) { note.innerhtml += '<li>new item added to database.</li>'; title.value = ''; hours.value = null; minutes.value = null; day.value = 01; month.value = 'january'; year.value = 2020; }; } this next section creates a log message to say the new item addition is successful, and resets the form so it's
ready for the next task to be entered.
MediaSource.activeSourceBuffers - Web APIs
example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); console.log(mediasource.activesourcebuffers); // will contain the source buffer that was added above, // as it is selected for playing in the video...
... player video.play(); //console.log(mediasource.
readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; ...
MediaSource.duration - Web APIs
invalidstateerror mediasource.
readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e.
... their sourcebuffer.updating property is true.) example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); mediasource.duration = 120; video.play(); //console.log(mediasource.
readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; ...
MediaSource.isTypeSupported() - Web APIs
ew the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.
readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sour...
...cebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.
readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'istypesupported()' in that specification.
MediaStream - Web APIs
this has been removed from the specification; you should instead check the value of mediastreamtrack.
readystate to see if its value is ended for the track or tracks you want to ensure have finished playing.
...if the track has al
ready been added to the mediastream object, nothing happens.
MediaStreamTrack - Web APIs
mediastreamtrack.
readystate read only returns an enumerated value giving the status of the track.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: ended sent when playback of the track ends (when the value
readystate changes to ended).
Capabilities, constraints, and settings - Web APIs
if it's clicked and there's not al
ready media in use, we call startvideo(), and let that function handle starting the stream with the specified settings in place.
... otherwise, we follow these steps to apply the updated constraints to the al
ready-active stream: buildconstraints() is called to construct updated mediatrackconstraints objects for the audio track (audioconstraints) and the video track (videoconstraints).
MutationObserver.observe() - Web APIs
there are some caveats to note: if you call observe() on a node that's al
ready being observed by the same mutationobserver, all existing observers are automatically removed from all targets being observed before the new observer is activated.
... if the same mutationobserver is not al
ready in use on the target, then the existing observers are left alone and the new one is added.
NDEFWriter.write() - Web APIs
notallowederror the permission for this operation was rejected or overwrite is false and there are al
ready records on the tag.
... networkerror transfer failed after it al
ready started (e.g., the tag was removed from the reader).
Web-based protocol handlers - Web APIs
registering the same protocol handler more than once will pop up a different notification, indicating that the protocol handler is al
ready registered.
... therefore, it is a good idea to guard your call to register the protocol handler with a check to see if it is al
ready registered, such as in the example below.
Notification.requestPermission() - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have al
ready been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notificati...
...firefox is al
ready doing this from version 72, for example.
Notification - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have al
ready been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notificati...
...firefox is al
ready doing this from version 72, for example.
ProgressEvent() - Web APIs
lengthcomputable optional is a boolean flag indicating if the total work to be done, and the amount of work al
ready done, by the underlying process is calculable.
... loaded optional is an unsigned long long representing the amount of work al
ready performed by the underlying process.
ProgressEvent.initProgressEvent() - Web APIs
lengthcomputable is a boolean flag indicating if the total work to be done, and the amount of work al
ready done, by the underlying process is calculable.
... loaded is an unsigned long long representing the amount of work al
ready performed by the underlying process.
ProgressEvent - Web APIs
progressevent.lengthcomputable read only is a boolean flag indicating if the total work to be done, and the amount of work al
ready done, by the underlying process is calculable.
... progressevent.loaded read only is an unsigned long long representing the amount of work al
ready performed by the underlying process.
PromiseRejectionEvent.promise - Web APIs
examples this example listens for unhandled promises and, if the reason is an object with a code field containing the text "module not
ready", it sets up an idle callback that will retry the task that failed to execute correctly.
... window.onunhandledrejection = function(event) { if (event.reason.code && event.reason.code == "module not
ready") { window.requestidlecallback(function(deadline) { loadmodule(event.reason.modulename) .then(performstartup); }); event.preventdefault(); } } specifications specification status comment html living standardthe definition of 'promiserejectionevent.promise' in that specification.
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
excludecredentials, an optional property of the publickeycredentialcreationoptions dictionary, is an array whose elements are descriptors for the public keys al
ready existing for a given user.
... if the authenticator al
ready contains one of such a public key credential, the client will throw a domexception or asks the user if they want to create a new credential.
PublicKeyCredentialCreationOptions - Web APIs
this is provided by the relying party to avoid creating new public key credentials for an existing user who al
ready have some.
...authenticator's origin attestation attestation: "none", extensions: { uvm: true, exts: true }, // filter out authenticators which are bound to the device authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey: true, userverification: "preferred" }, // exclude al
ready existing credentials for the user excludecredentials: [ { type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ ...
PushManager.subscribe() - Web APIs
} navigator.serviceworker.register('serviceworker.js'); // use serviceworker.
ready to ensure that you can subscribe for push navigator.serviceworker.
ready.then( function(serviceworkerregistration) { var options = { uservisibleonly: true, applicationserverkey: applicationserverkey }; serviceworkerregistration.pushmanager.subscribe(options).then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscr...
...firefox is al
ready doing this from version 72, for example.
RTCDTMFSender - Web APIs
"30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">rtcdtmfsender</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties rtcdtmfsender.tonebuffer read only a domstring which contains the list of dtmf tones currently in the queue to be transmitted (tones which have al
ready been played are no longer included in the string).
...calling insertdtmf() replaces any al
ready-pending tones from the tonebuffer.
RTCDataChannel.close() - Web APIs
the sequence of events which occurs in response to this method being called: rtcdatachannel.
readystate is set to "closing".
... the rtcdatachannel.
readystate property is set to "closed".
RTCPeerConnection.createDataChannel() - Web APIs
resourceinuse an id was specified, but another rtcdatachannel is al
ready using the same value.
... operationerror either the specified id is al
ready in use or, if no id was specified, the webrtc layer was unable to automatically generate an id because all ids are in use.
RTCPeerConnection.createOffer() - Web APIs
the sdp offer includes information about any mediastreamtracks al
ready attached to the webrtc session, codec, and options supported by the browser, and any candidates al
ready gathered by the ice agent, for the purpose of being sent over the signaling channel to a potential peer to request a connection or to update the configuration of an existing connection.
...this will cause the returned offer to have different credentials than those al
ready in place.
RTCPeerConnection.removeTrack() - Web APIs
if the track is al
ready stopped, or is not in the connection's senders list, this method has no effect.
... if the connection has al
ready been negotiated (signalingstate is set to "stable"), it is marked as needing to be negotiated again; the remote peer won't experience the change until this negotiation occurs.
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
exceptions typeerror the supplied stream parameter is not a readablestream, or it is al
ready locked for reading by another reader.
... function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has al
ready given you all its data.
SVGImageElement.decode - Web APIs
the decode() method of the svgimageelement interface initiates asynchronous decoding of an image, returning a promise that resolves once the image data is
ready for use.
... return value a promise which resolves once the image data is
ready to be used, such as by appending it to the dom, replacing an existing image, and so forth.
ServiceWorkerGlobalScope: notificationclick event - Web APIs
cancelable no interface notificationevent event handler onnotificationclick examples you can use the notificationclick event in an addeventlistener method: self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); or use the onnotificationclic...
...k event handler property: self.onnotificationclick = function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }; specifications specification status notifications apithe definition of 'onnotificationclick' in that specification.
Using Service Workers - Web APIs
this is al
ready available with native apps, which is one of the main reasons native apps are often chosen over web apps.
... the service worker is now
ready to process events.
SourceBuffer.abort() - Web APIs
exceptions exception explanation invalidstateerror the mediasource.
readystate property of the parent media source is not equal to open, or this sourcebuffer has been removed from the mediasource.
...in lines 92-101, the seek() function is defined — note that abort() is called if mediasource.
readystate is set to open, which means that it is
ready to receive new source buffers — at this point it is worth aborting the current segment and just getting the one for the new seek position (see checkbuffer() and getcurrentsegment().) specifications specification status comment media source extensionsthe definition of 'abort()' in that specification.
SourceBuffer - Web APIs
r further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.
readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sour...
...cebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.
readystate); // ended }); sourcebuffer.appendbuffer(buf); }); } function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); } specifications specification status comment media source extensionsthe definition of 'sourcebuffer' in that specification.
Using readable streams - Web APIs
function readstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has al
ready given you all its data.
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } closing and cancelling streams we’ve al
ready shown examples of using readablestreamdefaultcontroller.close() to close a reader.
A basic 2D WebGL animation example - Web APIs
with the association in place between the vertex buffer for our shape and the avertexposition attribute used to deliver vertexes one by one into the vertex shader, we're
ready to draw the shape by calling drawarrays().
...that's done here by calling requestanimationframe(), which asks that a callback function be executed the next time the browser is
ready to update the screen.
Basic scissoring - Web APIs
we have al
ready seen how fragment color changes during graphics operations, by applying color masking.
... in other cases, the fragments may be discarded altogether (so the pixel value is not updated), or it may interact with the al
ready existing pixel value (such as when doing color blending for non-opaque elements in the scene).
Compressed texture formats - Web APIs
note that webgl makes no functionality available to compress or decompress textures: they must al
ready be in a compressed format and can then be directly uploaded to video memory.
... no examples async function getcompressedtextureifavailable(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // create texture object on gpu const ext = gl.getextension('webgl_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is al
ready in the correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 ...
Animating textures in WebGL - Web APIs
o can be copied to texture var copyvideo = false; function setupvideo(url) { const video = document.createelement('video'); var playing = false; var timeupdate = false; video.autoplay = true; video.muted = true; video.loop = true; // waiting for these 2 events ensures // there is data in the video video.addeventlistener('playing', function() { playing = true; check
ready(); }, true); video.addeventlistener('timeupdate', function() { timeupdate = true; check
ready(); }, true); video.src = url; video.play(); function check
ready() { if (playing && timeupdate) { copyvideo = true; } } return video; } first we create a video element.
...instead, all it does is create an empty texture object, put a single pixel in it, and set its filtering for later use: function inittexture(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because video has to be download over the internet // they might take a moment until it's
ready so // put a single pixel in the texture so we can // use it immediately.
Getting started with WebGL - Web APIs
it's assumed that you al
ready have an understanding of the mathematics involved in 3d graphics, and this article doesn't pretend to try to teach you 3d graphics concepts itself.
... at this point, you have enough code that the webgl context should successfully initialize, and you should wind up with a big black, empty box,
ready and waiting to receive content.
WebRTC connectivity - Web APIs
the pendinglocaldescription contains not just the offer or answer under consideration, but any local ice candidates which have al
ready been gathered since the offer or answer was created.
... ice rollbacks when renegotiating a connection that's al
ready active and a situation arises in which the negotiation fails, you don't really want to kill the al
ready-running call.
Starting up and shutting down a WebXR session - Web APIs
assuming you're al
ready familiar with 3d graphics in general and webgl in particular, taking that next bold step into mixed reality—the idea of presenting artificial scenery or objects in addition to or in place of the real world—is not overly complicated.
...when you're
ready to create your reference space, you can try for a local space, and if that fails, fall back to a viewer reference space, which all devices are required to support.
Web Audio API - Web APIs
audioprocess (event) the audioprocess event is fired when an input buffer of a web audio api scriptprocessornode is
ready to be processed.
... audioprocessingevent the web audio api audioprocessingevent represents events that occur when a scriptprocessornode input buffer is
ready to be processed.
Window - Web APIs
window.scrollx read only returns the number of pixels that the document has al
ready been scrolled horizontally.
... window.scrolly read only returns the number of pixels that the document has al
ready been scrolled vertically.
WritableStream.getWriter() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += dec...
WritableStreamDefaultWriter.close() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += dec...
WritableStreamDefaultWriter.write() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.
ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call
ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.
ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += dec...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
the channel property becomes available only after the request is sent and the connection was established, that is, on
readystate loaded, interactive or completed.
... // sec_error_expired_certificate, sec(11) errname = 'securityexpiredcertificateerror'; break; case 12: // sec_error_revoked_certificate, sec(12) errname = 'securityrevokedcertificateerror'; break; // per bsmith, we will be unable to tell these errors apart very soon, // so it makes sense to just folder them all together al
ready.
XMLHttpRequest.abort() - Web APIs
the xmlhttprequest.abort() method aborts the request if it has al
ready been sent.
... when a request is aborted, its
readystate is changed to xmlhttprequest.unsent (0) and the request's status code is set to 0.
XMLHttpRequest.getAllResponseHeaders() - Web APIs
example this example examines the headers in the request's
readystatechange event handler, xmlhttprequest.on
readystatechange.
... var request = new xmlhttprequest(); request.open("get", "foo.txt", true); request.send(); request.on
readystatechange = function() { if(this.
readystate == this.headers_received) { // get the raw header string var headers = request.getallresponseheaders(); // convert the header string into an array // of individual headers var arr = headers.trim().split(/[\r\n]+/); // create a map of header names to values var headermap = {}; arr.foreach(function (line) { var parts = line.split(': '); var header = parts.shift(); var value = parts.join(': ')...
XMLHttpRequest.getResponseHeader() - Web APIs
example in this example, a request is created and sent, and a
readystatechange handler is established to look for the
readystate to indicate that the headers have been received; when that is the case, the value of the content-type header is fetched.
... var client = new xmlhttprequest(); client.open("get", "unicorns-are-teh-awesome.txt", true); client.send(); client.on
readystatechange = function() { if(this.
readystate == this.headers_received) { var contenttype = client.getresponseheader("content-type"); if (contenttype != my_expected_type) { client.abort(); } } } specifications specification status comment xmlhttprequestthe definition of 'getresponseheader()' in that specification.
XMLHttpRequest.responseText - Web APIs
you know the entire content has been received when the value of
readystate becomes xmlhttprequest.done (4), and status becomes 200 ("ok").
... example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); // if specified, responsetype must be empty string or "text" xhr.responsetype = 'text'; xhr.onload = function () { if (xhr.
readystate === xhr.done) { if (xhr.status === 200) { console.log(xhr.response); console.log(xhr.responsetext); } } }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XRRigidTransform() - Web APIs
the specified orientation gets normalized if it's not al
ready.
...the drawframe() callback will be executed when the system is
ready to draw the next frame.
XRSystem: isSessionSupported() - Web APIs
if no session is al
ready underway, we request the vr session and, if successful, set up the session in a method called onsessionstarted(), not shown.
... if a session is al
ready underway when the button is clicked, we call the xrsession object's end() method to shut down the webxr session.
ARIA: listbox role - Accessibility
when a list is tabbed to, the first item in the list will be selected if nothing else al
ready is.
... the first rule of aria use is you can use a native feature with the semantics and behavior you require al
ready built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
some assistive technologies will look for msaa if it doesn't al
ready know that the given window class is used for something common.
...in addition, assistive technology vendors are tiny companies, often scrambling to keep up with changes in the applications they al
ready support, or new products other than yours which they need to support.
Accessibility documentation index - Accessibility
authors must assign an aria role and the appropriate states and properties to an element during its life-cycle, unless the element al
ready has appropriate aria semantics (via use of an appropriate html element).
... 62 aria: figure role aria, aria role, aria figure, accessibility, reference, rôle, figure the aria figure role can be used to identify a figure inside page content where appropriate semantics do not al
ready exist.
:visited - CSS: Cascading Style Sheets
the :visited css pseudo-class represents links that the user has al
ready visited.
... html <a href="#test-visited-link">have you visited this link yet?</a><br> <a href="">you've al
ready visited this link.</a> css a { /* specify non-transparent defaults to certain properties, allowing them to be styled with the :visited state */ background-color: white; border: 1px solid white; } a:visited { background-color: yellow; border-color: hotpink; color: hotpink; } result specifications specification status comment html living standard...
Detecting CSS animation support - CSS: Cascading Style Sheets
the first thing to do is look to see if there's al
ready a style sheet on the document; if so, we simply insert the keyframe description into that stylesheet; this is done in lines 13-15.
... if there isn't al
ready a style sheet, a new <style> element is created, and its content is set to the value of keyframes.
Media buffering, seeking, and time ranges - Developer guides
byte range requests allow parts of the media file to be delivered from the server and so can be
ready to play almost immediately — thus they are seekable.
... var seekabletimeranges = myaudio.seekable; creating our own buffering feedback if we wish to create our own custom player, we may want to provide feedback on how much of the media is
ready to be played.
HTML5 Parser - Developer guides
ie al
ready fails to parse documents with a missing </title> tag, so if you test with ie, you probably don't have that problem.
...however, unclosed comments often al
ready break in existing browsers for one reason or another, so it's unlikely that you have this issue in sites that are tested in multiple browsers.
Index - Developer guides
14 web audio playbackrate explained apps, audio, media, video, playbackrate the playbackrate property of the <audio> and <video> elements allows us to change the speed, or rate, at which a piece of web audio or video is playing 15 writing web audio api code that works in every browser api you probably have al
ready read the announcement on the web audio api coming to firefox, and are totally excited and
ready to make your until-now-webkit-only sites work with firefox, which uses the unprefixed version of the spec.
...once we're
ready for wider adoption the information from wiki.mozilla.org will be moved here, updated and expanded.
<input type="date"> - HTML: Hypertext Markup Language
lback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.display = 'block'; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populatedays(monthselect.value); populateyears(); } function populatedays(month) { // delete the current set of <option> elements out of the // day <select>,
ready for the next set to be injected while(dayselect.firstchild){ dayselect.removechild(dayselect.firstchild); } // create variable to hold new number of days to inject var daynum; // 31 or 30 days?
...daynum = 29 : daynum = 28; } // inject the right number of new <option> elements into the day <select> for(i = 1; i <= daynum; i++) { var option = document.createelement('option'); option.textcontent = i; dayselect.appendchild(option); } // if previous day has al
ready been set, set dayselect's value // to that day, to avoid the day jumping back to 1 when you // change the year if(previousday) { dayselect.value = previousday; // if the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g.
Evolution of HTTP - HTTP
these four building blocks were completed by the end of 1990, and the first servers were al
ready running outside of cern by early 1991.
...by july 2016, 8.7% of all web sites[1] were al
ready using it, representing more than 68% of all requests[2].
Compression in HTTP - HTTP
in practice, web developers don't need to implement compression mechanisms, both browsers and servers have it implemented al
ready, but they have to be sure that the server is configured adequately.
... as compression brings significant performance improvements, it is recommended to activate it for all files, but al
ready compressed ones like images, audio files and videos.
Configuring servers for Ogg media - HTTP
this information may also be useful if you encounter other media types your server isn't al
ready configured to recognize.
...the data in media files is al
ready compressed, so you won't get any real benefit from compression, and the use of compression makes it impossible for the browser to properly seek the video or determine its duration.
Accept-Encoding - HTTP
two common cases lead to this: the data to be sent is al
ready compressed and a second compression won't lead to smaller data to be transmitted.
... * matches any content encoding not al
ready listed in the header.
Link prefetching FAQ - HTTP
basically, there are two ways of looking at this issue: websites can al
ready cause things to be silently downloaded using js/dom hacks.
... privacy implications along with the referral and url-following implications al
ready mentioned above, prefetching will generally cause the cookies of the prefetched site to be accessed.
Details of the object model - JavaScript
this chapter assumes that you are al
ready somewhat familiar with javascript and that you have used javascript functions to create simple objects.
...in a class definition, you can specify that the new class is a subclass of an al
ready existing class.
Regular expressions - JavaScript
note: if you are al
ready familiar with the forms of a regular expression, you may also read the cheatsheet for a quick lookup for a specific pattern/construct.
... if escape strings are not al
ready part of your pattern you can add them using string.replace: function escaperegexp(string) { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } the "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches.
SyntaxError: redeclaration of formal parameter "x" - JavaScript
message syntaxerror: let/const redeclaration (edge) syntaxerror: redeclaration of formal parameter "x" (firefox) syntaxerror: identifier "x" has al
ready been declared (chrome) error type syntaxerror what went wrong?
...if you want to create a new variable, you need to rename it as conflicts with the function parameter al
ready.
Promise.any() - JavaScript
return value an al
ready resolved promise if the iterable passed is empty.
... if an empty iterable is passed, then this method returns (synchronously) an al
ready resolved promise.
Promise.prototype.then() - JavaScript
returns an al
ready fulfilled promise, the promise returned by then gets fulfilled with that promise's value as its value.
... returns an al
ready rejected promise, the promise returned by then gets rejected with that promise's value as its value.
Symbol.for() - JavaScript
symbol.for() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is al
ready present in the registry.
... examples using symbol.for symbol.for('foo'); // create a new global symbol symbol.for('foo'); // retrieve the al
ready created symbol // same global symbol, but not locally symbol.for('bar') === symbol.for('bar'); // true symbol('bar') === symbol('bar'); // false // the key is also used as the description var sym = symbol.for('mario'); sym.tostring(); // "symbol(mario)" to avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: ...
WebAssembly.instantiate() - JavaScript
the secondary overload takes an al
ready-compiled webassembly.module and returns a promise that resolves to an instance of that module.
... this overload is useful if the module has al
ready been compiled.
Object initializer - JavaScript
(see property accessors for detailed information.) object.foo // "bar" object['age'] // 42 object.foo = 'baz' property definitions we have al
ready learned how to notate properties using the initializer syntax.
...this is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties al
ready.
class - JavaScript
class foo {}; class foo {}; // uncaught syntaxerror: identifier 'foo' has al
ready been declared the same error is thrown when a class has been defined before using the class expression.
... let foo = class {}; class foo {}; // uncaught syntaxerror: identifier 'foo' has al
ready been declared specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification.
let - JavaScript
in the same line, the if block's foo has al
ready been created in the lexical environment, but has not yet reached (and terminated) its initialization (which is part of the statement itself).
...the instruction let n of n.a is al
ready inside the private scope of the for loop's block.
Strict mode - JavaScript
i'm a strict mode script!"; this syntax has a trap that has al
ready bitten a major site: it isn't possible to blindly concatenate conflicting scripts.
... x; } the simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands
ready to replace with.
OpenSearch description format
reference material opensearch documentation safari 8.0 release notes: quick website search microsoft edge dev guide: search provider discovery the chromium projects: tab to search imdb.com has a working osd.xml opensearch plugin generator
ready2search - create opensearch plugins.
... customized search through
ready2search ...
Progressive web app structure - Progressive web apps (PWAs)
that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any new content is requested from the server (if it isn’t available in the cache al
ready).
...it's different with html, as the browser is actually streaming the data al
ready and you can see when the elements are loaded and rendered on the website.
Introduction to progressive web apps - Progressive web apps (PWAs)
progressive enhancement and responsive design al
ready allow us to build mobile friendly websites.
... some of the capabilities have al
ready been enabled on certain web-based platforms by proprietary technologies like open graph, which provides a format for specifying similar metadata in the html <head> block using <meta> tags.
Progressive loading - Progressive web apps (PWAs)
it's not unusual to have megabytes of image data to download before announcing the site is
ready, but this again creates a bad perception of performance.
...you could try to make your apps more bulletproof by making them work without javascript — either using <noscript> to show the image with final src al
ready assigned, or by wrapping <img> tags with <a> elements pointing at the target images, so the user can click and access them when desired.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
as mentioned before, to be able to receive push messages, you have to have a service worker, the basics of which are al
ready explained in the making pwas work offline with service workers article.
... in the registration part, the code looks like this: if(subscription) { return subscription; } if the user has al
ready subscribed, we then return the subscription object and move to the subscription part.
Structural overview of progressive web apps - Progressive web apps (PWAs)
that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any new content is requested from the server (if it isn’t available in the cache al
ready).
...it's different with html, as the browser is actually streaming the data al
ready and you can see when the elements are loaded and rendered on the website.
<use> - SVG: Scalable Vector Graphics
html,body,svg { height:100% } <svg viewbox="0 0 30 10" xmlns="http://www.w3.org/2000/svg"> <circle id="mycircle" cx="5" cy="5" r="4" stroke="blue"/> <use href="#mycircle" x="10" fill="blue"/> <use href="#mycircle" x="20" fill="white" stroke="red"/> <!-- stroke="red" will be ignored here, as stroke was al
ready set on mycircle.
... most attributes on use do not override those al
ready on the element referenced by use.
SVG documentation index - SVG: Scalable Vector Graphics
271 basic transformations intermediate, svg, svg:tutorial now we're
ready to start distorting our beautiful images.
...it can be used to create an image either by specifying all the lines and shapes necessary, by modifying al
ready existing raster images, or by a combination of both.
Paths - SVG: Scalable Vector Graphics
if the cursor was al
ready somewhere on the page, no line is drawn to connect the two positions.
...you might have al
ready gained practical experience with bézier curves using path tools in inkscape, illustrator or photoshop.
How to fix a website with blocked mixed content - Web security
note that since mixed content blocking al
ready happens in chrome and internet explorer, it is very likely that if your website works in both of these browsers, it will work equally well in firefox with mixed content blocking.
... often, the https version of the content al
ready exists and this just requires adding an "s" to links - http:// to https://.
Types of attacks - Web security
the browser executes the code because it assumes the response is from a "trusted" server which the user has al
ready interacted with.
... session fixation should primarily be mitigated by regenerating session cookie values when the user authenticates (even if a cookie al
ready exists) and by tieing any csrf token to the user.
Tutorials
intermediate level css layout at this point we've al
ready looked at css fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside.
...you've seen this stuff al
ready in the course, but only in passing — here we'll discuss it all explicitly.
Understanding WebAssembly text format - WebAssembly
putting this together with what we have al
ready learned, we can finally define a module containing our own simple function: (module (func (param $lhs i32) (param $rhs i32) (result i32) local.get $lhs local.get $rhs i32.add)) this function gets two parameters, adds them together, and returns the result.
...on statement outside the function, elsewhere in the module in the same manner as we did before, e.g.: (export "getanswerplus1" (func $functionname)) the javascript code to call our above module looks like so: webassembly.instantiatestreaming(fetch('call.wasm')) .then(obj => { console.log(obj.instance.exports.getanswerplus1()); // "43" }); importing functions from javascript we have al
ready seen javascript calling webassembly functions, but what about webassembly calling javascript functions?
Communicating With Other Scripts - Archive of obsolete content
n.js" will create a page-mod that will attach "content-script.js" to the target web page, and will then load the target web page: var tabs = require("sdk/tabs"); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageurl = self.data.url("page.html") var pagemod = mod.pagemod({ include: pageurl, contentscriptfile: self.data.url("content-script.js"), contentscriptwhen: "
ready" }) tabs.open(pageurl); the target web page "page.html" includes a button and a page script: <html> <head> <meta charset="utf-8"> </head> <body> <input id="message" type="button" value="send a message"/> <script type="text/javascript" src="page-script.js"></script> </body> </html> the content script "content-script.js" adds an event listener to the button, that sends a cu...
port - Archive of obsolete content
due to bug 816272 the page-mod's removelistener() function does not prevent the listener from receiving messages that are al
ready queued.
self - Archive of obsolete content
if you do this, the data is available to the content script in the options property of self: // main.js const tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", on
ready: function(tab) { tab.attach({ contentscriptfile: "./content-script.js", contentscriptoptions: { a: "blah" } }); } }); // content-script.js alert(self.options.a); port you can use port to receive messages from, and send messages to, the main add-on code.
Porting the Library Detector - Archive of obsolete content
tview(tab.window); if (!tab.libraries) { tab.libraries = []; } widgetview.content = buildwidgetviewcontent(tab.libraries); widgetview.width = tab.libraries.length * icon_width; } main.js will use the tabs module to update the widget's content when necessary (for example, when the user switches between tabs): tabs.on('activate', function(tab) { updatewidgetview(tab); }); tabs.on('
ready', function(tab) { tab.libraries = []; }); showing the library detail the xul library detector displayed the detailed information about each library on mouseover in a tooltip: we can't do this using a widget, so instead will use a panel.
hotkeys - Archive of obsolete content
the following commonly used hotkey combinations will not pass amo review: accel-z, accel-c, accel-x, accel-v or accel-q if you choose to use a key combination that's al
ready defined, choose one which makes sense for the operation it will perform.
private-browsing - Archive of obsolete content
for example, here's an add-on that stores the titles of tabs the user loads, and uses isprivate() to exclude the titles of tabs that were loaded into private windows: var simplestorage = require("simple-storage"); if (!simplestorage.storage.titles) simplestorage.storage.titles = []; require("tabs").on("
ready", function(tab) { if (!require("sdk/private-browsing").isprivate(tab)) { console.log("storing..."); simplestorage.storage.titles.push(tab.title); } else { console.log("not storing, private data"); } }); here's an add-on that uses a page-mod to log the content of pages loaded by the user, unless the page is private.
content/worker - Archive of obsolete content
the script may not be initialized yet, or may al
ready have been unloaded you can handle the detach event in the content script itself though: // in content script self.port.on("detach", function() { window.close(); }); ...
event/core - Archive of obsolete content
to avoid hassles of removing such listeners there is a convenient once function: once(target, 'load', function() { console.log('
ready'); }); emit(target, 'load') // info: '
ready' emit(target, 'load') there are also convenient ways to remove registered listeners.
places/favicon - Archive of obsolete content
let { getfavicon } = require("sdk/places/favicon"); // string example getfavicon("http://mozilla.org").then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); // tab example require("sdk/tabs").open({ url: "http://mozilla.org", on
ready: function (tab) { getfavicon(tab).then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); } }); // an optional callback can be provided to handle // the promise's resolve and reject states getfavicon("http://mozilla.org", function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); parameters object :...
jpm-mobile - Archive of obsolete content
jpm usage is: jpm-mobile [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number installation jpm-mobile is distributed using the node package manager npm, so to get jpm-mobile you need to have npm installed, if you haven't al
ready.
Displaying annotations - Archive of obsolete content
updating main.js first, initialize an array to hold workers associated with the matcher's content scripts: var matchers = []; in the main function, add the code to create the matcher: var matcher = pagemod.pagemod({ include: ['*'], contentscriptwhen: '
ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('matcher.js')], onattach: function(worker) { if(simplestorage.storage.annotations) { worker.postmessage(simplestorage.storage.annotations); } worker.port.on('show', function(data) { annotation.content = data; annotation.show(); }); worker.port.on('hide', function() { ...
Implementing the widget - Archive of obsolete content
the following code: var widgets = require('sdk/widget'); var data = require('sdk/self').data; var annotatorison = false; function toggleactivation() { annotatorison = !annotatorison; return annotatorison; } exports.main = function() { var widget = widgets.widget({ id: 'toggle-switch', label: 'annotator', contenturl: data.url('widget/pencil-off.png'), contentscriptwhen: '
ready', contentscriptfile: data.url('widget/widget.js') }); widget.port.on('left-click', function() { console.log('activate/deactivate'); widget.contenturl = toggleactivation() ?
Logging - Archive of obsolete content
the following add-on logs the html content of every tab the user loads, by calling console.log() inside a content script: require("sdk/tabs").on("
ready", function(tab) { tab.attach({ contentscript: "console.log(document.body.innerhtml);" }); }); console output if you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used.
Modifying Web Pages Based on URL - Archive of obsolete content
in particular, the pagemod constructor takes several additional options to control its behavior: by default, content scripts are not attached to any tabs that are al
ready open when the page-mod is created, and are attached to iframes as well as top-level documents.
Miscellaneous - Archive of obsolete content
= stream.readbytearray(stream.available()); var poststr = string.fromcharcode.apply(null, postbytes); //do anything to your poststr alert(poststr); getting a string from the input stream is made somewhat simpler in firefox 4, by the addition of netutil.readinputstreamtostring() getting postdata of a request before the request is sent the above code will get the postdata for a page that has al
ready loaded.
Post data to window - Archive of obsolete content
createinstance(ci.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); // postdata is
ready to be used as apostdata argument ...
Sidebar - Archive of obsolete content
// toggle the bookmarks sidebar (close it if it's open or // open it if it's currently closed) sidebarui.toggle("viewbookmarkssidebar"); // show the history sidebar, whether it's hidden or al
ready showing sidebarui.show("viewhistorysidebar"); // hide the sidebar, if one is showing sidebarui.hide(); avoid opening the sidebar on startup.
xml:base support in old browsers - Archive of obsolete content
3 : 2; // if the file protocol has an extra slashe, prepare to also skip it in the separator search var att2 = att.indexof('/', protocolpos+skipfile); // find first path separator ('/') after protocol if (att2 !== -1) { att = att.substring(0, att2 - 1); // don't want any trailing slash, as the absolute path to be added al
ready has one } } else if (!att.match(/\/$/)) { // if no trailing slash, add one, since it is being attached to a relative path att += '/'; } xmlbase = att + xmlbase; // if previous path was not absolute, resolve against the full uri here' break; } else if (att.indexof('/') === 0) { // if absolute (/), need to prepare for next time to strip out after slash xmlbas...
Extension Versioning, Update and Compatibility - Archive of obsolete content
in the install.rdf of the al
ready installed add-on updateurl must be specified in one of the following ways: the updateurl uses https, or there is no updateurl at all (which defaults to addons.mozilla.org which is https) the updateurl uses http and the updatekey entry is specified which will be used to verify the data in the update manifest.
JavaScript crypto - Archive of obsolete content
# of // arguments js_err_add_module = -5 // error adding a module js_err_bad_module_name = -6 // the module name is invalid js_err_add_module_duplicate = -10 // the module being installed has the // same name as one of the modules that // has al
ready been installed miscellaneous domstring random(in long numbytes); unimplementedyou can use window.crypto.getrandomvalues instead.
Basics - Archive of obsolete content
blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring on
ready()when the inherited document is fully loaded.
Me - Archive of obsolete content
note that this mechanism is independent of the first-run page; in particular, the callback is not a load event listener or jquery
ready callback.
Jetpack Snippets - Archive of obsolete content
ppendchild(firebug); (function(){if(window.firebug.version){firebug.init();}else{settimeout(arguments.callee);}})();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebug onselect: function(slide) { slide.slide(800, true); }}); calling into a slidebar from the global jetpack scope jetpack.slidebar.append({ on
ready: function (slide) { // call out to a global function, passing the slidebar object exinitslidebar(slide); }, ...});function exinitslidebar(aslidebar) { // this variable will now be global slider = aslidebar;} // then, accessing the slidebar htmlvar tl = slider.contentdocument.getelementbyid("thumblist"); // or calling slidebar api methods or accessing propertiesslider.notify(); ...
Simple Storage - Archive of obsolete content
jetpack.future.import("menu");jetpack.future.import("selection");jetpack.future.import("storage.simple");// create the persistent notes array if it doesn't al
ready exist.jetpack.storage.simple.notes = jetpack.storage.simple.notes || [];var notes = jetpack.storage.simple.notes;// updates the jetpack menu with the current notes.
Monitoring downloads - Archive of obsolete content
omponents.interfaces.nsifile); this.dbfile.append("downloadlogger.sqlite"); // get access to the storage service and open the database this.storageservice = components.classes["@mozilla.org/storage/service;1"] .getservice(components.interfaces.mozistorageservice); var dbconn = this.storageservice.opendatabase(this.dbfile); // now create the table; if it al
ready exists, this fails, but we don't care!
Supporting per-window private browsing - Archive of obsolete content
var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(function (asubject, atopic, adata) { asubject.queryinterface(components.interfaces.nsisupportsprbool); // if another extension has not al
ready canceled entering the private mode if (!asubject.data) { /* you should display some user interface here */ asubject.data = true; // cancel the operation } }, "last-pb-context-exiting", false); forcing a channel into private mode usually, network channels inherit the privacy status of the document that created them, which means that they work correctly most of the time.
Supporting private browsing mode - Archive of obsolete content
tification with the subject "exit", and set its data field to true to cancel the operation, like this: var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(function (asubject, atopic, adata) { asubject.queryinterface(components.interfaces.nsisupportsprbool); // if another extension has not al
ready canceled entering the private mode if (!asubject.data) { if (adata == "exit") { // if we are leaving the private mode /* you should display some user interface here */ asubject.data = true; // cancel the operation } } }, "private-browsing-cancel-vote", false); note: a well-mannered extension should display some sort of user interface to indicate that private...
How to implement a custom XUL query processor component - Archive of obsolete content
datasource: function(adatasources, arootnode, aistrusted, abuilder, ashoulddelaybuilding) { // todo: parse the adatasources variable // for now, ignore everything and let's just signal that we have data return this._data; }, initializeforbuilding: function(adatasource, abuilder, arootnode) { // perform any initialization that can be delayed until the content builder // is
ready for us to start }, done: function() { // called when the builder is destroyed to clean up state }, compilequery: function(abuilder, aquery, arefvariable, amembervariable) { // outputs a query object.
Namespaces - Archive of obsolete content
it holds and allows disambiguation of items having the same name." if you are familiar with c++ namespaces, java packages, perl packages, or python module importing, you are al
ready familiar with the namespace concept.
Extensions - Archive of obsolete content
you may wish to use these properties instead of determining the type yourself, as the code al
ready handles various special and complex cases that would take a lot of code to deal with manually.
MenuItems - Archive of obsolete content
note that the checked state is updated before the command event fires, so if you use the menuitem's checked attribute within the command listener, it will al
ready be in the new state.
Sorting and filtering a custom tree view - Archive of obsolete content
1 : -1; //if the column is passed and it's al
ready sorted by that column, reverse sort if (column) { columnname = column.id; if (tree.getattribute("sortresource") == columnname) { order *= -1; } } else { columnname = tree.getattribute("sortresource"); } function columnsort(a, b) { if (prepareforcomparison(a[columnname]) > prepareforcomparison(b[columnname])) return 1 * order; if (prepareforcomparison(a[columnname]) < preparefo...
XULRunner tips - Archive of obsolete content
lerules/popupoverlay.xul overlay chrome://inspector/content/commandoverlay.xul chrome://inspector/content/viewers/dom/commandoverlay.xul to launch dom inspector in your application, you need to open its main window, with a command like this: window.open("chrome://inspector/content/inspector.xul", "", "chrome"); alternatively, the dom inspector may also be added as an extension: (if you al
ready have inspector installed for another application you can skip to the next step) follow the instructions above through "unzip the package." create a file in the extensions directory of your application with the same name as the dom inspector id (inspector@mozilla.org) containing one line of text -- the exact path to the root directory of dom inspector (where the install.rdf is) like this one: ...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
req.setrequestheader("method", "post"); < req.setrequestheader("content-length", soapclient.contentlength); < req.setrequestheader("soapserver", soapclient.soapserver); < req.setrequestheader("soapaction", soapreq.action); < } < }); --- > var xhr = new xmlhttprequest(); > xhr.mozbackgroundrequest = true; > xhr.open('post', soapclient.proxy, true); > xhr.on
readystatechange = function() { > if (4 != xhr.
readystate) { return; } > getresponse(xhr); > }; > var headers = { > 'method': 'post', > 'content-type': soapclient.contenttype + '; charset="' + > soapclient.charset + '"', > 'content-length': soapclient.contentlength, > 'soapserver': soapclient.soapserver, > 'soapaction': soapreq.action > }; > for (var h in he...
What XULRunner Provides - Archive of obsolete content
the following features are either al
ready implemented or planned: gecko features xpcom networking gecko rendering engine dom editing and transaction support (no ui) cryptography xbl (xbl2 planned) xul svg xslt xml extras (xmlhttprequest, domparser, etc.) web services (soap) auto-update support (not yet complete) type ahead find toolbar history implementation (the places implementation in the 1.9 cycle) accessibility support ipc services for communication between gecko-based apps (not yet complete) storage/sqlite interfaces user interface features the following user interface is supplied by xulr...
calICalendarViewController - Archive of obsolete content
modifyoccurrence void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); the modifyoccurrence method is used to change the attributes of an al
ready existing caliitem.
2006-11-10 - Archive of obsolete content
important dates: technical submissions: monday 19th feb 2007 technical paper notification: friday 16th march 2007 communication submissions: monday 26th march 2007 communication paper notification: friday 06th april 2007 all camera
ready due: monday 16th april 2007 conference dates: monday 07th and tuesday 08th may 2007 notable keynotes representatives from w3c, ibm, university of manchester, uk and oxford brookes university, uk.
2006-10-13 - Archive of obsolete content
user questions about a open/saveas bug that al
ready exisits: https://bugzilla.mozilla.org/show_bug.cgi?id=347230 installer for 2.0rc2 ehume gives the developers a thumbs up for the new installer for 2.0rc2 having a textfield where you can type in the installation directory.
Table Reflow Internals - Archive of obsolete content
nt=445 block 03017e08 d=1695,300 cell 03017da8 d=1755,360 cell 0301a8cc r=2 a=2625,uc c=2565,uc cnt=446 block 0301a92c r=2 a=2565,uc c=2565,uc cnt=447 block 0301a92c d=2565,300 cell 0301a8cc d=2625,360 row 03017c08 d=4470,360 rowg 03017a7c d=4470,360 tbl 030178c4 d=4500,450 tblo 030176cc d=4500,450 table reflow optimizations if the table is al
ready balanced, pass 1 constrains the width (like a normal pass 2) based on the current column widths.
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
if you haven't al
ready created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension localizing an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension.
Using workers in extensions - Archive of obsolete content
if you haven't al
ready created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension localizing an extension updating an extension to support multiple mozilla applications download the sample you may download the complete example: download the example.
Enumerator.atEnd - Archive of obsolete content
method is used to determine if the end of a list of drives has been reached: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.is
ready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not
ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the follow...
Enumerator.item - Archive of obsolete content
example function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.is
ready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not
ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the follow...
Enumerator.moveFirst - Archive of obsolete content
d to evaluate members of the drivescollection from the beginning of the list: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.is
ready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not
ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the follow...
Enumerator.moveNext - Archive of obsolete content
e movenext method is used to move to the next drive in the drives collection: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.is
ready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not
ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the follow...
Enumerator - Archive of obsolete content
example the following code shows the usage of the enumerator object: var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); document.write(fso.drives); var e = new enumerator(fso.drives); var drivestring = ""; e.movefirst(); while (e.atend() == false) { var drv = e.item(); drivestring += drv.path + " - "; if (drv.is
ready){ var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; drivestring += freegb.tofixed(3) + " gb free of "; drivestring += totalgb.tofixed(3) + " gb"; } else{ drivestring += "not
ready"; } drivestring += "<br />";; e.movenext(); } document.write(drivestring); // output: <drive information properties the...
GetObject - Archive of obsolete content
for example: myobject.line(9, 90); myobject.inserttext(9, 100, "hello, world."); myobject.saveas("c:\\drawings\\sample.drw"); note: use the getobject function when there is a current instance of the object, or if you want to create the object with a file al
ready loaded.
Mozilla XForms Specials - Archive of obsolete content
if you are wondering why we have this restriction, here is a simple example of why: <xforms:model> <xforms:instance src="http://intranetserver/addrbook.xml"/> <xforms:submission id="sub" action="http://megaspammer.com/gather" method="post"/> <xforms:send submission="sub" ev:event="xforms-
ready"/> </xforms:model> this imaginary would fetch something that is only accessible for you (f.x.
Mozilla's DOCTYPE sniffing - Archive of obsolete content
quirks mode the following trigger quirks mode (this list needs to be comprehensive to ensure that pages al
ready existing on the web trigger quirks mode): the following sites have been useful in preparing this list: w3c html validator, htmlhelp html validator.
XUL Parser in Python - Archive of obsolete content
or, since the dictionary is al
ready storing the values of all the attributes it finds, you can write the values of a particular attribute (e.g., id) to the results file by checking the attribute in sys.argv[1]: for attr in a.keys(): if strip(attr) == sys.argv[1]: el_list[name][strip(attr)] = strip(a[attr]) and writing thevalues to the html results file instead of thekeys: for item in elements: w.write('<tr><td class="h...
Game monetization - Game development
add-ons and dlcs add-ons and downloadable content are a good way to provide extra value to an al
ready released game, but remember that you'll have to offer decent, entertaining content to attract people to buy it.
Game promotion - Game development
and you can use your own game as an example, especially in a tutorial when you're showing how to do something you've implemented al
ready.
Desktop mouse and keyboard controls - Game development
that way, if you al
ready implemented the buttons as shown in the mobile touch controls article, it will work out of the box on the desktop too: var buttonenclave = this.add.button(10, 10, 'logo-enclave', this.clickenclave, this); the button will be placed ten pixels from the top left corner of the screen, use the logo-enclave image, and will execute the clickenclave() function when clicked.
Introduction to CSS layout - Learn web development
overview: css layout next this article will recap some of the css layout features we've al
ready touched upon in previous modules — such as different display values — and introduce some of the concepts we'll be covering throughout this module.
Practical positioning examples - Learn web development
first, add the following rule at the bottom of your css to remove the default padding-left and margin-top from the unordered list: .info-box ul { padding-left: 0; margin-top: 0; } note: we are using descendant selectors with .info-box at the start of the chain throughout this example — this is so that we can insert this feature into a page with other content al
ready on it, without fear of interfering with the styles applied to other parts of the page.
Supporting older browsers - Learn web development
couple this information with the knowledge that browsers ignore css that they don’t understand, and you have a way to create simple layouts using the legacy techniques we have al
ready covered, which are then overwritten by your grid layout in modern browsers that understand it.
CSS FAQ - Learn web development
the use of such properties on production websites is not recommended — they have al
ready created a huge web compatibility mess.
Styling lists - Learn web development
in our finished example, we have styled the unordered list like so (on top of what you've al
ready seen above): ul { padding-left: 2rem; list-style-type: none; } ul li { padding-left: 2rem; background-image: url(star.svg); background-position: 0 0; background-size: 1.6rem 1.6rem; background-repeat: no-repeat; } here we've done the following: set the padding-left of the <ul> down from the default 40px to 20px, then set the same amount on the list items.
Web fonts - Learn web development
you've reached the end of this article, and al
ready did some skill testing in our active learning sections, but can you remember the most important information going forward?
Styling text - Learn web development
get started prerequisites before starting this module, you should al
ready have basic familiarity with html, as discussed in the introduction to html module, and be comfortable with css fundamentals, as discussed in introduction to css.
Introducing asynchronous JavaScript - Learn web development
e here, and see the source): const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); in this block, the lines are executed one after the other: we grab a reference to a <button> element that is al
ready available in the dom.
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
they will define the start time if it is not defined al
ready (this will only happen on the first loop iteration), and set the rotatecount to a value to rotate the spinner by (the current timestamp, take the starting timestamp, divided by three so it doesn't go too fast): if (!starttime) { starttime = timestamp; } rotatecount = (timestamp - starttime) / 3; below the previous line inside draw(), add the following block — this checks to ...
Build your own function - Learn web development
const panel = document.createelement('div'); panel.setattribute('class', 'msgbox'); html.appendchild(panel); the next two sections make use of the same createelement() and appendchild() functions we've al
ready seen to create two new elements — a <p> and a <button> — and insert them in the page as children of the panel <div>.
Basic math in JavaScript — numbers and operators - Learn web development
we have al
ready used the most basic one, =, loads of times — it simply assigns the variable on the left the value stated on the right: let x = 3; // x contains the value 3 let y = 4; // y contains the value 4 x = y; // x now contains the same value y contains, 4 but there are some more complex types, which provide useful shortcuts to keep your code neater and more efficient.
Getting started with React - Learn web development
this is the same as the class attribute in html, but because jsx is javascript, we can't use the word class — it's reserved, meaning javascript al
ready uses it for a specific purpose and it would cause problems here in our code.
Componentizing our Svelte app - Learn web development
code along with us git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/04-componentizing-our-app or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app remember to run npm install && npm run dev to start your app in development mode.
Getting started with Svelte - Learn web development
the code so far git clone the github repo (if you haven't al
ready done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/01-getting-started or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/01-getting-started remember to run npm install && npm run dev to start your app in development mode.
Accessibility API cross-reference
the roles it specifies have al
ready informed the 'semantic elements' of html5 (such as main and footer), but there is not a one-to-one mapping between the aria roles and the semantics of html5.
Software accessibility: Where are we today?
ensure correct keyboard accessibility when developing new controls: mozilla's xul and html widgets al
ready support proper keyboard accessibility, so let's not regress in that area.
Theme concepts
, } }, 'night': { images: { theme_frame: 'moon.jpg', }, colors: { frame: '#000', tab_background_text: '#fff', } } }; the theme.theme object is then passed to theme.update() to change the header theme, as in this code snippet from the same example: function settheme(theme) { if (currenttheme === theme) { // no point in changing the theme if it has al
ready been set.
Adding a new CSS property
also, it's very important not to touch the computed style data at all when there's no specified data provided (ecssunit_null); touching the computed style data in this case would break partial computation based on a start struct, which is when we computed style data on the basis of computed data we've al
ready computed from a subset of the style rules that we're currently computing from.
A bird's-eye view of the Mozilla framework
suppose the client al
ready has an nsirdfdatasource object representing a sub-graph of an rdf graph and calls nsirdfdatasource.gettarget(resource, nc_link, true) to obtain an nsirdfnode representing a specific node in the graph, in this case a link to ahelp viewer document page.
Bugzilla
how to tell if a bug has al
ready been reported it's useful (but not mandatory) for you to check if the problem you're reporting has been al
ready tracked.
Building SpiderMonkey with UBSan
/bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then echo "directory $1 al
ready exists" else autoconf2.13 autoconf213 mkdir $1 cd $1 llvm_root="$home/llvm" sanflag="-fsanitize=undefined -fno-sanitize=alignment,float-cast-overflow,float-divide-by-zero,vptr -dxmalloc=myxmalloc" \ cc="$llvm_root/build/release+asserts/bin/clang" \ cxx="$llvm_root/build/release+asserts/bin/clang++" \ cflags="$sanflag" \ cxxflags="$sanflag" \ moz_llvm_hacks=1 \ ../configure --enable-debug --disable-optimize make -j 8 fi 3.
Chrome registration
gecko 1.9.2 note the contents.rdf manifest format is no longer supported at all starting with gecko 1.9.2; add-ons al
ready installed using this format will continue to work but can no longer be installed.
Debugging on Windows
you can click "start" button to run firefox then, al
ready attached in the debugger.
Simple Thunderbird build
do not copy mapi.h, it is al
ready in c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\mapi.h.
pymake
this should come back with "no makefile found." if it does, your pymake alias is connected and you are
ready to type in pymake -f client.mk to start the build.
SVG Guidelines
most of time, cdata isn't needed, for example, the content in <style> tags doesn't need to be wrapped in a cdata section as the content inside the tag is al
ready correctly parsed as css.
Developer guide
this guide provides information that will not only help you get started as a mozilla contributor, but that you'll find useful to refer to even if you are al
ready an experienced contributor.
Firefox UI considerations for web developers
providing a top sites
ready icon the simple rule is to provide an icon which is at least 96x96 pixels in size, using a <link> element whose rel attribute is a reference to a file containing an icon of a supported type.
MozBeforePaint
whenever you're
ready to refresh your animation, you call the window.requestanimationframe() method.
NetUtil.jsm
}); remarks note: if you specify an nsichannel as the input source, and its notification callbacks have al
ready been set, callers are responsible for implementing nsibadcertlistener and nsisslerrorlistener.
OSFile.jsm
from a worker thread in some cases, the main thread api for os.file is not appropriate as it would require too much message passing, or because the code that requires file i/o is al
ready executed on a worker thread.
PopupNotifications.jsm
only one notification for each id can be visible at a time; if one with the specified id al
ready exists, it will be replaced with the newer notification.
PromiseWorker.jsm
main thread file the basepromiseworker object needs to be imported: const { utils: cu } = components; const { basepromiseworker } = cu.import('resource://gre/modules/promiseworker.jsm', {}); let myworker = new basepromiseworker('path_to_worker_file.js'); you're now
ready to start using promiseworker.
Sqlite.jsm
if the original connection is al
ready read-only, the clone will be, regardless of this option.
Task.jsm
if you specify anything else, you get a promise that is al
ready fulfilled with the specified value.
Webapps.jsm
importing components.utils.import("resource://gre/modules/webapps.jsm"); // exported symbol is domapplicationregistry method overview init: function() loadcurrentregistry: function() notifyappsregistrystart: function notifyappsregistrystart() notifyappsregistry
ready: function notifyappsregistry
ready() sanitizeredirects: function sanitizeredirects(asource) _savewidgetsfullpath: function(amanifest, adestapp) appkind: function(aapp, amanifest) updatepermissionsforapp: function(aid, aispreinstalled) updateofflinecacheforapp: function(aid) installpreinstalledapp: function installpreinstalledapp(aid) removeifhttpsduplicate: function(aid) installsystemapps: functio...
Localizing with Mercurial
comm-central contains the files for seamonkey and thunderbird which are not al
ready part of firefox.
Translation phase
the l10n tools are meant to help you maintain your localized content from release to release and leverage al
ready localized materials when localizing new content.
Localization formats
as every new web-dev project takes shape, a project manager should ask themselves these questions and have the answers
ready before starting the web l10n process.
Setting up the infrastructure
copy the shell scripts from /addons/trunk/site/app/locale/ to your locale directory: extract-po.sh will be used to extract all english strings from your application's directories specified in source_dirs, merge the resulting template (*.pot) file with the existing (al
ready containing translations) messages.po files for each locale (if they exist) and merge the new messages.po files to messages.mo files.
Fonts for Mozilla's MathML engine
on debian/ubuntu/mint and other debian-based distributions, use the following command: sudo apt-get install fonts-lmodern fonts-stix on fedora and other fedora-based distributions, use the following command (stix-math-fonts is often al
ready installed): sudo dnf install texlive-lm-math stix-math-fonts on opensuse and other opensuse-based distributions, use the following command: sudo zypper install texlive-lm-math stix-fonts on other linux distributions, consider installing appropriate texlive packages, which includes latin modern math and xits: sudo pacman -s texlive-core texlive-fontsextra # arch linux sudo urpmi texlive-dist ...
MathML In Action
you al
ready have a mathml-enabled build but what you see on the screenshot is not what you get?
Mozilla Development Tools
bugzilla bugzilla is where developers can report bugs in the mozilla source releases, and browse an online database of al
ready-reported bugs.
mozilla::MonitorAutoEnter
constructors monitorautoenter( in mozilla::monitor& monitor; ); this parameter is a reference so as to guarantee that your code has al
ready properly constructed the mozilla::monitor.
mozilla::MutexAutoLock
constructors mutexautolock( in mozilla::mutex& lock; ); this parameter is a reference so as to guarantee that your code has al
ready properly constructed the mozilla::mutex.
mozilla::MutexAutoUnlock
constructors mutexautounlock( in mozilla::mutex& lock; ); this parameter is a reference so as to guarantee that your code has al
ready properly constructed the mozilla::mutex.
DMD
building and running nightly firefox the easiest way to use dmd is with the normal nightly firefox build, which has dmd al
ready enabled in the build.
Intel Power Gadget
note: the power profiling overview is worth reading at this point if you haven't al
ready.
JS::PerfMeasurement
counter values are accumulated across many start/stop cycles, and you can modify their values if you want; stop simply adds counts read back from the os to whatever is al
ready in each counter.
Memory reporting
other considerations a number of the existing basic data structures al
ready have sizeof{in,ex}cludingthis functions, e.g.
TimerFirings logging
note: the power profiling overview is worth reading at this point if you haven't al
ready.
dtrace
note: the power profiling overview is worth reading at this point if you haven't al
ready.
perf
note: the power profiling overview is worth reading at this point if you haven't al
ready.
powermetrics
note: the power profiling overview is worth reading at this point if you haven't al
ready.
tools/power/rapl
note: the power profiling overview is worth reading at this point if you haven't al
ready.
turbostat
note: the power profiling overview is worth reading at this point if you haven't al
ready.
Patches and pushes
note that if your team selects a local version of an al
ready default plugin (e.g., wikipedia), the xml filename should include the locale code (e.g., wikipedia-es).
Profile Manager
for this reason, if you attempt to launch firefox using profile manager, and it detects that another instance of firefox is al
ready running, it will automatically add the -no-remote argument for you, regardless of whether this launch option was checked.
AsyncTestUtils extended framework
most of the things you will want to do al
ready have helper functions that take care of all of this, so all you need to do is pass their return values through.
Nonblocking IO In NSPR
(note: <tt>pr_poll()</tt> also works with blocking file descriptors, although it is less useful in the blocking io model.) when <tt>pr_poll()</tt> reports that a file descriptor is
ready for some io operation, the central thread invokes that io function on the file descriptor.
Named Shared Memory
shared memory protocol named shared memory functions shared memory protocol using named shared memory functions pr_opensharedmemory creates the shared memory segment, if it does not al
ready exist, or opens a connection with the existing shared memory segment if it al
ready exists.
PL_HashTableAdd
if an entry with the same key al
ready exists in the table, the freeentry function is invoked with the ht_free_value flag.
PRIOMethods
poll test the file descriptor to see if it is
ready for i/o.
PR_CEnterMonitor
if a match is found, then either the calling thread is al
ready in the monitor (and this is a reentrant call) or another thread is holding the monitor's mutex.
PR_Rename
if a file with the new name al
ready exists, pr_rename fails with the error code pr_file_exists_error.
PR_SetErrorText
if there is error text al
ready present in the thread, the previous value is first deleted.
PR_SetThreadPrivate
description if the thread al
ready has non-null private data associated with it, and if the destructor function for the index is known (not null), nspr calls the destructor function associated with the index before setting the new data value.
PR_WaitCondVar
when the condition variable is notified, a thread waiting on that condition moves from the "waiting on condition" state to the "
ready" state.
NSS Certificate Download Specification
if the certificates contain a basicconstraints certificate extension that indicates they are ca certificates, and do not al
ready exist in the local certificate database, they are added as untrusted cas.
Encrypt Decrypt MAC Keys As Session Objects
strcpy(headerfilename, infilename); strcat(headerfilename, ".header"); /* for intermediate encrypted file, choose filename as inputfile name with extension ".enc" */ strcpy(encryptedfilename, infilename); strcat(encryptedfilename, ".enc"); pr_init(pr_user_thread, pr_priority_normal, 0); switch (cmd) { case encrypt: /* if the intermediate header file al
ready exists, delete it */ if (pr_access(headerfilename, pr_access_exists) == pr_success) { pr_delete(headerfilename); } /* if the intermediate encrypted al
ready exists, delete it */ if (pr_access(encryptedfilename, pr_access_exists) == pr_success) { pr_delete(encryptedfilename); } /* open db for read/write and authenticate to it...
Encrypt and decrypt MAC using token
strcpy(headerfilename, infilename); strcat(headerfilename, ".header"); /* for intermediate encrypted file, choose filename as inputfile name with extension ".enc" */ strcpy(encryptedfilename, infilename); strcat(encryptedfilename, ".enc"); pr_init(pr_user_thread, pr_priority_normal, 0); switch (cmd) { case encrypt: /* if the intermediate header file al
ready exists, delete it */ if (pr_access(headerfilename, pr_access_exists) == pr_success) { pr_delete(headerfilename); } /* if the intermediate encrypted al
ready exists, delete it */ if (pr_access(encryptedfilename, pr_access_exists) == pr_success) { pr_delete(encryptedfilename); } /* open db for read/write and authenticate to it...
NSS FAQ
because nss provides complete support for all versions of ssl and tls, it is particularly well-suited for applications that need to communicate with the many clients and servers that al
ready support the ssl protocol.
Introduction to Network Security Services
what you should al
ready know before using nss, you should be familiar with the following topics: concepts and techniques of public-key cryptography the secure sockets layer (ssl) protocol the pkcs #11 standard for cryptographic token interfaces cross-platform development issues and techniques where to find more information for information about pki and ssl that you should understand before using nss, see the f...
Using JSS
using jss newsgroup: mozilla.dev.tech.crypto if you have al
ready built jss, or if you are planning to use a binary release of jss, here's how to get jss working with your code.
NSS 3.16.3 release notes
this function was al
ready added in nss 3.16.2, however, it wasn't declared in a public header file.
NSS 3.16 release notes
it just verifies the signature, assuming that the certificate has been verified al
ready.
NSS 3.28.1 release notes
cn = symantec class 2 public primary certification authority - g6 sha-256 fingerprint: cb:62:7d:18:b5:8a:d5:6d:de:33:1a:30:45:6b:c6:5c:60:1a:4e:9b:18:de:dc:ea:08:e7:da:aa:07:81:5f:f0 the version number of the updated root ca list has been set to 2.11 a misleading assertion/alert has been removed, when nss tries to flush data to the peer but the connection was al
ready reset.
NSS 3.35 release notes
without a prefix, the default database type will be used (dbm in versions prior to 3.35, and sql in version 3.35 and later.) when using the sql type (either explicitly, or because of the new default), with a database directory which al
ready contains a dbm type database, nss will automatically perform a one time migration of the information contained in the dbm files to the newer sql files.
NSS 3.37 release notes
added hacl* poly1305 32-bit the code to support the npn protocol, which had al
ready been disabled in a previous release, has been fully removed.
NSS Developer Tutorial
check with nss-dev@ before using a language feature not al
ready used, if you are uncertain.
NSS Sample Code Sample_3_Basic Encryption and MACing
strcpy(headerfilename, infilename); strcat(headerfilename, ".header"); /* for intermediate encrypted file, choose filename as inputfile name with extension ".enc" */ strcpy(encryptedfilename, infilename); strcat(encryptedfilename, ".enc"); pr_init(pr_user_thread, pr_priority_normal, 0); switch (cmd) { case encrypt: /* if the intermediate header file al
ready exists, delete it */ if (pr_access(headerfilename, pr_access_exists) == pr_success) { pr_delete(headerfilename); } /* if the intermediate encrypted al
ready exists, delete it */ if (pr_access(encryptedfilename, pr_access_exists) == pr_success) { pr_delete(encryptedfilename); } /* open db for read/write and authenticate to it.
NSS Sample Code sample2
h; pk11slotinfo* slot = null; pk11symkey* symkey = null; secitem* secparam = null; pk11context* enccontext = null; secitem keyitem, ivitem; secstatus rv, rv1, rv2; unsigned char data[1024], buf1[1024], buf2[1024]; int i, result_len, tmp1_outlen, tmp2_outlen; /* initialize nss * if your application code has al
ready initialized nss, you can skip it * here.
NSS Sample Code sample3
++) printf("%02x ", digest[i]); cout << endl; } /* * main */ int main(int argc, const char *argv[]) { int status = 0; pk11slotinfo *slot = 0; pk11symkey *key = 0; pk11context *context = 0; unsigned char data[80]; unsigned char digest[20]; /*is there a way to tell how large the output is?*/ unsigned int len; secstatus s; /* initialize nss * if your application code has al
ready initialized nss, you can skip it * here.
EncDecMAC using token object - sample 3
as inputfile name with extension ".header" */ strcpy(headerfilename, infilename); strcat(headerfilename, ".header"); /* for intermediate encrypted file, choose filename as inputfile name with extension ".enc" */ strcpy(encryptedfilename, infilename); strcat(encryptedfilename, ".enc"); pr_init(pr_user_thread, pr_priority_normal, 0); switch (cmd) { case encrypt: /* if the intermediate header file al
ready exists, delete it */ if (pr_access(headerfilename, pr_access_exists) == pr_success) { pr_delete(headerfilename); } /* if the intermediate encrypted al
ready exists, delete it */ if (pr_access(encryptedfilename, pr_access_exists) == pr_success) { pr_delete(encryptedfilename); } /* open db for read/write and authenticate to it.
Build instructions
(the free edition works, and other versions like visual studio 2008 and visual studio 2012 may also work.) use start-shell-msvc2010.bat from mozillabuild to get a bash shell with the path al
ready configured, and execute these instructions from within that bash shell.
FC_InitPIN
ckr_device_error: normal user's pin is al
ready initialized.
FC_Initialize
ckr_cryptoki_al
ready_initialized: the library is al
ready initialized.
NSS_Initialize
nss_init_pk11reload - ignore the ckr_cryptoki_al
ready_initialized error when loading pkcs#11 modules.
NSS Key Functions
when an application makes a copy of a particular certificate or key structure that al
ready exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
NSS tools : modutil
if any of these databases al
ready exist in a specified directory, modutil returns an error message.
gtstd.html
for production deployment, the nss team strongly recommends that you either: use certificates from a competent third-party ca that is al
ready known to your relying party software (e.g.
sslcrt.html
when an application makes a copy of a particular certificate or key structure that al
ready exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
sslkey.html
when an application makes a copy of a particular certificate or key structure that al
ready exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
NSS Tools modutil
if any of these databases al
ready exist in a specified directory, the security module database tool displays an error message.
NSS tools : modutil
if any of these databases al
ready exist in a specified directory, modutil returns an error message.
Installing Pork
apply this patch: note: this doesn't seem necessary in the latest version; cppflags is al
ready an argument.
Pork Tools
var = getter(); // detect ns_ensure_success immediately following // and change it to an equivalent ns_ensure_true ns_ensure_true(var, ns_error_failure); // case 2 var = getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = getter(); ns_ensure_true(var, ns_error_failure) } outparamdel also support rewriting getters such that they return al
ready_addrefed<nsifoo>.
Rhino Examples
implementing host objects first check out the tutorial if you haven't al
ready.
Rhino scopes and contexts
to associate the current thread with a context, simply call the enter method of context: context cx = context.enter(); once you are done with execution, simply exit the context: context.exit(); these calls will work properly even if there is al
ready a context associated with the current thread.
Scripting Java
rhino also makes the javascript methods available to java strings if the java.lang.string class doesn't al
ready define them.
GC Rooting Guide
the usual way is to define a void trace(jstracer* trc, const char* name) method on the class -- which is al
ready enough be able to create a js::rooted<yourstruct> on the stack -- and then arrange for it to be called during tracing.
SpiderMonkey Internals
var sumofdivisors = new exprarray(n + 1, 1); for (var divisor = 2; divisor <= n; divisor++) { for (var j = divisor + divisor; j <= n; j += divisor) { sumofdivisors[j] += " + " + divisor; } // at this point everything up to 'divisor' has its sumofdivisors // expression calculated, so we can determine whether it's perfect // al
ready by evaluating.
JIT Optimization Outcomes
the interpreted callee function has a lazy, compiled on-demand script instead of an al
ready compiled script.
JS_InitStandardClasses
as a side effect, js_initstandardclasses establishes obj as the global object for cx, if one is not al
ready established.
JS_InternString
if an interned string al
ready exists with the desired value, these functions return the existing string.
JS_SetParent
js_setparent has no way to check that this is the case, but nonetheless, applications must not call js_setparent on an object that has al
ready been exposed to a script.
JS_SetPrivate
that object may al
ready be using the private data field for something else; or there might not be a private data field in that object at all, in which case js_setprivate would overwrite an object property.
JS_ValueToFunction
instead, use jsval_is_object and js_objectisfunction() to check whether a value is al
ready a function, or use js_convertvalue() to convert a value to jstype_function safely.
Property attributes
some objects like function/object have self-hosted functions that can only be defined after the initialization is al
ready finished.
JSAPI reference
tub_gsops added in spidermonkey 17 jsfun_constructor added in spidermonkey 17 jsprop_redefine_nonconfigurable added in spidermonkey 38 jsprop_resolving added in spidermonkey 45 jsprop_ignore_enumerate added in spidermonkey 38 jsprop_ignore_readonly added in spidermonkey 38 jsprop_ignore_permanent added in spidermonkey 38 jsprop_ignore_value added in spidermonkey 38 js_al
readyhasownelement added in spidermonkey 1.8 js_al
readyhasownproperty added in spidermonkey 1.8 js_al
readyhasownucproperty added in spidermonkey 1.8 js_al
readyhasownpropertybyid added in spidermonkey 1.8.1 js_defineproperty js_defineucproperty js_definepropertybyid added in spidermonkey 1.8.1 js_defineproperties js_enumerate js_forwardgetpropertyto added in spidermonkey 17 js_forwardgetelemen...
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_al
readyhasownpropertybyid 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_d...
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_al
readyhasownpropertybyid 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_d...
SpiderMonkey 1.8
js_al
readyhasownproperty and friends are new functions for examining an object without triggering resolve hooks.
Shell global objects
return true if obj's [[prototype]] was successfully made immutable (or if it al
ready was immutable), false otherwise.
TPS Tests
the sync_wipe_server argument causes tps to set the firstsync="wipeserver" pref before syncing, in case the sync account al
ready contains data (this is typically unnecessary, and done largely as an example).
Redis Tips
so for a test user account creation and verification service called "persona test user," i have these keys: ptu:nextval an iterator ptu:mailq a queue (list) of incoming verification emails ptu:emails:staging a zset of emails being staged, sorted by creation date ptu:emails:valid a zset of email accounts
ready for use, sorted by creation date ptu:email:<email>:passwd the password for an email account the ptu: prefix makes it extra clear what these keys are for.
Secure Development Guidelines
on handling they free data in try block and then free it again in the catch block this is a common issue double freeing pointers char *ptr1 = null, *ptr2 = null; try { ptr1 = new char[1024]; do_something(); delete ptr1; do_something_else(); ptr2 = new char[-1] // oom } catch (...) { delete ptr1; delete ptr2; } new will throw an exception — ptr1 is al
ready freed in the try block then freed again in the catch block freeing un-initialized data free data in the catch block assumption is that it’s initialized in the try block if the try block throws before the variable is initialized, the catch block will operate on un-intialized data freeing un-initialized data example: int main(){ char *ptr; try { ptr = new char[-1]...
A Web PKI x509 certificate primer
*.yourcompany.com) but you want others outside of your organization to be able to browse to your website using https without having to manually import a root certificate, then you can get an ssl certificate from one of the cas who al
ready have a root certificate included in the major browsers.
XForms Accessibility
currently we have verified that xforms accessibility is working on the windows platform, and linux testing has not yet been done, although everything should work and is
ready to be tested.
History Service Design
if a page can be added we first check if it exists al
ready, then it is added or updated accordingly to the previous check, and common attributes are set based on concurrent visit properties.
Using the Places annotation service
uri's are easier to use for services that want to annotate a web page loaded in the browser, while id's are easier to use for services al
ready working with the places database.
Using the Places history service
if database initialization completes correctly a "places-init-complete" topic is notified, at this point is possible to look for database status: var databasestatus = historyservice.databasestatus; switch (databasestatus) { case historyservice.database_status_ok: // database did al
ready exist and has been correctly initialized.
Using the Places keywords API
placesutils.keywords.insert({ keyword: "my_keyword", url: "http://www.example.com/" postdata: "post+data=1&test=2" }).then(() => { /* success */ }, e => { /* failure */ }); note that setting an al
ready existing keyword to a different url, will silently update the existing keyword to the new url.
extIApplication
supports: "load", "
ready", "quit", "unload" the following interfaces are only available to firefox: attribute type description bookmarks readonly attribute fuelibookmarkroots the root bookmarks object for the application.
Creating a Python XPCOM component
creating applications with mozilla al
ready provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
Generic factory
fine_iid(kifactoryiid, ns_ifactory_iid); ns_impl_isupports(nsgenericfactory, kifactoryiid) ns_imethodimp nsgenericfactory::createinstance(nsisupports *aouter, refnsiid aiid, void **aresult) { return mcreator(aouter, aiid, aresult); } ns_imethodimp nsgenericfactory::lockfactory(prbool alock) { return ns_ok; } many of our classes al
ready have a static entry point that serves as the creator function, so in most cases, creating a new factory for a class is just: nsifactory* newmallocfactory() { nsifactory* factory = new nsgenericfactory(&nsmalloc::create); factory->addref(); return factory; } talking to warren, he suggests that we even provide a shorthand for this, we should be able to register a factory with just a fun...
XPCOM glue
this is the case for xpcom components, because they are loaded into mozilla which al
ready has full xpcom loaded and initialized.
Packaging WebLock
n be read and executed */ function installweblock() { weblock_xpi = {'weblock extension': 'weblock.xpi'}; installtrigger.install(weblock_xpi); } </script> <h1>install weblock</h1> <p><a href="#" onclick="installweblock();">install weblock</a></p> </html> distributing your component once you have the component packaged properly and the necessary installation and trigger scripts, you are
ready to distribute your component so others can install it in their gecko applications.
Using XPCOM Components
« previousnext » one of the best ways to begin working with xpcom - especially when you are designing the interface to a component that will be used by others, as we do in starting weblock - is to look at how clients are al
ready using xpcom components.
Making cross-thread calls using runnables
so we declare an asynchronous version of the same function: typedef void (*picallback)(const nscstring& result); // callback function void calculatepiasynchronously(int digits, picallback callback); creating a runnable nsrunnable is a helper class: it al
ready implements threadsafe refcounting, so all you need to do is override the run() function.
Detailed XPCOM hashtable guide
the mozilla codebase al
ready contains hash functions for most key types, including narrow and wide strings, pointers, and most binary data: void* (or nsisupports*) cast using ns_ptr_to_int32 char* string nscrt::hashcode() prunichar* string nsastring hashstring() nsacstring nsid& nsidhashkey::hashkey() writing a good hash function is well beyond the...
Components.ID
the exception to this is the case where a component is written in javascript and needs to register itself with the component manager using its own nsid - an id that is not al
ready registered and thus does not appear in components.classes.
Components.utils.evalInWindow
the result is structured cloned back to the original context, unless it is native (for example, if it returns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper al
ready), so it's guaranteed to behave predictably.
Using components
commonly, we start our scripts like so: var cc = components.classes; var ci = components.interfaces; if we want to get a hold of a component, we then do something like: var rc = cc["@mozilla.org/registry;1"]; var rs = rc.getservice(ci.nsiregistry); see also: xpcshell -- how to get a command line interface to javascript more info as was al
ready stated, it is common to start addon scripts like: var cc = components.classes; var ci = components.interfaces; there is also another way to start, which is exactly equivalent to the above.
Language bindings
the result is structured cloned back to the original context, unless it is native (for example, if it returns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper al
ready), so it's guaranteed to behave predictably.
NS_OVERRIDE
example class a has a method getfoo() which is overridden by class b: class a { virtual nsresult getfoo(nsifoo** aresult); }; class b : public a { ns_override virtual nsresult getfoo(nsifoo** aresult); }; later, the signature of a::getfoo() is changed to remove the output parameter: class a { - virtual nsresult getfoo(nsifoo** aresult); + virtual al
ready_addrefed<nsifoo> getfoo(); }; b::getfoo() no longer overrides a::getfoo() as was originally intended.
nsFixedCString
methods constructors void nsfixedcstring(char*, pruint32) - source @param data fixed-size buffer to be used by the string (the contents of this buffer may be modified by the string) @param storagesize the size of the fixed buffer @param length (optional) the length of the string al
ready contained in the buffer parameters char* data pruint32 storagesize void nsfixedcstring(char*, pruint32, pruint32) - source parameters char* data pruint32 storagesize pruint32 length operator= nscstring& operator=(const nscstring&) - source parameters nscstring& str nsacstring_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*)...
nsFixedString
methods constructors void nsfixedstring(prunichar*, pruint32) - source @param data fixed-size buffer to be used by the string (the contents of this buffer may be modified by the string) @param storagesize the size of the fixed buffer @param length (optional) the length of the string al
ready contained in the buffer parameters prunichar* data pruint32 storagesize void nsfixedstring(prunichar*, pruint32, pruint32) - source parameters prunichar* data pruint32 storagesize pruint32 length operator= nsstring& operator=(const nsstring&) - source parameters nsstring& str nsastring_internal& operator=(prunichar) - source parameters prunichar c nsastring_internal& ope...
IAccessibleText
s_false if the object is al
ready at the specified location.
nsIHttpServer
* * @param port * the port upon which listening should happen, or -1 if no specific port is * desired * @throws ns_error_al
ready_initialized * if this server is al
ready started * @throws ns_error_not_available * if the server is not started and cannot be started on the desired port * (perhaps because the port is al
ready in use or because the process does * not have privileges to do so) * @note * behavior is undefined if this method is called after stop() has been * called on this but bef...
nsIINIParserWriter
when you're done and
ready to write the ini file to disk, call the writefile() method.
nsILocalFile
if the file al
ready exists, no action and null is returned.
nsILoginManager
exceptions thrown an exception is thrown if the login information is al
ready stored in the login manager.
nsIMicrosummaryService
the set might change after this method returns, since this method will trigger an asynchronous load of the page in question (if it isn't al
ready loaded) to see if it references any page-specific microsummaries.
nsIMsgAccount
exceptions thrown ns_error_al
ready_opened if it is called more then once removeidentity() removes an identity from this account.
nsINavHistoryService
if the uri does not have an entry in the history database al
ready, one will be created with no visits, no title, hidden, not typed.
nsINetworkLinkService
for example, the link is down during dhcp configuration (unless there is another usable interface al
ready configured).
nsIObserver
s.interfaces.nsiobserverservice); observerservice.addobserver(this, "mytopicid", false); }, unregister: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "mytopicid"); } } instantiation - this should be fired once you're
ready to start observing (for example a window's load event).
nsIPipe
the pipe supports nsiasyncinputstream and nsiasyncoutputstream, which give the user of a non-blocking pipe the ability to wait for the pipe to become
ready again.
nsIPluginHost
it may or may not be al
ready opened when this function is called.
nsIProcessScriptLoader
for example data:,dump("foo\n"); aallowdelayedload boolean if this flag is false, the process script will only be loaded into child processes that are al
ready running at the time of the call.
nsIWebProgress
ns_error_failure indicates that alistener was al
ready registered.
nsIWebSocketChannel
note: implementations should throw ns_error_al
ready_opened if the websocket connection is reopened.
nsIWebappsSupport
isapplicationinstalled() checks is a web application is al
ready installed.
nsIWinAppHelper
returns true only if all the following conditions are all true at once: the operating system is at least windows vista user account control is enabled the user is an administrator the application is not al
ready running with elevated permissions otherwise it returns false.
nsIWinTaskbar
fails if a jump list build operation has al
ready been initiated, developers should make use of a single instance of nsijumplistbuilder for building lists within an application.
nsIWindowMediator
getting most recent window the following code is useful when you need any of the windows of given type, or to check if a window of a particular type (for example your extension's options dialog) is al
ready open.
nsIXMLHttpRequest
the 'onload', 'onerror', and 'on
readystatechange' attributes moved to nsijsxmlhttprequest, but if you're coding in c++ you should avoid using those.
nsIXULTemplateBuilder
the default conditions specified inside the <rule> tag are applied before the rule filter is applied, meaning that the filter may be used to further filter out results but not reaccept results that have al
ready been rejected.
Frequently Asked Questions
any xpcom function that returns an interface pointer, i.e., a `getter', must have al
ready addrefed that pointer.
Using nsIDirectoryService
customizing the locations is important if, for example, your application al
ready has a profile directory or other resource directories.
Using the Gecko SDK
introduction it is assumed that you al
ready know something about xpcom component development.
XPCOM ownership guidelines
such a function is the perfect example of something that creates an object with a longer lifespan that itself, and gives away ownership (by producing a pointer that is al
ready addrefed) --- in this case, to the caller.
XPCOM tasks
a first step is moving all qi implementations to the table-like macros al
ready in place (and some slight modifications to those macros).
XPIDL
finally, as an exception to everything al
ready mentioned, for attribute getters and setters the jscontext *cx comes before any other arguments.
Account Provisioner
if the user al
ready has an email account, the user can switch to the original account setup wizard.
nsIMsgCloudFileProvider
managementurl acstring readonly: a chrome url for an xhtml page displayed within the filelink preferences dialog, used for displaying and setting provider-specific settings once the account has al
ready been set up.
LDAP Support
it assumes you are al
ready familiar with configuring preferences for deployed builds in addition to setting up thunderbird to use an ldap directory.
Mail composition back end
const struct nsmsgattachedfile *preloaded_attachments, - attachments that are al
ready locally stored on disk (note: both attachments and preloaded_attachments cannot be specified on a single call void *relatedpart /* nsmsgsendpart */, - a related part for multipart related operations nsimsgsendlistener **alistenerarray) = 0; - an array of listeners for the send operation.
Main Windows
you’ll sometimes see reimplementations of things that are al
ready in toolkit, written specially for thunderbird.
Demo Addon
let query = gloda.newquery(gloda.noun_message); query.subjectmatches(searchterm); let mylistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function mylistener_onitemsadded(aitems, acollection) { }, /* called when items that are al
ready in our collection get re-indexed */ onitemsmodified: function mylistener_onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function mylistener_onitemsremoved(aitems, acollection) { }, /* called when our database query completes */ onquerycompleted: function mylistener_onquerycompleted...
customDBHeaders Preference
some of the functionality described here is really new, so please try to be understanding if some of these things change tomorrow (or have changed al
ready).
Using Objective-C from js-ctypes
typedef struct objc_selector *sel; in this example, we need to send alloc, its selector can be retrieved with the following code: sel alloc = sel_registername("alloc"); sending a message once target class and selector are
ready, you can send a message.
Declaring types
types are declared in terms of other, al
ready defined types.
Initialization and Destruction - Plugins
during initialization, when the browser encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it loads the plug-in code into memory (if it hasn't been loaded al
ready) and creates a new instance of the plug-in.
Gecko Plugin API Reference - Plugins
npp_destroy npp_destroystream npp_getvalue np_getvalue npp_handleevent np_initialize npp_new npp_newstream npp_print npp_setvalue npp_setwindow np_shutdown npp_streamasfile npp_urlnotify npp_write npp_write
ready browser side plug-in api this chapter describes methods in the plug-in api that are available from the browser.
Accessibility Inspector - Firefox Developer Tools
accessing the accessibility inspector when you first open any of the other developer tools, the accessibility features are turned off (unless you've al
ready got them turned on in another browser tab, or got the firefox accessibility engine started al
ready, e.g., you might be a screenreader user or tester).
All keyboard shortcuts - Firefox Developer Tools
clear search box content (only when the search box is focused, and content has been entered) esc esc esc step forward through properties and values tab tab tab step backward through properties and values shift + tab shift + tab shift + tab start editing property or value (rules view only, when a property or value is selected, but not al
ready being edited) enter or space return or space enter or space cycle up and down through auto-complete suggestions (rules view only, when a property or value is being edited) up arrow , down arrow up arrow , down arrow up arrow , down arrow choose current auto-complete suggestion (rules view only, when a property or value is being edited) enter or tab return...
Examine and edit HTML - Firefox Developer Tools
use in console assigns the currently selected node to a variable named temp0 (or temp1 if temp0 is al
ready taken, and so on), then opens the split console, enabling you to interact with that node using the console's command line.
Page inspector keyboard shortcuts - Firefox Developer Tools
clear search box content (only when the search box is focused, and content has been entered) esc esc esc step forward through properties and values tab tab tab step backward through properties and values shift + tab shift + tab shift + tab start editing property or value (rules view only, when a property or value is selected, but not al
ready being edited) enter or space return or space enter or space cycle up and down through auto-complete suggestions (rules view only, when a property or value is being edited) up arrow , down arrow up arrow , down arrow up arrow , down arrow choose current auto-complete suggestion (rules view only, when a property or value is being edited) enter or tab return...
Intensive JavaScript - Firefox Developer Tools
console.log(message.data.primes); worker.removeeventlistener("message", handleworkercompletion); } } worker.addeventlistener("message", handleworkercompletion, false); worker.postmessage({ "multiplier": multiplier, "iterations": iterations }); } the main difference here, compared with the original, is that we need to: create a worker send it a message when we are
ready to calculate listen for a message called "done", which indicates that the worker has finished.
Waterfall - Firefox Developer Tools
for example, consider code like this: var timerbutton = document.getelementbyid("timer"); timerbutton.addeventlistener("click", handleclick, false); function handleclick() { console.time("timer"); runtimer(1000).then(timerfinished); } function timerfinished() { console.timeend("timer"); console.log("
ready!"); } function runtimer(t) { return new promise(function(resolve) { settimeout(resolve, t); }); } the waterfall will display a marker for the period between time() and timeend(), and if you select it, you'll see the async stack in the sidebar: timestamp markers timestamps enable you to mark an instant in the recording.
Animation - Web APIs
animation.
ready read only returns the current
ready promise for this animation.
Attr - Web APIs
the assumption was that since you get an attr object from an element, you should al
ready know the associated element.
AudioNode.connect() - Web APIs
an audioparam will take the rendered audio data from any audionode output connected to it and convert it to mono by down-mixing (if it is not al
ready mono).
AudioNode - Web APIs
audionode.disconnect() allows us to disconnect the current node from another one it is al
ready connected to.
AudioParam.setTargetAtTime() - Web APIs
depending on your use case, getting 95% toward the target value may al
ready be enough; in that case, you could set timeconstant to one third of the desired duration.
AudioProcessingEvent - Web APIs
the web audio api audioprocessingevent represents events that occur when a scriptprocessornode input buffer is
ready to be processed.
AudioScheduledSourceNode.start() - Web APIs
if no value is passed then the duration will be equal to the length of the audio buffer minus the offset value return value undefined exceptions invalidstatenode the node has al
ready been started.
AudioWorkletGlobalScope - Web APIs
// test-processor.js class testprocessor extends audioworkletprocessor { constructor () { super() // current sample-frame and time at the moment of instantiation // to see values change, you can put these two lines in process method console.log(currentframe) console.log(currenttime) } // the process method is required - simply output silence, // which the outputs are al
ready filled with process (inputs, outputs, parameters) { return true } } // the sample rate is not going to change ever, // because it's a read-only property of a baseaudiocontext // and is set only during its instantiation console.log(samplerate) // you can declare any variables and use them in your processors // for example it may be an arraybuffer with a wavetable const usefulvariable = 4...
AuthenticatorResponse.clientDataJSON - Web APIs
it has two properties: status: a string which is either "supported" which indicates the client support token binding but did not negotiate with the relying party or "present" when token binding was used al
ready id: a domstring which is the base64url encoding of the token binding id which was used for the communication.
BatteryManager.chargingTime - Web APIs
syntax var time = battery.chargingtime on return, time is the remaining time in seconds until the battery, which is a batterymanager object, is fully charged, or 0 if the battery is al
ready fully charged.
BatteryManager - Web APIs
batterymanager.chargingtime read only a number representing the remaining time in seconds until the battery is fully charged, or 0 if the battery is al
ready fully charged.
Bluetooth - Web APIs
bluetooth.getdevices() returns a promise that resolved to an array of bluetoothdevices which the origin al
ready obtained permission for via a call to bluetooth.requestdevice().
Body.arrayBuffer() - Web APIs
once getdata() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is al
ready playing (this would cause an error.) function getdata() { source = audioctx.createbuffersource(); var myrequest = new request('viper.ogg'); fetch(myrequest).then(function(response) { return response.arraybuffer(); }).then(function(buffer) { audioctx.decodeaudiodata(buffer, function(decodeddata) { source.buffer = decodeddata; source.connect(audioctx.destination); ...
CSSOMString - Web APIs
while browser implementations that use utf-8 internally to represent strings in memory can use usvstring when the specification says cssomstring, implementations that al
ready represent strings as 16-bit sequences might choose to use domstring instead.
CSSStyleSheet - Web APIs
as the stylesheet list cannot be modified directly, there's no useful way to create a new cssstylesheet object manually (although constructable stylesheet objects is coming to the web platform soon and is al
ready supported in blink).
Using dynamic styling information - Web APIs
var el = document.getelementbyid('some-element'); el.setattribute('style', 'background-color:darkblue;'); be aware, however, that setattribute removes all other style properties that may al
ready have been defined in the element's style object.
Cache - Web APIs
the code then uses cache.match() to see if there's al
ready a matching font in the cache, and if so, returns it.
CacheStorage - Web APIs
cachestorage.open() returns a promise that resolves to the cache object matching the cachename (a new cache is created if it doesn't al
ready exist.) cachestorage.delete() finds the cache object matching the cachename, and if found, deletes the cache object and returns a promise that resolves to true.
CanvasRenderingContext2D.addHitRegion() - Web APIs
(if you don't see the full smiley, check the browser compatibility table to see if your current browser supports hit regions al
ready; you might need to activate a preference.) playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:250px"> ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi, fal...
CanvasRenderingContext2D.font - Web APIs
let f = new fontface('test', 'url(x)'); f.load().then(function() { //
ready to use the font in a canvas context }); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.font' in that specification.
CanvasRenderingContext2D.getTransform() - Web APIs
the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] note: the returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an al
ready returned dommatrix.
A basic ray-caster - Web APIs
after realizing, to my delight, that the nifty <canvas> element i'd been reading about was not only soon to be supported in firefox, but was al
ready supported in the current version of safari, i had to try a little experiment.
Advanced animations - Web APIs
adding velocity now that we have a ball, we are
ready to add a basic animation like we have learned in the last chapter of this tutorial.
Basic animations - Web APIs
the requestanimationframe method provides a smoother and more efficient way for animating by calling the animation frame when the system is
ready to paint the frame.
Drawing text - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.font = '48px serif'; ctx.stroketext('hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); styling text in the examples above we are al
ready making use of the font property to make the text a bit larger than the default size.
Using channel messaging - Web APIs
// handle messages received on port1 function onmessage(e) { output.innerhtml = e.data; input.value = ''; } when a message is received back from the iframe confirming that the original message was received successfully, this simply outputs the confirmation to a paragraph and empties the text input
ready for the next message to be sent.
Client.url - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: 'window' }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status com...
Clients.openWindow() - Web APIs
m' }, }; self.registration.shownotification('you\'ve got messages!', notificationobject); } // notification click event listener self.addeventlistener('notificationclick', e => { // close the notification popout e.notification.close(); // get all the window clients e.waituntil(clients.matchall({ type: 'window' }).then(clientsarr => { // if a window tab matching the targeted url al
ready exists, focus that; const hadwindowtofocus = clientsarr.some(windowclient => windowclient.url === e.notification.data.url ?
Clients - Web APIs
addeventlistener('notificationclick', event => { event.waituntil(async function() { const allclients = await clients.matchall({ includeuncontrolled: true }); let chatclient; // let's see if we al
ready have a chat window open: for (const client of allclients) { const url = new url(client.url); if (url.pathname == '/chat/') { // excellent, let's use it!
ContentIndex.add() - Web APIs
amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.
ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } the add method can also be used within the service worker scope.
ContentIndex.delete() - Web APIs
async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.
ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } the delete method can also be used within the service worker scope.
ContentIndex.getAll() - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.
ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline readin...
CustomElementRegistry.define() - Web APIs
exceptions exception description notsupportederror the customelementregistry al
ready contains an entry with the same name or the same constructor (or is otherwise al
ready defined), or extends is specified and it is a valid custom element name, or extends is specified but the element it is trying to extend is an unknown element.
DOMString - Web APIs
as javascript al
ready uses such strings, domstring is mapped directly to a string.
DataTransferItemList.add() - Web APIs
exceptions notsupportederror a string data parameter was provided, and the list al
ready contains an item whose kind is "plain unicode string" and whose type is equal to the specified type parameter.
Document.fonts - Web APIs
examples doing operation after all fonts are loaded document.fonts.
ready.then(function() { // any operation that needs to be done only after all the fonts // have finished loading can go here.
Document.write() - Web APIs
writing to a document that has al
ready loaded without calling document.open() will automatically call document.open().
Element.accessKey - Web APIs
the element.accesskey property is seldom used because of its multiple conflicts with al
ready present key bindings in browsers.
Element.setAttributeNode() - Web APIs
html <div id="one" align="left">one</div> <div id="two">two</div> javascript let d1 = document.getelementbyid('one'); let d2 = document.getelementbyid('two'); let a = d1.getattributenode('align'); d2.setattributenode(a.clonenode(true)); // returns: 'left' alert(d2.attributes[1].value); notes if the attribute named al
ready exists on the element, that attribute is replaced with the new one and the replaced one is returned.
Event.bubbles - Web APIs
passes the event along if does not passiton(e); } // al
ready bubbling dooutput(e); } note: only certain events can bubble.
Event - Web APIs
if the event has al
ready been dispatched, this method does nothing.
ExtendableMessageEvent - Web APIs
// in the page being controlled if (navigator.serviceworker) { navigator.serviceworker.register('service-worker.js'); navigator.serviceworker.addeventlistener('message', event => { // event is a messageevent object console.log(`the service worker sent me a message: ${event.data}`); }); navigator.serviceworker.
ready.then( registration => { registration.active.postmessage("hi service worker"); }); } the service worker can receive the message by listening to the message event: // in the service worker addeventlistener('message', event => { // event is an extendablemessageevent object console.log(`the client sent me a message: ${event.data}`); event.source.postmessage("hi client"); }); specific...
Using Fetch - Web APIs
both methods of creating a copy will fail if the body of the original request or response has al
ready been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.
Fetch API - Web APIs
aborting a fetch browsers have started to add experimental support for the abortcontroller and abortsignal interfaces (aka the abort api), which allow operations like fetch and xhr to be aborted if they have not al
ready completed.
FileReader.readAsText() - Web APIs
when the read operation is complete, the
readystate is changed to done, the loadend event is triggered, and the result property contains the contents of the file as a text string.
FileSystemFlags.create - Web APIs
syntax filesystemflags.create = booleanvalue values the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path al
ready exists.
FontFace.display - Web APIs
the display property of the fontface interface determines how a font face is displayed based on whether and when it is downloaded and
ready to use.
FontFace - Web APIs
fontface.display a cssomstring that determines how a font face is displayed based on whether and when it is downloaded and
ready to use.
FontFaceSet - Web APIs
fontfaceset.
ready read only promise which resolves once font loading and layout operations have completed.
Fullscreen API - Web APIs
if full-screen mode is al
ready active (fullscreenelement is not null), we call exitfullscreen() on the document to shut off full-screen mode.
Using the Gamepad API - Web APIs
if a gamepad is al
ready connected when the page loaded, the gamepadconnected event is dispatched to the focused page when the user presses a button or moves an axis.
GlobalEventHandlers.onemptied - Web APIs
the emptied event is fired when the media has become empty; for example, this event is sent if the media has al
ready been loaded (or partially loaded), and the load() method is called to reload it.
Audio() - Web APIs
determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the
readystate property.
HTMLInputElement.setRangeText() - Web APIs
html <input type="text" id="text-box" size="30" value="this text has not been updated."> <button onclick="selecttext()">update text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.setrangetext('al
ready', 14, 17, 'select'); } result specifications specification status comment html living standardthe definition of 'htmlinputelement.setselectionrange()' in that specification.
HTMLMediaElement: emptied event - Web APIs
the emptied event is fired when the media has become empty; for example, this event is sent if the media has al
ready been loaded (or partially loaded), and the load() method is called to reload it.
HTMLMediaElement.pause() - Web APIs
the htmlmediaelement.pause() method will pause playback of the media, if the media is al
ready in a paused state this method will have no effect.
Option() - Web APIs
note that a value of true does not set the option to selected if it is not al
ready selected.
HTMLTrackElement - Web APIs
htmltrackelement.
readystate read only returns an unsigned short that show the readiness state of the track: constant value description none 0 indicates that the text track's cues have not been obtained.
The HTML DOM API - Web APIs
this code looks at the length of the current value of the input; if it's zero, then the "send" button is disabled if it's not al
ready disabled.
Ajax navigation example - Web APIs
-codes.xml */ { 100: "continue", 101: "switching protocols", 102: "processing", 200: "ok", 201: "created", 202: "accepted", 203: "non-authoritative information", 204: "no content", 205: "reset content", 206: "partial content", 207: "multi-status", 208: "al
ready reported", 226: "im used", 300: "multiple choices", 301: "moved permanently", 302: "found", 303: "see other", 304: "not modified", 305: "use proxy", 306: "reserved", 307: "temporary redirect", 308: "permanent redirect", 400: "bad request", 401: "unauthori...
IDBDatabase.createObjectStore() - Web APIs
has been deleted or removed.) in firefox previous to version 41, an invalidstateerror was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) constrainterror an object store with the given name (based on case-sensitive comparison) al
ready exists in the connected database.
IDBDatabase.transaction() - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the displaydata() function to populate the task list with // all the to-do list data al
ready in the idb displaydata(); }; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtm...
IDBDatabase - Web APIs
this is used a lot later on db = dbopenrequest.result; // run the displaydata() function to populate the task // list with all the to-do list data al
ready in the idb displaydata(); }; // this event handles the event whereby a new version of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>...
IDBObjectStore.autoIncrement - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(e...
IDBObjectStore.clear() - Web APIs
// this is used a lot below db = dbopenrequest.result; // clear all the data form the object store cleardata(); }; function cleardata() { // open a read/write db transaction,
ready for clearing the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.e...
IDBObjectStore.delete() - Web APIs
this is used a lot below db = dbopenrequest.result; // run the deletedata() function to delete a record from the database deletedata(); }; function deletedata() { // open a read/write db transaction,
ready for deleting the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.e...
IDBObjectStore.deleteIndex() - Web APIs
this is used a lot below db = this.result; // run the displaydata() function to populate the task list with all the to-do list data al
ready in the idb displaydata(); }; // this event handles the event whereby a new version of the database needs to be created // either one has not been created before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(even...
IDBObjectStore.get() - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the getdata() function to get the data from the database getdata(); }; function getdata() { // open a read/write db transaction,
ready for retrieving the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction...
IDBObjectStore.indexNames - Web APIs
// this is used a lot below db = this.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(e...
IDBObjectStore.keyPath - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(e...
IDBObjectStore.put() - Web APIs
the put() method of the idbobjectstore interface updates a given record in a database, or inserts a new record if the given item does not al
ready exist.
IDBObjectStore.transaction - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(e...
IDBObjectStore - Web APIs
store.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; // create a new item to add in to the object store var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: 'december', year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error.
IDBOpenDBRequest.onblocked - Web APIs
// this is used a lot below db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data al
ready in the idb displaydata(); }; // this event handles the event whereby a new version of the // database needs to be created.
IDBOpenDBRequest - Web APIs
this is used a lot below db = dbopenrequest.result; // run the displaydata() function to populate the task // listwith all the to-do list data al
ready in the idb displaydata(); }; // this event handles the event whereby a new version of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above // it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(...
IDBTransaction.commit() - Web APIs
examples // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["mydb"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error.
IDBTransaction.db - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
IDBTransaction.error - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
IDBTransaction.mode - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
IDBTransaction.onabort - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
IDBTransaction.oncomplete - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
IDBTransaction.onerror - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object
ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.in...
IDBTransaction - Web APIs
this is used a lot below db = dbopenrequest.result; // add the data to the database adddata(); }; function adddata() { // create a new object to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction,
ready to add data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error.
firesTouchEvents - Web APIs
you can use this property to detect mouse events that represent an action that may al
ready have been handled by touch event handlers.
Intersection Observer API - Web APIs
once options is
ready, we create the new observer, calling the intersectionobserver() constructor, specifying a function to be called when intersection crosses one of our thresholds, handleintersect(), and our set of options.
KeyboardEvent.code - Web APIs
window.addeventlistener("keydown", function(event) { if (event.defaultprevented) { return; // do nothing if event al
ready handled } switch(event.code) { case "keys": case "arrowdown": // handle "back" updateposition(-moverate); break; case "keyw": case "arrowup": // handle "forward" updateposition(moverate); break; case "keya": case "arrowleft": // handle "turn left" angle -= turnrate; break; case "keyd": case "arrowright": ...
KeyboardEvent.key - Web APIs
window.addeventlistener("keydown", function (event) { if (event.defaultprevented) { return; // do nothing if the event was al
ready processed } switch (event.key) { case "down": // ie/edge specific value case "arrowdown": // do something for "down arrow" key press.
MIDIMessageEvent - Web APIs
note: even though the web midi api specifies a receivedtime property that returns a domhighrestimestamp, chrome (the only implementation at the time of writing) does not support that property since the basic event.timestamp property al
ready returns a domhighrestimestamp in chrome.
MediaRecorder.resume() - Web APIs
syntax mediarecorder.resume() errors an invalidstate error is raised if the resume() method is called while the mediarecorder object’s mediarecorder.state is "inactive" — the recording cannot be resumed if it is not al
ready paused; if mediarecorder.state is al
ready "recording", resume() has no effect.
MediaRecorder.start() - Web APIs
invalidstateerror the mediarecorder is not in the inactive state; you can't start recording media if it's al
ready being recorded.
MediaRecorder.stop() - Web APIs
syntax mediarecorder.stop() errors an invalidstate error is raised if the stop() method is called while the mediarecorder object’s mediarecorder.state is "inactive" — it makes no sense to stop media capture if it is al
ready stopped.
MediaSource.MediaSource() - Web APIs
for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.
readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } ...
MediaSource.sourceBuffers - Web APIs
example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.
readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); console.log(mediasource.sourcebuffers); // will contain the source buffer that was added above video.play(); //console.log(mediasource.
readystate);...
MediaStream.ended - Web APIs
this property has been removed from the specification; you should instead rely on the ended event or check the value of mediastreamtrack.
readystate to see if its value is "ended" for the track or tracks you want to ensure have finished playing.
MediaTrackConstraints.cursor - Web APIs
ting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertfakecursorflag = false; if (displaystream.getvideotracks()[0].getsettings().cursor === "never") { insertfakecursorflag = true; } following this code, insertfakecursorflag is true if there's no cursor rendered into the stream al
ready.
Media Source API - Web APIs
mse allows us to replace the usual single track src value fed to media elements with a reference to a mediasource object, which is a container for information like the
ready state of the media for being played, and references to multiple sourcebuffer objects that represent the different chunks of media that make up the entire stream.
msPlayToPreferredSourceUri - Web APIs
example <video src="http://www.contoso.com/videos/video.mp4" msplaytopreferredsourceuri="http://www.contoso.com/catalogid=1234" /> var video = document.createelement('video'); document.body.appendchild(video); video.src = "http://www.contoso.com/videos/video.mp4"; video.msplaytopreferredsourceuri = "http://www.contoso.com/catalogid=1234"; see also microsoft play
ready content access and protection technology is a set of technologies that can be used to distribute audio/video content more securely over a network, and help prevent the unauthorized use of this content.
Navigator.vibrate() - Web APIs
if a vibration pattern is al
ready in progress when this method is called, the previous pattern is halted and the new one begins instead.
Node.insertBefore() - Web APIs
if the given node al
ready exists in the document, insertbefore() moves it from its current position to the new position.
Node.parentNode - Web APIs
example if (node.parentnode) { // remove a node from the tree, unless // it's not in the tree al
ready node.parentnode.removechild(node); } notes document and documentfragment nodes can never have a parent, so parentnode will always return null.
Notification.close() - Web APIs
the user al
ready read the notification on the webpage in the case of a messaging app or the following song is al
ready playing in a music app).
NotificationEvent.notification - Web APIs
console.log('notification tag:', event.notification.tag); console.log('notification data:', event.notification.data); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications spec...
NotificationEvent - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications spec...
OfflineAudioContext: complete event - Web APIs
flineaudiocontext.oncomplete examples when processing is complete, you might want to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.addeventlistener('complete', () => { console.log('offline audio processing now complete'); showmodaldialog('song processed and
ready to play'); playbtn.disabled = false; }) you can also set up the event handler using the offlineaudiocontext.oncomplete property: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.oncomplete = function() { console.log('offline audio processing now complete'); showmodaldialog('song processed and
ready to play'); playbtn.disabled = false; } specifications specifi...
OfflineAudioContext.oncomplete - Web APIs
offlineaudioctx.oncomplete = function() { console.log('offline audio processing now complete'); showmodaldialog('song processed and
ready to play'); playbtn.disabled = false; } specifications specification status comment web audio apithe definition of 'oncomplete' in that specification.
Path2D - Web APIs
if the shape has al
ready been closed or has only one point, this function does nothing.
PaymentRequest - Web APIs
additionally, in some browsers, the parts of the address will be redacted for privacy until the user indicates they are
ready to complete the transaction (i.e., they hit "pay").
PaymentResponse.retry() - Web APIs
if show() is rejected, the payment request failed, usually because either there's al
ready one being processed, because the user agent doesn't support any of the specified payment methods, or because of a security issue.
Payment Request API - Web APIs
advantages of using the payment request api with "basic-card" (card-based payments): fast purchase experience: users enter their details once into the browser and are then
ready to pay for goods and services on the web.
PerformanceResourceTiming.workerStart - Web APIs
the workerstart read-only property of the performanceresourcetiming interface returns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is al
ready running, or immediately before starting the service worker thread if it is not al
ready running.
PerformanceResourceTiming - Web APIs
performanceresourcetiming.workerstartread only returns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is al
ready running, or immediately before starting the service worker thread if it is not al
ready running.
PerformanceTiming.domComplete - Web APIs
the legacy performancetiming.domcomplete read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.
readystate changes to 'complete' and the corresponding
readystatechange event is thrown.
PerformanceTiming.domInteractive - Web APIs
the legacy performancetiming.dominteractive read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.
readystate changes to 'interactive' and the corresponding
readystatechange event is thrown.
PerformanceTiming.domLoading - Web APIs
the legacy performancetiming.domloading read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser started its work, that is when its document.
readystate changes to 'loading' and the corresponding
readystatechange event is thrown.
PerformanceTiming.fetchStart - Web APIs
the legacy performancetiming.fetchstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the browser is
ready to fetch the document using an http request.
ProgressEvent.loaded - Web APIs
the progressevent.loaded read-only property is an integer representing the amount of work al
ready performed by the underlying process.
PushManager.getSubscription() - Web APIs
(no live demo is available.) // we need the service worker registration to check for a subscription navigator.serviceworker.
ready.then(function(serviceworkerregistration) { // do we al
ready have a push message subscription?
PushSubscription.endpoint - Web APIs
example navigator.serviceworker.
ready.then(function(reg) { reg.pushmanager.subscribe({uservisibleonly: true}).then(function(subscription) { console.log(subscription.endpoint); // at this point you would most likely send the subscription // endpoint to your server, save it, then use it to send a // push message at a later date }) }) specifications specification status comment push ...
PushSubscription.toJSON() - Web APIs
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.
PushSubscription.unsubscribe() - Web APIs
example navigator.serviceworker.
ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'unsubscribe()' in that specification.
PushSubscription - Web APIs
example navigator.serviceworker.
ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'pushsubscription' in that specification.
Web Push API Notifications best practices - Web APIs
for example, safari 12.1 now requires—and other browsers either al
ready do, or are planning[1] to do so—that the user interact with the page in some way before the page can request permission to perform push notifications.
RTCConfiguration.iceServers - Web APIs
if the list of servers is changed while a connection is al
ready active by calling the the rtcpeerconnection method setconfiguration(), no immediate effect occurs.
RTCConfiguration - Web APIs
you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're al
ready available for inspection when rtcpeerconnection.setlocaldescription() is called.
RTCDataChannel: open event - Web APIs
bubbles no cancelable no interface rtcdatachannelevent event handler property onopen examples this example adds to the rtcdatachannel dc a handler for the open event that adjusts the user interface to indicate that a chat window is
ready to be used after a connection has been established.
RTCDataChannel.send() - Web APIs
exceptions invalidstateerror since the data channel uses a separate transport channel from the media content, it must establish its own connection; if it hasn't finished doing so (that is, its
readystate is "connecting"), this error occurs without sending or buffering the data.
RTCDataChannel - Web APIs
if no protocol was specified when the data channel was created, then this property's value is "" (the empty string).
readystate read only the read-only rtcdatachannel property
readystate returns an enum of type rtcdatachannelstate which indicates the state of the data channel's underlying data connection.reliable read only the read-only rtcdatachannel property reliable indicates whether or not the data channel is reliable.stream read only the deprecated (and never part of the official specification) read-on...
RTCIceCandidatePairStats.readable - Web APIs
syntax isreadable = rtcicecandidatepairstats.readable; value a boolean value which is true if the connection described by this candidate pair has received at least one valid ice request, and is therefore
ready to be read from.
RTCIceCandidateStats - Web APIs
for host candidates, true means that any network resources (usually a network socket) associated with the candidate have al
ready been released.
RTCIceTransport - Web APIs
these are the same candidates which have al
ready been sent to the remote peer by sending an icecandidate event to the rtcpeerconnection for transmission.
RTCInboundRtpStreamStats.fecPacketsDiscarded - Web APIs
this can happen if all the packets covered by the fec packet have al
ready been received or recovered using another fec packet, or if the fec packet arrived outside the recovery window and the lost rtp packets have al
ready been skipped during playback as a result.
RTCPeerConnection() - Web APIs
you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're al
ready available for inspection when rtcpeerconnection.setlocaldescription() is called.
RTCPeerConnection.addIceCandidate() - Web APIs
syntax apromise = pc.addicecandidate(candidate); addicecandidate(candidate, successcallback, failurecallback); parameters candidate optional an object conforming to the rtcicecandidateinit dictionary, or an rtcicecandidate object; the contents of the object should be constructed from a message received over the signaling channel, describing a newly received ice candidate that's
ready to be delivered to the local ice agent.
RTCPeerConnection.ondatachannel - Web APIs
example pc.ondatachannel = function(ev) { console.log('data channel is created!'); ev.channel.onopen = function() { console.log('data channel is open and
ready to be used.'); }; }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.ondatachannel' in that specification.
RTCPeerConnection.onnegotiationneeded - Web APIs
if the session is modified in a manner that requires negotiation while a negotiation is al
ready in progress, no negotiationneeded event will fire until negotiation completes, and only then if negotiation is still needed.
RTCPeerConnection.peerIdentity - Web APIs
if there isn't al
ready a target peer identity, peeridentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur.
ReadableStream.cancel() - Web APIs
fore); var bytesreceived = 0; var buffer = ''; var matchfoundat = -1; return reader.read().then(function process(result) { if (result.done) { console.log('failed to find match'); return; } bytesreceived += result.value.length; console.log(`received ${bytesreceived} bytes of data so far`); buffer += decoder.decode(result.value, {stream: true}); // al
ready found match & just context-gathering?
ReadableStream.getReader() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has al
ready given you all its data.
ReadableStream.tee() - Web APIs
; fetchstream(teedoff[0], list2); fetchstream(teedoff[1], list3); } function fetchstream(stream, list) { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has al
ready given you all its data.
ReadableStreamDefaultReader.cancel() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has al
ready given you all its data.
ReadableStreamDefaultReader.read() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has al
ready given you all its data.
ServiceWorkerRegistration.index - Web APIs
here is an example from the main script: // reference registration const registration = await navigator.serviceworker.
ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } from the service worker: // service worker script const contentindex = self.registration.index; specifications specification status comment unknownthe definition of 'index' in that specification.
ServiceWorkerRegistration.showNotification() - Web APIs
examples navigator.serviceworker.register('sw.js'); function shownotification() { notification.requestpermission(function(result) { if (result === 'granted') { navigator.serviceworker.
ready.then(function(registration) { registration.shownotification('vibration sample', { body: 'buzz!
SourceBuffer.changeType() - Web APIs
usage notes if the parent mediasource is in its "ended"
readystate, calling changetype() will transition the media source to the "open"
readystate and fire a simple event named sourceopen at the parent media source.
SourceBuffer.mode - Web APIs
if timestamps al
ready exist for the media segments, then the value will be set to segments; if they don't, then the value will be set to sequence.
SpeechRecognition.abort() - Web APIs
turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('
ready to receive a color command.'); } abortbtn.onclick = function() { recognition.abort(); console.log('speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('speech recognition has stopped.'); } specifications specification status comment web speech apithe definition of 'abort()' in that specification.
SpeechRecognition.start() - Web APIs
turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('
ready to receive a color command.'); } abortbtn.onclick = function() { recognition.abort(); console.log('speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('speech recognition has stopped.'); } specifications specification status comment web speech apithe definition of 'start()' in that specification.
SpeechRecognition.stop() - Web APIs
turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('
ready to receive a color command.'); } abortbtn.onclick = function() { recognition.abort(); console.log('speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('speech recognition has stopped.'); } specifications specification status comment web speech apithe definition of 'stop()' in that specification.
SpeechRecognition - Web APIs
st(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('
ready to receive a color command.'); } recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'speechrecognition' in that specification.
SpeechSynthesis.resume() - Web APIs
the resume() method of the speechsynthesis interface puts the speechsynthesis object into a non-paused state: resumes it if it was al
ready paused.
SpeechSynthesis - Web APIs
speechsynthesis.resume() puts the speechsynthesis object into a non-paused state: resumes it if it was al
ready paused.
Storage.setItem() - Web APIs
the setitem() method of the storage interface, when passed a key name and value, will add that key to the given storage object, or update that key's value if it al
ready exists.
Storage - Web APIs
storage.setitem() when passed a key name and value, will add that key to the storage, or update that key's value if it al
ready exists.
StorageManager - Web APIs
storagemanager.persisted() secure context returns a promise that resolves to true if persistence has al
ready been granted for your site's storage.
Storage API - Web APIs
the storage api gives sites' code the ability to find out how much space they can use, how much they are al
ready using, and even control whether or not they need to be alerted before the user agent disposes of site data in order to make room for other things.
WebGL by example - Web APIs
instead of trying to juggle shaders, geometry, and working with gpu memory, al
ready in the first program, the examples here explore webgl in an incremental way.
WebGL constants - Web APIs
r 0x8a46 sync objects constant name value description object_type 0x9112 sync_condition 0x9113 sync_status 0x9114 sync_flags 0x9115 sync_fence 0x9116 sync_gpu_commands_complete 0x9117 unsignaled 0x9118 signaled 0x9119 al
ready_signaled 0x911a timeout_expired 0x911b condition_satisfied 0x911c wait_failed 0x911d sync_flush_commands_bit 0x00000001 miscellaneous constants constant name value description color 0x1800 depth 0x1801 stencil 0x1802 min 0x8007 ...
Lifetime of a WebRTC session - Web APIs
in particular, if a developer al
ready has a method in place for connecting two devices, it doesn’t make sense for them to have to use another one, defined by the specification, just for webrtc.
Using WebRTC data channels - Web APIs
this makes it easy to write efficient routines that make sure there's always data
ready to send without over-using memory or swamping the channel completely.
WebSocket.onclose - Web APIs
the websocket.onclose property is an eventhandler that is called when the websocket connection's
readystate changes to closed.
WebSocket.onopen - Web APIs
the websocket.onopen property is an eventhandler that is called when the websocket connection's
readystate changes to 1; this indicates that the connection is
ready to send and receive data.
Using bounded reference spaces - Web APIs
ton(event) { if (!xrsession) { navgator.xr.requestsession("immersive-vr"), { requiredfeatures: ["local-floor"], optionalfeatures: ["bounded-floor"] }).then((session) => { xrsession = session; startsessionanimation(); }); } } this function, called when the user clicks on a button to start the xr experience, works as usual, exiting at once if a session is al
ready in place, then requesting a new session using immersive-vr mode.
Controlling multiple parameters with ConstantSourceNode - Web APIs
function toggleplay(event) { if (playing) { playbutton.innerhtml = "▶️"; stoposcillators(); } else { playbutton.innerhtml = "⏸"; startoscillators(); } } if the playing variable indicates we're al
ready playing the oscillators, we change the playbutton's content to be the unicode character "right-pointing triangle" (▶️) and call stoposcillators() to shut down the oscillators.
Visualizations with Web Audio API - Web APIs
to create the oscilloscope visualisation (hat tip to soledad penadés for the original code in voice-change-o-matic), we first follow the standard pattern described in the previous section to set up the buffer: analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); next, we clear the canvas of what had been drawn on it before to get
ready for the new visualization display: canvasctx.clearrect(0, 0, width, height); we now define the draw() function: function draw() { in here, we use requestanimationframe() to keep looping the drawing function once it has been started: var drawvisual = requestanimationframe(draw); next, we grab the time domain data and copy it into our array analyser.getbytetimedomaindata(dataarray); next, f...
Attestation and Assertion - Web APIs
when registering an authenticator for a new account, typically a trust on first use (tofu) model applies; and when adding an authenticator to an existing account, a user has al
ready been authenticated and has established a secure session.
Web Authentication API - Web APIs
many websites al
ready have pages that allow users to register new accounts or sign in to an existing account, and the web authentication api acts as a replacement or supplement to those on those existing webpages.
Using the Web Speech API - Web APIs
try ' + colorhtml + '.'; document.body.onclick = function() { recognition.start(); console.log('
ready to receive a color command.'); } receiving and handling results once the speech recognition is started, there are many event handlers that can be used to retrieve results, and other pieces of surrounding information (see the speechrecognition event handlers list.) the most common one you'll probably use is speechrecognition.onresult, which is fired once a successful result is received: recogni...
window.dump() - Web APIs
if you don't have one al
ready, closing the application and re-opening it with the command line parameter -console should create the console or use -attach-console to use the existing console.
Window.getComputedStyle() - Web APIs
originally, css 2.0 defined the computed values as the "
ready to be used" final values of properties after cascading and inheritance, but css 2.1 redefined them as pre-layout, and used values as post-layout.
Window: load event - Web APIs
ht: 2rem; } js const log = document.queryselector('.event-log-contents'); const reload = document.queryselector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('
readystatechange', (event) => { log.textcontent = log.textcontent + `
readystate: ${document.
readystate}\n`; }); document.addeventlistener('domcontentloaded', (event) => { log.textcontent = log.textcontent + `domcontentloaded\n`; }); result specifications specification status comment ui eventsthe definition of 'load' in that specification.
window.requestIdleCallback() - Web APIs
currently only one property is defined: timeout: if timeout is specified and has a positive value, and the callback has not al
ready been called by the time timeout milliseconds have passed, the callback will be called during the next idle period, even if doing so risks causing a negative performance impact.
Window.scrollY - Web APIs
} window.scrollbypages(1); notes use this property to check that the document hasn't al
ready been scrolled when using relative scroll functions such as scrollby(), scrollbylines(), or scrollbypages().
WindowClient.focus() - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications speci...
WindowClient.focused - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) { if(!client.focused) return client.focus(); } } } if (clients.openwindow) return clients.openwindo...
WindowClient - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is al
ready open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) { client.focus(); break; } } if (clients.openwindow) return clients.openwindow('/'); })); }); specificatio...
HTML in XMLHttpRequest - Web APIs
this test file is small and is not well-formed xml: <title>&&<</title> if the file is named detect.html, the following function can be used for detecting html parsing support: function detecthtmlinxhr(callback) { if (!window.xmlhttprequest) { window.settimeout(function() { callback(false); }, 0); return; } var done = false; var xhr = new window.xmlhttprequest(); xhr.on
readystatechange = function() { if (this.
readystate == 4 && !done) { done = true; callback(!!(this.responsexml && this.responsexml.title && this.responsexml.title == "&&<")); } } xhr.onabort = xhr.onerror = function() { if (!done) { done = true; callback(false); } } try { xhr.open("get", "detect.html"); xhr.responsetype = "document"; xhr.send(...
init() - Web APIs
if this is specified, it is used even if the global has a window with a load group al
ready established.
XMLHttpRequest.open() - Web APIs
note: calling this method for an al
ready active request (one for which open() has al
ready been called) is the equivalent of calling abort().
XMLHttpRequest.responseXML - Web APIs
example var xhr = new xmlhttprequest; xhr.open('get', '/server'); // if specified, responsetype must be empty string or "document" xhr.responsetype = 'document'; // force the response to be parsed as xml xhr.overridemimetype('text/xml'); xhr.onload = function () { if (xhr.
readystate === xhr.done && xhr.status === 200) { console.log(xhr.response, xhr.responsexml); } }; xhr.send(); specifications specification status comment xmlhttprequestthe definition of 'responsexml' in that specification.
XRSession.onsqueezeend - Web APIs
that's because (in this example, at least) the handler for the squeeze event has al
ready dropped the object into its new location and then cleared the value of heldobject to indicate that the user is no longer holding anything.
XRSession.requestAnimationFrame() - Web APIs
the xrsession method requestanimationframe(), much like the window method of the same name, schedules a callback to be executed the next time the browser is
ready to paint the session's virtual environment to the xr display.
XRSession: visibilitychange event - Web APIs
bubbles yes cancelable no interface xrsessionevent event handler property onvisibilitychange when the xrsession receives this event, the visibility state has al
ready been changed.
XRSystem: requestSession() - Web APIs
exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: invalidstateerror the requested session mode is immersive-vr but there is al
ready an immersive vr session either currently active or in the process of being set up.
XRWebGLLayer() - Web APIs
exceptions invalidstateerror the new xrwebgllayer could not be created due to one of a number of possible state errors: the xrsession specified by session has al
ready been stopped.
XRWebGLLayer - Web APIs
let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); rendering every view in a frame each time the gpu is
ready to render the scene to the xr device, the xr runtime calls the function you specified when you called the xrsession method requestanimationframe() to ask to render the frame.
Using the aria-hidden attribute - Accessibility
</p> accessibility concerns best practices aria-hidden="true" should not be added when: the html hidden attribute is present the element or the element's ancestor is hidden with display: none the element or the element's ancestor is hidden with visibility: hidden in all three scenarios, the attribute is unnecessary to add because the element has al
ready been removed from the accessibility tree.
ARIA Test Cases - Accessibility
however, where things don't work we may test with nightly builds if they are available, in order to show what is al
ready fixed in upcoming releases.
ARIA annotations - Accessibility
aria-details versus aria-describedby we have al
ready alluded to the difference between these two above — aria-describedby is for textual descriptions, whereas aria-details is for more complex sets of details.
ARIA: tabpanel role - Accessibility
the first rule of aria use is you can use a native feature with the semantics and behavior you require al
ready built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: cell role - Accessibility
keyboard interactions none required javascript features the first rule of aria use is if you can use a native feature with the semantics and behavior you require al
ready built in, instead of repurposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: row role - Accessibility
the first rule of aria use is you can use a native feature with the semantics and behavior you require al
ready built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: rowgroup role - Accessibility
the first rule of aria use is if you can use a native feature with the semantics and behavior you require al
ready built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: table role - Accessibility
the first rule of aria use is if you can use a native feature with the semantics and behavior you require al
ready built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: button role - Accessibility
whether an element is a toggle button or not can be indicated with the aria-pressed attribute in addition to the button role (if the element is not al
ready a native button element): if aria-pressed is not used, or is set to the "undefined" state, the button is not a toggle button.
WAI-ARIA Roles - Accessibility
a feed enables screen readers to use the browse mode reading cursor to both read and scroll through a stream of rich content that may continue scrolling infinitely by loading more content as the user reads.aria: figure rolethe aria figure role can be used to identify a figure inside page content where appropriate semantics do not al
ready exist.
Keyboard-navigable JavaScript widgets - Accessibility
non-native controls native html elements that are interactive, like <a>, <input> and <select>, are al
ready accessible by keyboards, so to use one of them is the fastest path to make components work with keyboards.
content - CSS: Cascading Style Sheets
html <h1>5</h1> <p>according to sir tim berners-lee, <q cite="http://www.w3.org/people/berners-lee/faq.html#internet">i was lucky enough to invent the web at the time when the internet al
ready existed - and had for a decade and a half.</q> we must understand that there is nothing fundamentally wrong with building on the contributions of others.
vertical-align - CSS: Cascading Style Sheets
op">top</td> <td style="vertical-align: middle">middle</td> <td style="vertical-align: bottom">bottom</td> <td> <p>there is a theory which states that if ever anyone discovers exactly what the universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.</p> <p>there is another theory which states that this has al
ready happened.</p> </td> </tr> </table> table { margin-left: auto; margin-right: auto; width: 80%; } table, th, td { border: 1px solid black; } td { padding: 0.5em; font-family: monospace; } note that vertical-align only applies to inline, inline-block and table-cell elements: you can't use it to vertically align block-level elements.
CSS: Cascading Style Sheets
css layout at this point we've al
ready looked at css fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside.
Creating a cross-browser video player - Developer guides
ontainer.requestfullscreen(); else if (videocontainer.mozrequestfullscreen) videocontainer.mozrequestfullscreen(); else if (videocontainer.webkitrequestfullscreen) videocontainer.webkitrequestfullscreen(); else if (videocontainer.msrequestfullscreen) videocontainer.msrequestfullscreen(); setfullscreendata(true); } } first of all the function checks if the browser is al
ready in fullscreen mode by calling another function isfullscreen: var isfullscreen = function() { return !!(document.fullscreen || document.webkitisfullscreen || document.mozfullscreen || document.msfullscreenelement || document.fullscreenelement); } this function checks all the various browser prefixed versions to try and determine the correct result.
Standard metadata names - HTML: Hypertext Markup Language
other metadata names the whatwg wiki metaextensions page contains a large set of non-standard metadata names that have not been formally accepted yet; however, some of the names included there are al
ready used quite commonly in practice — including the following: creator: the name of the creator of the document, such as an organization or institution.
HTTP conditional requests - HTTP
integrity of a partial download partial downloading of files is a functionality of http that allows to resume previous operations, saving bandwidth and time, by keeping the al
ready obtained information: a server supporting partial downloads broadcasts this by sending the accept-ranges header.
Using HTTP cookies - HTTP
if your site authenticates users, it should regenerate and resend session cookies, even ones that al
ready exist, whenever the user authenticates.
Content-Encoding - HTTP
the recommendation is to compress data as much as possible and therefore to use this field, but some types of resources, such as jpeg images, are al
ready compressed.
CSP: trusted-types - HTTP
'allow-duplicates' allows for creating policies with a name that was al
ready used examples todo polyfill a polyfill for trusted types is available on github.
Expires - HTTP
invalid dates, like the value 0, represent a date in the past and mean that the resource is al
ready expired.
Feature-Policy - HTTP
publickey-credentials-get controls whether the current document is allowed to use the web authentication api to retreive al
ready stored public-key credentials, i.e.
If-None-Match - HTTP
they are only useful when uploading a resource, usually with put, to check if another resource with the identity has al
ready been uploaded before.
Upgrade - HTTP
the http 1.1 (only) upgrade header can be used to upgrade an al
ready established client/server connection to a different protocol (over the same transport protocol).
HTTP headers - HTTP
this is used to update caches (for safe requests), or to prevent to upload a new resource when one al
ready exists.
Protocol upgrade mechanism - HTTP
the http/1.1 protocol provides a special mechanism that can be used to upgrade an al
ready established connection to a different protocol, using the upgrade header field.
Proxy Auto-Configuration (PAC) file - HTTP
dnsdomainis() localhostordomainis() isresolvable() isinnet() related utility functions dnsresolve() convert_addr() myipaddress() dnsdomainlevels() url/hostname based conditions shexpmatch() time based conditions weekdayrange() daterange() timerange() logging utility alert() there was one associative array (object) al
ready defined, because at the time javascript code was unable to define it by itself: proxyconfig.bindings note: pactester (part of the pacparser package) was used to test the following syntax examples.
Redirections in HTTP - HTTP
redirection loops redirection loops happen when additional redirections follow the one that has al
ready been followed.
A typical HTTP session - HTTP
an absolute url without the protocol or domain name the http protocol version subsequent lines represent an http header, giving the server information about what type of data is appropriate (e.g., what language, what mime types), or other data altering its behavior (e.g., not sending an answer if it is al
ready cached).
100 Continue - HTTP
the http 100 continue informational status response code indicates that everything so far is ok and that the client should continue with the request or ignore it if it is al
ready finished.
409 Conflict - HTTP
for example, you may get a 409 response when uploading a file which is older than the one al
ready on the server resulting in a version control conflict.
503 Service Unavailable - HTTP
the hypertext transfer protocol (http) 503 service unavailable server error response code indicates that the server is not
ready to handle the request.
A re-introduction to JavaScript (JS tutorial) - JavaScript
you could just rewrite the function as follows: function avgarray(arr) { var sum = 0; for (var i = 0, j = arr.length; i < j; i++) { sum += arr[i]; } return sum / arr.length; } avgarray([2, 3, 4, 5]); // 3.5 but it would be nice to be able to reuse the function that we've al
ready created.
Closures - JavaScript
because the loop has al
ready run its course by that time, the item variable object (shared by all three closures) has been left pointing to the last entry in the helptext list.
Concurrency model and the event loop - JavaScript
event loop the event loop got its name because of how it's usually implemented, which usually resembles: while (queue.waitformessage()) { queue.processnextmessage() } queue.waitformessage() waits synchronously for a message to arrive (if one is not al
ready available and waiting to be handled).
Grammar and types - JavaScript
e 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}}`(myon
readystatechangehandler); you should use string literals unless you specifically need to use a string object.
Introduction - JavaScript
what you should al
ready know this guide assumes you have the following basic background: a general understanding of the internet and the world wide web (www).
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
examples deprecated syntax var num = 15; string.replace(num, /5/, '2'); standard syntax var num = 15; string(num).replace(/5/, '2'); shim the following is a shim to provide support to non-supporting browsers: /*globals define*/ // assumes all supplied string instance methods al
ready present // (one may use shims for these if not available) (function() { 'use strict'; var i, // we could also build the array of methods with the following, but the // getownpropertynames() method is non-shimable: // object.getownpropertynames(string).filter(function(methodname) { // return typeof string[methodname] === 'function'; // }); methods = [ 'contai...
JavaScript error reference - JavaScript
d array.prototype.sort argumenttypeerror: invalid argumentstypeerror: invalid assignment to const "x"typeerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but al
ready has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return statement ...
Array.prototype.indexOf() - JavaScript
ement, idx + 1); } console.log(indices); // [0, 2, 4] finding if an element exists in the array or not and updating the array function updatevegetablescollection (veggies, veggie) { if (veggies.indexof(veggie) === -1) { veggies.push(veggie); console.log('new veggies collection is : ' + veggies); } else if (veggies.indexof(veggie) > -1) { console.log(veggie + ' al
ready exists in the veggies collection.'); } } var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; updatevegetablescollection(veggies, 'spinach'); // new veggies collection is : potato,tomato,chillies,green-pepper,spinach updatevegetablescollection(veggies, 'spinach'); // spinach al
ready exists in the veggies collection.
Date.prototype.toLocaleDateString() - JavaScript
to check whether an implementation supports them al
ready, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaledatestringsupportslocales() { try { new date().tolocaledatestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats.
Date.prototype.toLocaleString() - JavaScript
to check whether an implementation supports them al
ready, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocalestringsupportslocales() { try { new date().tolocalestring('i'); } catch (e) { return e instanceof rangeerror; } return false; } using locales this example shows some of the variations in localized date and time formats.
Date.prototype.toLocaleTimeString() - JavaScript
to check whether an implementation supports them al
ready, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaletimestringsupportslocales() { try { new date().tolocaletimestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats.
Date - JavaScript
it needs real-world feedback from web developers, but is not yet
ready for production use!
Generator.prototype.return() - JavaScript
function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } if return(value) is called on a generator that is al
ready in "completed" state, the generator will remain in "completed" state.
Object.defineProperty() - JavaScript
s in the o object and its value is 38 // the value of o.b is now always identical to bvalue, // unless o.b is redefined // you cannot try to mix both: object.defineproperty(o, 'conflict', { value: 0x9f91102, get() { return 0xdeadbeef; } }); // throws a typeerror: value appears // only in data descriptors, // get appears only in accessor descriptors modifying a property when the property al
ready exists, object.defineproperty() attempts to modify the property according to the values in the descriptor and the object's current configuration.
Object.entries() - JavaScript
polyfill to add compatible object.entries() support in older environments that do not natively support it, you can use any of the following: a demonstration implementation of object.entries in the tc39/proposal-object-values-entries (if you don't need any support for ie); a polyfill in the es-shims/object.entries repositories; or, you can use the simple,
ready-to-deploy polyfill listed below: if (!object.entries) { object.entries = function( obj ){ var ownprops = object.keys( obj ), i = ownprops.length, resarray = new array(i); // preallocate the array while (i--) resarray[i] = [ownprops[i], obj[ownprops[i]]]; return resarray; }; } for the above polyfill code snippet, if you need support for ie<9, then you wi...
Object.prototype.hasOwnProperty() - JavaScript
note that the for...in loop is al
ready only iterating enumerable items, so one should not assume based on the lack of non-enumerable properties shown in the loop that hasownproperty itself is confined strictly to enumerable items (as with object.getownpropertynames()).
Object.setPrototypeOf() - JavaScript
function to that chain function person(sname) { this.identity = sname; } var george = object.appendchain(new person('george'), 'console.log("hello guys!!");'); console.log(george.identity); // 'george' george(); // 'hello guys!!' polyfill using the older object.prototype.__proto__ property, we can easily define object.setprototypeof if it isn't available al
ready: if (!object.setprototypeof) { // only works in chrome and firefox, does not work in ie: object.prototype.setprototypeof = function(obj, proto) { if(obj.__proto__) { obj.__proto__ = proto; return obj; } else { // if you want to return prototype of object.create(null): var fn = function() { for (var ke...
Promise.allSettled() - JavaScript
however, if and only if an empty iterable is passed as an argument, promise.allsettled() returns a promise object that has al
ready been resolved as an empty array.
Promise.prototype.catch() - JavaScript
ion(){ console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); return originalthen.apply(this, arguments); }; promise.prototype.catch = function(){ console.error('> > > > > > called .catch on %o with arguments: %o', this, arguments); return originalcatch.apply(this, arguments); }; })(this.promise); // calling catch on an al
ready resolved promise promise.resolve().catch(function xxx(){}); // logs: // > > > > > > called .catch on promise{} with arguments: arguments{1} [0: function xxx()] // > > > > > > called .then on promise{} with arguments: arguments{2} [0: undefined, 1: function xxx()] description the catch method is used for error handling in promise composition.
String.prototype.charAt() - JavaScript
throw 'low surrogate without preceding high surrogate'; } var prev = str.charcodeat(i - 1); // (could change last hex to 0xdb7f to treat high private // surrogates as single characters) if (0xd800 > prev || prev > 0xdbff) { throw 'low surrogate without preceding high surrogate'; } // we can pass over low surrogates now as the second component // in a pair which we have al
ready processed return false; } in an ecmascript 2016 environment which allows destructured assignment, the following is a more succinct and somewhat more flexible alternative in that it does increment for an incrementing variable automatically (if the character warrants it in being a surrogate pair).
String.prototype.charCodeAt() - JavaScript
hi = code; low = str.charcodeat(idx + 1); if (isnan(low)) { throw 'high surrogate not followed by ' + 'low surrogate in fixedcharcodeat()'; } return ( (hi - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000; } if (0xdc00 <= code && code <= 0xdfff) { // low surrogate // we return false to allow loops to skip // this iteration since should have al
ready handled // high surrogate above in the previous iteration return false; // hi = str.charcodeat(idx - 1); // low = code; // return ((hi - 0xd800) * 0x400) + // (low - 0xdc00) + 0x10000; } return code; } fixing charcodeat() to handle non-basic-multilingual-plane characters if their presence earlier in the string is known function knowncharcodeat(str, idx) { str +=...
WeakSet - JavaScript
use case: detecting circular references functions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have al
ready been processed.
WebAssembly.Module() constructor - JavaScript
a webassembly.module() constructor creates a new module object containing stateless webassembly code that has al
ready been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.
WebAssembly.Module - JavaScript
a webassembly.module object contains stateless webassembly code that has al
ready been compiled by the browser — this can be efficiently shared with workers, and instantiated multiple times.
WebAssembly - JavaScript
webassembly.module() contains stateless webassembly code that has al
ready been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.
Logical OR (||) - JavaScript
this happens because the value of the operator is al
ready determined after the evaluation of the first operand.
Logical OR assignment (||=) - JavaScript
syntax expr1 ||= expr2 description short-circuit evaluation the logical or operator works like this: x || y; // returns x when x is truthy // returns y when x is not truthy the logical or operator short-circuits: the second operand is only evaluated if the first operand doesn’t al
ready determine the result.
Unary plus (+) - JavaScript
the unary plus operator (+) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't al
ready.
block - JavaScript
note that the block-scoped const c = 2 does not throw a syntaxerror: identifier 'c' has al
ready been declared because it can be declared uniquely within the block.
const - JavaScript
my_fav = 20; // my_fav is 7 console.log('my favorite number is: ' + my_fav); // trying to redeclare a constant throws an error // uncaught syntaxerror: identifier 'my_fav' has al
ready been declared const my_fav = 20; // the name my_fav is reserved for constant above, so this will fail too var my_fav = 20; // this throws an error too let my_fav = 20; block scoping it's important to note the nature of block scoping.
switch - JavaScript
take a look at this example: const action = 'say_hello'; switch (action) { case 'say_hello': let message = 'hello'; console.log(message); break; case 'say_hi': let message = 'hi'; console.log(message); break; default: console.log('empty action received.'); break; } this example will output the error uncaught syntaxerror: identifier 'message' has al
ready been declared which you were not probably expecting.
try...catch - JavaScript
myfile(); try { // tie up a resource writemyfile(thedata); } finally { closemyfile(); // always close the resource } examples nested try-blocks first, let's see what happens with this: try { try { throw new error('oops'); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "finally" // "outer" "oops" now, if we al
ready caught the exception in the inner try-block by adding a catch-block try { try { throw new error('oops'); } catch (ex) { console.error('inner', ex.message); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "inner" "oops" // "finally" and now, let's rethrow the error.
Trailing commas - JavaScript
if you want to add a new property, you can simply add a new line without modifying the previously last line if that line al
ready uses a trailing comma.
Digital audio concepts - Web media technologies
for example, consider a stereo audio clip (that is, two audio channels) with a sample size of 16 bits (2 bytes), recorded at 48 khz: 2×2bytessample×48000samplessecond=192000bytessecond=192kbps2 \times 2\frac { bytes }{ sample } \times 48000\frac { samples }{ second } = 192000\frac { bytes }{ second } = 192 kbps at 192 kbps, lower-end networks are al
ready going to be strained just by a single audio stream playing.
contentStyleType - SVG: Scalable Vector Graphics
usage notes value one of the content types specified in the media types default value text/css animatable no since css is the only widely deployed style sheet language for online styling and it's al
ready defined as default value if contentstyletype is ommitted, the attribute is not well supported in user agents.
externalResourcesRequired - SVG: Scalable Vector Graphics
if an external resource is not available, progressive rendering is suspended, the document's svgload event is not fired and the animation timeline does not begin until that resource and all other required resources become available, have been parsed and are
ready to be rendered.
Namespaces crash course - SVG: Scalable Vector Graphics
if you don't al
ready have one, make one up starting with the following code: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations.
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
general change notes length attribute and indexed property for list interfaces implementation status unknown <script> element in content model of all elements implementation status unknown initialize(), appenditem(), replaceitem(), and insertitembefore() on list objects making a copy of any list item being inserted that is al
ready in another list implementation status unknown crossorigin attribute for <image> and <script> elements not implemented yet (at least for <image>; bug 1240357) rendering model change notes svg root and <foreignobject> not overflow:hidden in ua style sheet implementation status unknown allow overflow: auto; to clip and show scroll bars i...
Subresource Integrity - Web security
therefore, the resource must be served with an access-control-allow-origin header that allows the resource to be shared with the requesting origin; for example: access-control-allow-origin: * examples in the following examples, assume that oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc is al
ready known to be the expected sha-384 hash (digest) of a particular script example-framework.js, and there’s a copy of the script hosted at https://example.com/example-framework.js.
Using shadow DOM - Web Components
high-level view this article assumes you are al
ready familiar with the concept of the dom (document object model) — a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an html document in the case of web documents).
Caching compiled WebAssembly modules - WebAssembly
we start by trying to open a database, then see if we al
ready have a compiled module with the key url stored in the given db: return opendatabase().then(db => { return lookupindatabase(db).then(module => { if we do, we instantiate it with the given import object: console.log(`found ${url} in wasm cache`); return webassembly.instantiate(module, importobject); }, if not, we compile it from scratch and then store the compiled module i...
Using the WebAssembly JavaScript API - WebAssembly
if you have al
ready compiled a module from another language using tools like emscripten, or loaded and run the code yourself, the next step is to learn more about using the other features of the webassembly javascript api.
WebAssembly
webassembly.module() a webassembly.module object contains stateless webassembly code that has al
ready been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.