Search completed in 1.27 seconds.
1228 results for "done":
Your results are loading. Please wait...
mozbrowseractivitydone
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The mozbrowseractivitydone event is fired when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. ...
...s a web activity, and that web activity's message is consumed by the receiving app. If the activity has a returnValue set to true, then the activity is consumed when postResult or postError is invoked on the activity by the receiving app. Note: For activities where the receiving app's activity definition in its manifest does not include returnValue or returnValue is false, no mozbrowseractivitydone event will be generated as of the landing of bug 1194525 in Firefox OS 2.5. postResult and postError calls made on such an activity will be ignored and have no effect. General info Specification Non standard Interface CustomEvent Bubbles Yes Cancelable Yes Target <iframe> Default Action None Properties Property Type Description target Read only E...
...s cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: success A Boolean that indicates whether the activity has completed successfully (true) or not (false). ...
loadOneTab - Archive of obsolete content
}) Return type: tab element Opens a new tab that loads a page with the specified URL. The rest of the parameters are optional. This method works the same as addTab except for the loadInBackground parameter which allows you to choose whether to open the new tab in foreground or background. There's also no owner parameter as the owner tab is specified automatically. Parameters inBackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab. ...
NSS Sample Code Sample1
ey(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 already a private key with this name. // If there is one, no further action is required. ...
...Params rsaParams; SECStatus s; // See if there is already a private key with this name. // If there is one, no further action is required. ...
...eKey(&prvKey); if (rv == 0 && prvKey) goto done; rv = 0; // These could be parameters to the Init function rsaParams.keySizeInBits = 1024; rsaParams.pe = 65537; slot = PK11_GetInternalKeySlot(); if (!slot) { rv = 1; goto done; } prvKey = PK11_GenerateKeyPair(slot, CKM_RSA_PKCS_KEY_PAIR_GEN, &rsaParams, &pubKey, PR_TRUE, PR_TRUE, 0); if (!prvKey) { rv = 1; goto done; } // Set the nickname on the private key so that it // can be found later. ...
...And 24 more matches
Index - Web APIs
Web › API › Index
API, Format, MIME, MIME Type, Property, Reference, Type The type property of a Blob object returns the MIME type of the file. 294 BlobBuilder API, DOM, DOM Reference, File API, Obsolete, Reference The BlobBuilder interface provides an easy way to construct Blob objects. Just create a BlobBuilder and append chunks of data to it by calling the append() method. When you're done building your blob, call getBlob() to retrieve a Blob containing the data you sent into the blob builder. 295 BlobEvent API, Audio, Blob, Interface, Media, MediaStream Recording, MediaStream Recording API, Recording Media, Reference, Video, events The BlobEvent interface represents events associated with a Blob. These blobs are typically, but not necessarily, associated with...
... 528 Hit regions and accessibility Canvas, Graphics, Tutorial The content inside the <canvas> ... </canvas> tags can be used as a fallback for browsers which don't support canvas rendering. It's also very useful for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done: 529 Optimizing canvas Advanced, Canvas, Graphics, HTML, HTML5, Tutorial This article provides suggestions for optimizing your use of the canvas element to ensure that your graphics perform well. 530 Pixel manipulation with canvas Canvas, Graphics, Intermediate, Tutorial The ImageData object represents the underlying pixel data of an area of a canvas obje...
...hod, Reference, Web Components The document.registerElement() method registers a new custom element in the browser and returns a constructor for the new element. 959 Document.releaseCapture() API, DOM, Method, Reference The releaseCapture() method releases mouse capture if it's currently enabled on an element within this document. Enabling mouse capture on an element is done by calling element.setCapture(). 960 Document.requestStorageAccess() API, DOM, Document, Method, Reference, Storage Access API, requestStorageAccess The requestStorageAccess() method of the Document interface returns a Promise that resolves if the access to first-party storage was granted, and rejects if access was denied. 961 Document.scripts API, Document, HT...
...And 14 more matches
Xptcall Porting Status
de. This is being maintained by John Bandhauer <jband@netscape.com>. Feel free to email me with questions or to volunteer to contribute xptcall code for any platform. Mike Shaver <shaver@mozilla.org> is the best contact regarding 'nix (Unix, Linux, Finux, etc.) ports of xptcall. ...
... me with questions or to volunteer to contribute xptcall code for any platform. Mike Shaver <shaver@mozilla.org> is the best contact regarding 'nix (Unix, Linux, Finux, etc.) ports of xptcall. ...
...t contact regarding 'nix (Unix, Linux, Finux, etc.) ports of xptcall. Status Status Platform Contributors and <font color="red">?</font> Possible Contributors Notes <font color="white">Done</font> Win32 x86 John Bandhauer <jband@netscape.com> win32 <font color="white">Done</font> Linux x86 John Bandhauer <jband@netscape.com> Ulrich Drepper <drepper@cygnus.com> unix <font color="white">Done</font> FreeBSD and NetBSD x86 Christoph Toshok <toshok@hungry.com>, John Bandhauer <jband@netscape.com> unix (same as Linux 86 code) <font color="white">Done</font> BSD/OS x86 Bert Driehuis <bert_driehuis@nl.compuware.com> unix (same as Linux 86 code) Bert contributed patches that *should* do the right thing for all the unixish-x86 versions of this code for GCC 2.7 or 2.8 vs. EGCS 1.1. He no...
...And 12 more matches
Iteration protocols - JavaScript
defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated. An object is an iterator when it implements a next() method with the following semantics: Property Value next() A zero-argument function that returns an object with at least the following two properties: done (boolean) Has the value false if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.) Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator. value Any JavaScript value returned by the iterator. Can be omitted...
...ean) Has the value false if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.) Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator. value Any JavaScript value returned by the iterator. Can be omitted when done is true. The next() method must always return an object with appropriate properties including done and value. If a non-object value gets returned (such as false or undefined), a TypeError ("iterator.next() returned a non-object value") will be thrown. Note: It is not possible to know reflectively whether a particular object implements the iterator protocol. However, it is easy...
...s using the iteration protocols A String is an example of a built-in iterable object: let someString = 'hi'; console.log(typeof someString[Symbol.iterator]); // "function" String's default iterator returns the string's code points one by one: let iterator = someString[Symbol.iterator](); console.log(iterator + ''); // "[object String Iterator]" console.log(iterator.next()); // { value: "h", done: false } console.log(iterator.next()); // { value: "i", done: false } console.log(iterator.next()); // { value: undefined, done: true } Some built-in constructs--such as the spread syntax--use the same iteration protocol under the hood: console.log([...someString]); // ["h", "i"] You can redefine the iteration behavior by supplying our own @@iterator: // need to construct a String object expl...
...And 10 more matches
Creating our first Vue component - Learn web development
validation functions are invoked before the component instance is created, so they do not have access to the component state (or other props). For this component, we'll use the object registration method. Go back to your ToDoItem.vue file. Add a props property inside the export default {} object, which contains an empty object. Inside this object, add two properties with the keys label and done. The label key's value should be an object with 2 properties (or props, as they are called in the context of being available to the components). The first is a required property, which will have a value of true. This will tell Vue that we expect every instance of this component to have a label field. Vue will warn us if a ToDoItem component does not have a label field. The second proper...
...f true. This will tell Vue that we expect every instance of this component to have a label field. Vue will warn us if a ToDoItem component does not have a label field. The second property we'll add is a type property. Set the value for this property as the JavaScript String type (note the capital "S"). This tells Vue that we expect the value of this property to be a string. Now on to the done prop. First add a default field, with a value of false. This means that when no done prop is passed to a ToDoItem component, the done prop will will have a value of false (bear in mind that this is not required -- we only need default on non-required props). Next add a type field with a value of Boolean. This tells Vue we expect the value prop to be a JavaScript boolean type. Your...
... prop will will have a value of false (bear in mind that this is not required -- we only need default on non-required props). Next add a type field with a value of Boolean. This tells Vue we expect the value prop to be a JavaScript boolean type. Your component object should now look like this: <script> export default { props: { label: { required: true, type: String }, done: { default: false, type: Boolean } } }; </script> Using registered props With these props defined inside the component object, we can now use these variable values inside our template. Let's start by adding the label prop to the component template. In your <template>, replace the contents of the <label> element with {{label}}. {{}} is a special template syntax in Vue, which lets us prin...
...And 9 more matches
Using readable streams - Web APIs
xample shows (see it live also), exposing it is a matter of just accessing the body property of the response: // Fetch the original image fetch('./tortoise.png') // Retrieve its body as ReadableStream .then(response => response.body) This provides us with a ReadableStream object. Attaching a reader Now we've got our streaming body, reading the stream requires attaching a reader to it. This is done using the ReadableStream.getReader() method: // Fetch the original image fetch('./tortoise.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(body => { const reader = body.getReader(); Invoking this method creates a reader and locks it to the stream -- no other reader may read this stream until this reader is released, e.g. by invoking ReadableStreamDefaultRea...
...n the next section), then create a new Response out of it, consume it as a Blob, create an object URL out of that blob using URL.createObjectURL(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched. ...
...t of that blob using URL.createObjectURL(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched. ...
...And 9 more matches
Index
the application's code. Those handles are reference counted. NSS will usually create an in-memory (RAM) presentation of certificates, once a certificate has been received from the network, read from disk, or looked up from the database, and prepare in-memory data structures that contain the certificate's properties, as well as providing a handle for the programmer to use. Once the application is done with a handle, it should be released, allowing NSS to free the associated resources. When working with handles to private keys it's usually difficult (and undesired) that an application gets access to the raw key data; therefore it may be difficult to extract such data from NSS. The usual minimum requirement is that private keys must be wrapped using a protective layer (such as password-based enc...
... to use certificates, and to look up certificates by properties such as the contained subject name (information that describes the owner of the certificate). For example, while NSS supports random calculation (creation) of a new public/private key pair, it's difficult to work with such a raw key pair. The usual approach is to create a certificate signing request (CSR) as soon as an application is done with the creation step, which will have created a handle to the key pair, and which can be used for the necessary related operations, like producing a proof-of-ownership of the private key, which is usually required when submitting the public key with a CSR to a CA. The usual follow up action is receiving a signed certificate from a CA. (However, it's also possible to use NSS functionality to cre...
...ten involves allocating many individual data items, and the code might be required to abort a task at many positions in the logic. An arena is requested once processing of a task starts, and all memory allocations that are logically associated to that task are requested from the associated arena. The implementation of arenas makes sure that all individual memory blocks are tracked. Once a task is done, regardless whether it completed or was aborted, the programmer simply needs to release the arena, and all individually allocated blocks will be released automatically. Often freeing is combined with immediately erasing (zeroing, zfree) the memory associated to the arena, in order to make it more difficult for attackers to extract keys from a memory dump. NSS uses many C data structures. Often...
...And 8 more matches
Vue conditional rendering: editing existing todos - Learn web development
to our ToDoItem component. Specifically, we need to add a variable to track if the item is being edited, and a button to toggle that variable. We'll also add a Delete button since deletion is closely related. Update your ToDoItem's template as shown below. ...
... to true. To do that, we'll need to first define it inside our data() property. The "Delete" button, when clicked, will delete the todo item via an event handler function called deleteToDo(). In this handler we'll emit an item-deleted event to our parent component so the list can be updated. Let's define our click handlers, and the necessary isEditing flag. ...
...fine it inside our data() property. The "Delete" button, when clicked, will delete the todo item via an event handler function called deleteToDo(). In this handler we'll emit an item-deleted event to our parent component so the list can be updated. Let's define our click handlers, and the necessary isEditing flag. ...
...And 7 more matches
Rendering a list of Vue components - Learn web development
tem components. Adding some data to render First we need to get an array of to-do items. To do that, we'll add a data property to the App.vue component object, containing a ToDoItems field whose value is an array of todo items. While we'll eventually add a mechanism to add new todo items, we can start with some mock to do items. ...
...ms, we can start with some mock to do items. Each to-do item will be represented by an object with a name and a done property. Add a few sample to-do items, along the lines of those seen below. This way you have some data available for rendering using v-for. export default { name: 'app', components: { ToDoItem }, data() { return { ToDoItems: [ { label: 'Learn Vue', done: false }, { label: 'Create a Vue project with the CLI', done: true }, { label: 'Have fun', done: true }, { label: 'Create a to-do list', done: false } ] }; } }; Now that we have a list of items, we can use the v-for directive to display them. Directives are applied to elements like other attributes. In case of v-for, you use a special syntax similar to a for..
...your ToDoItems array, and assign each of them a value of uniqueId('todo-'). ...
...And 7 more matches
Generator.prototype.next() - JavaScript
The next() method returns an object with two properties done and value. You can also provide a parameter to the next method to send a value to the generator. Syntax gen.next(value) Parameters value The value to send to the generator. The value will be assigned as a result of a yield expression. For example, in variable = yield expression, the value passed to the .next() function will be assigned to variable. Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value An...
... done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. ...
...s is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. ...
...And 7 more matches
Floats - Learn web development
viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
... viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
... viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
...And 5 more matches
Client-side storage - Learn web development
rgetDiv.style.display = 'none'; rememberDiv.style.display = 'block'; } } Last but not least, we need to run the nameDisplayCheck() function every time the page is loaded. If we don't do this, then the personalized greeting will not persist across page reloads. Add the following to the bottom of your code: document.body.onload = nameDisplayCheck; Your example is finished -- well done! All that remains now is to save your code and test your HTML page in a browser. You can see our finished version running live here. Note: There is another, slightly more complex example to explore at Using the Web Storage API. Note: In the line <script src="index.js" defer></script> of the source for our finished version, the defer attribute specifies that the contents of the <script> eleme...
...already exist, it will be created for you by subsequent code. You will see this request pattern used very often throughout IndexedDB. Database operations take time. You don't want to hang the browser while you wait for the results, so database operations are asynchronous, meaning that instead of happening immediately, they will happen at some point in the future, and you get notified when they're done. To handle this in IndexedDB, you create a request object (which can be called anything you like -- we called it request so it is obvious what it is for). You then use event handlers to run code when the request completes, fails, etc., which you'll see in use below. Note: The version number is important. If you want to upgrade your database (for example, by changing the table structure),...
... add probably the most important event handler for setting up the database: request.onupgradeneeded. This handler runs if the database has not already been set up, or if the database is opened with a bigger version number than the existing stored database (when performing an upgrade). ...
...And 5 more matches
Drawing graphics - Learn web development
need to remove the margin and also set overflow to hidden. Add the following into the <head> of your document: <style> body { margin: 0; overflow: hidden; } </style> The scrollbars should now be gone. Note: You should generally set the size of the image using HTML attributes or DOM properties, as explained above. ...
... the sizing is done after the canvas has rendered, and just like any other image (the rendered canvas is just an image), the image could become pixellated/distorted. Getting the canvas context and final setup We need to do one final thing before we can consider our canvas template finished. To draw onto the canvas we need to get a special reference to the drawing area called a context. This is done using the HTMLCanvasElement.getContext() method, which for basic usage takes a single string as a parameter representing the type of context you want to retrieve. In this case we want a 2d canvas, so add the following JavaScript line below the others inside the <script> element: const ctx = canvas.getContext('2d'); Note: other context values you could choose include webgl for WebGL, webgl2 fo...
...Many operations need to be given coordinates to pinpoint exactly where to draw something -- the top left of the canvas is point (0, 0), the horizontal (x) axis runs from left to right, and the vertical (y) axis runs from top to bottom...
...And 5 more matches
Using Vue computed properties - Learn web development
uted properties. Using computed properties The aim here is to add a summary count of our to-do list. This can be useful for users, while also serving to label the list for assistive technology. If we have 2 of 5 items completed in our to-do list, our summary could read "3 items completed out of 5". While it might be tempting to do something like this: <h2>{{ToDoItems.filter(item => item.done).length}} out of {{ToDoItems.length}} items completed</h2> It would be recalculated on every render. For a small app like this, that probably doesn't matter too much. For bigger apps, or when the expression is more complicated, that could cause a serious performance problem. A better solution is to use Vue's computed properties. Computed Properties work similarly to methods, but only re-run whe...
...ted property to our component object, much like the methods property we've used previously. Adding a summary counter Add the following code to your App component object, below the methods property. The list summary method will get the number of finished ToDoItems, and return a string reporting this. computed: { listSummary() { const numberFinishedItems = this.ToDoItems.filter(item =>item.done).length return `${numberFinishedItems} out of ${this.ToDoItems.length} items completed` } } Now we can add {{listSummary}} directly to our template; we'll add this inside an <h2> element, just above our <ul>. We'll also add an id and an aria-labelledby attribute to assign the <h2> contents to be a label for the <ul> element. Add the described <h2> and update the <ul> inside your App's tem...
...ove our <ul>. We'll also add an id and an aria-labelledby attribute to assign the <h2> contents to be a label for the <ul> element. ...
...And 5 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
ue. Add a blank <template> and a <script> tag like before: <template></template> <script> export default {}; </script> Let's add in an HTML form that lets you enter a new todo item and submit it into the app. We need a <form> with a <label>, an <input>, and a <button>. Update your template as follows: <template> <form> <label for="new-todo-input"> What needs to be done? </label> <input type="text" id="new-todo-input" name="new-todo" autocomplete="off" /> <button type="submit"> Add </button> </form> </template> So we now have a form component into which we can enter the title of a new todo item (which will become a label for the corresponding ToDoItem when it is eventually rendered). Let's load this co...
... If you fill it out and click the "Add" button, the page will post the form back to the server, but this isn't really what we want. What we actually want to do is run a method on the submit event that will add the new todo to the ToDo...
... If you fill it out and click the "Add" button, the page will post the form back to the server, but this isn't really what we want. What we actually want to do is run a method on the submit event that will add the new todo to the ToDoItem data l...
...And 5 more matches
Introducing asynchronous JavaScript - Learn web development
ll come across in JavaScript code, old-style callbacks and newer promise-style code. In the below sections we'll review each of these in turn. Async callbacks Async callbacks are functions that are specified as arguments when calling a function which will start executing code in the background. When the background code finishes running, it calls the callback function to let you know the work is done, or to let you know that something of interest has happened. Using callbacks is slightly old-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used APIs. An example of an async callback is the second parameter of the addEventListener() method (as we saw in action above): btn.addEventListener('click', () => { alert('You clicked me!'); let pElem = docume...
... It will then move to the next line and begin executing the fetch() block but, because fetch() executes asynchronously without blocking, code execution continues after the promise-related code, thereby reaching the final console.log() statement (All ...
...!'); The browser will begin executing the code, see the first console.log() statement (Starting) and execute it, and then create the image variable. ...
...And 4 more matches
An overview of NSS Internals
the application's code. Those handles are reference counted. NSS will usually create an in-memory (RAM) presentation of certificates, once a certificate has been received from the network, read from disk, or looked up from the database, and prepare in-memory data structures that contain the certificate's properties, as well as providing a handle for the programmer to use. Once the application is done with a handle, it should be released, allowing NSS to free the associated resources. When working with handles to private keys it's usually difficult (and undesired) that an application gets access to the raw key data; therefore it may be difficult to extract such data from NSS. The usual minimum requirement is that private keys must be wrapped using a protective layer (such as password-based enc...
... to use certificates, and to look up certificates by properties such as the contained subject name (information that describes the owner of the certificate). For example, while NSS supports random calculation (creation) of a new public/private key pair, it's difficult to work with such a raw key pair. The usual approach is to create a certificate signing request (CSR) as soon as an application is done with the creation step, which will have created a handle to the key pair, and which can be used for the necessary related operations, like producing a proof-of-ownership of the private key, which is usually required when submitting the public key with a CSR to a CA. The usual follow up action is receiving a signed certificate from a CA. (However, it's also possible to use NSS functionality to cre...
...ten involves allocating many individual data items, and the code might be required to abort a task at many positions in the logic. An arena is requested once processing of a task starts, and all memory allocations that are logically associated to that task are requested from the associated arena. The implementation of arenas makes sure that all individual memory blocks are tracked. Once a task is done, regardless whether it completed or was aborted, the programmer simply needs to release the arena, and all individually allocated blocks will be released automatically. Often freeing is combined with immediately erasing (zeroing, zfree) the memory associated to the arena, in order to make it more difficult for attackers to extract keys from a memory dump. NSS uses many C data structures. Often...
...And 4 more matches
NSS Sample Code sample3
* If your application code has already initialized NSS, you can skip it * here. ...
... cout << "GetInternalKeySlot failed" << endl; status = 1; goto done; } /* * Part 1 - Simple hashing */ cout << "Part 1 -- Simple hashing" << endl; /* Initialize data */ memset(data, 0xbc, sizeof data); /* Create a context for hashing (digesting) */ context = PK11_CreateDigestContext(SEC_OID_MD5); if (!context) { cout << "CreateDigestContext failed" << endl; goto done; } s = PK11_DigestBegin(context); if (s != SECSuccess) { cout << "DigestBegin failed" << endl; goto done; } s = PK11_DigestOp(context, data, sizeof data); if (s != SECSuccess) { cout << "DigestUpdate failed" << endl; goto done; } s = PK11_DigestFinal(context, digest, &len, sizeof digest); if (s != SECSuccess) { cout << "DigestFinal failed" << endl; goto done; } /* Print digest *...
...(digest, len); PK11_DestroyContext(context, PR_TRUE); context = 0; /* * Part 2 - Hashing with included secret key */ cout << "Part 2 -- Hashing with included secret key" << endl; /* Initialize data */ memset(data, 0xbc, sizeof data); /* Create a Key */ key = PK11_KeyGen(slot, CKM_GENERIC_SECRET_KEY_GEN, 0, 128, 0); if (!key) { cout << "Create key failed" << endl; goto done; } cout << (void *)key << endl; /* Create parameters for crypto context */ /* NOTE: params must be provided, but may be empty */ SECItem noParams; noParams.type = siBuffer; noParams.data = 0; noParams.len = 0; /* Create context using the same slot as the key */ // context = PK11_CreateDigestContext(SEC_OID_MD5); context = PK11_CreateContextBySymKey(CKM_MD5, CKA_DIGEST, key, ...
...And 4 more matches
Index
Mozilla › Tech › XPCOM › Index
mozITXTToHTMLConv Interfaces The mozITXTToHTMLConv interface is used to convert text into HTML format. Its primary use is in converting user-entered text into properly-formatted HTML. 224 mozIThirdPartyUtil Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference Determine whether the given channel and its content window hierarchy is third party. This is done as follows: 225 mozIVisitInfo No summary! 226 mozIVisitInfoCallback Interfaces, Interfaces:Scriptable, Places, Reference, XPCOM Interface Reference Called when a mozIPlaceInfo couldn't be processed. 227 mozIVisitStatusCallback Interfaces, Interfaces:Scriptable, Places, Reference, XPCOM Interface Reference Called when the mozIAsyncHis...
...M, XPCOM API Reference, XPCOM Interface Reference Returns the name of one of the autocomplete search session objects. 351 nsIAutoCompleteItem Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference No summary! 352 nsIAutoCompleteListener Interfaces, Interfaces:Scriptable, NeedsContent Called by the autocomplete session when the search is done or over. As of Gecko 1.9.1, can also be called with partial results, in a similar manner to the toolkit autocomplete interface. 353 nsIAutoCompleteObserver Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference Called when a search is complete and the results are ready. 354 nsIAutoCompleteResult See nsIAutoCompleteSearch 355 nsIAu...
...lti-reporter. Implement this method to handle the report information. 737 nsIMemoryReporter Interfaces, Interfaces:Scriptable, NeedsContent, XPCOM, XPCOM Interface Reference Any piece of code that wishes to allow its memory use to be monitored may create an nsIMemoryReporter object and then register it by calling nsIMemoryReporterManager.registerReporter(). Once that has been done, the reporter will be found by any client accessing the enumerator returned by nsIMemoryReporterManager.enumerateReporters(). This includes the about:memory page. 738 nsIMemoryReporterManager Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference Implemented by @mozilla.org/memory-reporter-manager;1 as a service: 739 nsIMenuBoxObject Interfaces, In...
...And 4 more matches
WebIDL bindings
rResult&, if any, for the method. Note that this allows callees to declare their methods as taking an nsAString& or nsString& if desired. Strings in sequences, dictionaries, owning unions, and variadic arguments become nsString. Nullable strings are represented by the same types as non-nullable ones, but the string will return true for DOMStringIsNull(). Returning null as a string value can be done using SetDOMStringToNull on the out param if it's an nsAString or calling SetNull() on a DOMString. For example, this WebIDL: interface Test { DOMString myAttr; [Throws] DOMString myMethod(sequence<DOMString> arg1, DOMString? arg2, optional DOMString arg3); }; will correspond to these C++ function declarations: void GetMyAttr(nsString& retval); void SetMyAttr(const nsAString& value); v...
...e an nsACString& out param appended to the argument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for the method. In sequences, dictionaries owning unions, and variadic arguments it becomes nsCString. Nullable UTF8Strings are represented by the same types as non-nullable ones, but the string will return true for IsVoid(). Returning null as a string value can be done using SetIsVoid() on the out param. ByteString ByteString is reflected in three different ways, depending on use: ByteString arguments become const nsACString&. ByteString return values become an nsCString& out param appended to the argument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for the method. ByteString in sequences, dictionaries, owning unions, a...
...CString& out param appended to the argument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for the method. ByteString in sequences, dictionaries, owning unions, and variadic arguments becomes nsCString. Nullable ByteString are represented by the same types as non-nullable ones, but the string will return true for IsVoid(). Returning null as a string value can be done using SetIsVoid() on the out param. object object is represented in three different ways, depending on use: object arguments become JS::Handle<JSObject*>. They will be in the compartment of the passed-in JSContext. object return values become a JS::MutableHandle<JSObject*> out param appended to the argument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for ...
...And 4 more matches
Add to iPhoto
oes here } Shutting down Core Foundation While the Core Foundation system framework itself doesn't need to be shut down, we do need to close the library we opened using the js-ctypes API; that's where the shutdown() method comes in: shutdown: function() { this.lib.close(); } Select API declarations Let's take a look at a few of the key APIs we declare for Core Foundation, to see how it's done. CFRange CFRange is a structure that identifies a range; that is, it identifies an offset to an item in a list and a number of items. In C, the declaration looks like this: typedef struct { CFIndex location; CFIndex length; } CFRange; To declare this for use with js-ctypes, we use the following code: this.CFRange = new ctypes.StructType("CFRange", [ {'location': ...
...se methods are used to manage the reference counting for Core Foundation objects. CFString A CFString is an opaque data type that contains a string. The string can be stored in any of a number of encodings, so you use assorted functions that know how to cope with different encodings to set and get values of CFStrings, as well as to perform typical string operations. The first declaration to be done here is to actually declare the CFStringRef data type; this is an opaque pointer to a CFString object. this.CFStringRef = new ctypes.PointerType("CFStringRef"); Now that we've declared the core type, we can declare the methods we use that work with CFString objects. Let's take a look at one of these. this.CFStringCreateWithCharacters = this.lib.declare("CFStringCreateWithCharacters", ...
...le to reference that predefined structure from our code. ...
...And 4 more matches
ReadableStreamDefaultReader.read() - Web APIs
omise providing access to the next chunk in the stream's internal queue. Syntax var promise = readableStreamDefaultReader.read(); Parameters None. Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Exceptions TypeError The source object is not a ReadableStreamDefaultReader, or the stream has no owner. Examples Example 1 - simple example This example shows the basic A...
...the UI as an array of UTF-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. ...
... read, at which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. ...
...And 4 more matches
window.location - Web APIs
Web › API › Window › location
r: #0000ff; text-decoration: underline; } </style> </head> <body> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit v...
...rerit vitae, volutpat non ipsum.</p> <p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.</p> <p id="myBookmark1">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark...
...ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p> <p>Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus sit amet lectus vitae eros egestas pellentesque fermentum eget magna. Quisque mauris nisl, gravida vitae placerat et, condimentum id metus. Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p> <p>Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem ipsum dolor sit amet, consectetur adipisc...
...And 4 more matches
yield* - JavaScript
ples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax yield* expression; expression The expression which returns an iterable object. Description The yield* expression iterates over the operand and yields each value returned by it. ...
...by that iterator when it's closed (i.e., when done is true). Examples Delegating to another generator In following code, values yielded by g1() are returned from next() calls just like those which are yielded by g2(). ...
...e). Examples Delegating to another generator In following code, values yielded by g1() are returned from next() calls just like those which are yielded by g2(). function* g1() { yield 2; yield 3; yield 4; } function* g2() { yield 1; yield* g1(); yield 5; } const iterator = g2(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, done: false} console.log(iterator.next()); // {value: 4, done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: undefined, done: true} Other Iterable objects Besides generator objects, yield* can also yield other kinds of iterables (e.g., arrays, strings, or arguments objects). function...
...And 4 more matches
Index - Archive of obsolete content
ocales, which have been translated to French since non-latin characters are not well supported). 242 Hiding browser chrome Add-ons, Extensions, XUL, XULBrowserWindow There are times in which an extension may find it useful to hide browser chrome (that is, toolbars, the location bar, and so forth), in order to reduce clutter when presenting a particular user interface. This is done, for example, by the about:addons page. 243 Hotfix Extension This document has been moved to the Add-ons wiki. 244 How to convert an overlay extension to restartless Add-ons, Code snippets, Extensions, Firefox, Firefox OS, Guide, Preferences system No summary! 245 Inline options Add-ons, Extensions, XUL No summary! 246 Ins...
...tion reference and the object reference. 421 Developing New Mozilla Features Developing Mozilla, Outdated_articles Tips For Contributing New Features To Mozilla. 422 Devmo 1.0 Launch Roadmap MDC Project archives Comments, ideas, questions and other discussion should be added on the Devmo talk:1.0 Launch Roadmap page. Further details on smaller tasks being done are available at User:Dria:TODO page. See also Current Events. 423 Download Manager improvements in Firefox 3 Download Manager, Firefox 3 Firefox 3 offers improvements to the Download Manager that allow multiple progress listeners, use of the Storage API for data management, download resuming, and more. In addition, you can augment or replace the Download Manager's user inter...
...Then simply call nsIWebBrowser->do_GetInterface on the nsIWebBrowser to retrieve the nsIEditingSession from it. From there you call editingSession->MakeWindowEditable(domWindow, editortype, PR_TRUE). The first parameter is the nsIDOMWindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. In calling this method, the editor is created underneath and the event listeners are all prepa if (NS_FAILED(rv)) return NS_ERROR_FAILURE; // we are not setup??!! nsCOMPtr<nsIEditingSession> editingSession; nsIWebBrowser->do_GetInterface(getter_AddRefs(editingSession)); if (editingSession) editingSession->MakeWindowEditable(domWindow, "html", PR_TRU?E); 430 Embedding FAQ E...
...And 3 more matches
How to Write and Land Nanojit Patches - Archive of obsolete content
nanojit-central $ cd nanojit-central $ autoconf $ mkdir build $ cd build $ ../configure $ make $ make check Learn and setup automated testing for all three repositories. Write a script for copying patches between repositories, it'll come in useful. Scenario 1: creating an internal (ie. Nanojit-only) patch Write the patch in whichever repository you like. For Mozilla people it's probably best done in your tracemonkey repo, for Adobe people it's probably best done in your tamarin-redux repo. Once the patch seems ready, copy it to the other two repositories and test it. [njn: It's possible that the other TM/TR public repo hasn't been updated from nanojit-central sufficiently recently, in which case the patch won't apply cleanly. If the breakage is minor you'll be able to fix it by hand. I...
...e other two repositories and test it. [njn: It's possible that the other TM/TR public repo hasn't been updated from nanojit-central sufficiently recently, in which case the patch won't apply cleanly. If the breakage is minor you'll be able to fix it by hand. If it's major you'll need to do a private update of that other repo in order to test. But don't push that update, as that should only be done by a member of that public repo.] Once it passes testing, file the patch to Bugzilla (file a bug under the "Nanojit" component in the "Core" product) and get a review. Generally, patches by Mozilla people should be reviewed by Adobe people and vice versa. Once it passes review, land it on nanojit-central, mark the bug's whiteboard as fixed-in-nanojit, and note the revision in a comment. (Note tha...
... Adobe people and vice versa. Once it passes review, land it on nanojit-central, mark the bug's whiteboard as fixed-in-nanojit, and note the revision in a comment. (Note that nanojit-central revision URLs have the form http://hg.mozilla.org/projects/nanojit-central/<revid>, ie. there is a projects/ subdir in there. You might find it easier to just cut-and-paste links from the commit log.) You're done, but watch the Nanojit tinderbox for breakage. Scenario 2: creating an external patch Write and test the patch, as in scenario 1 above. Split the patch into three parts: nanojit, tracemonkey, tamarin. File them all in a single bug. Reviews should involve people from both Mozilla and Adobe. Once all the patches pass review, land the nanojit patch on nanojit-central and mark the bug as fixed-i...
...And 3 more matches
Grids - Learn web development
erra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
... Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> </article> <aside> <h2>Other things</h2> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est.</p> </aside> <footer>Contact me@mysite.com</footer> </div> Note: you can also use the value -1 to target the end column or row line, and count inwards from the end using negative values. However this only works for the explicit grid. The value -1 will not target th...
...erra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
...And 3 more matches
How to build custom form controls - Learn web development
ications are obvious so we will handle them, but it can be a real problem for exotic new controls. When it comes to standardized elements, of which the <select> is one, the specification authors spent an inordinate amount of time specifying all interactions for every use case for every input device. Creating new controls is not that easy, especially if you are creating something that has not been done before, and therefore which nobody has the slightest idea of what the expected behaviors and interactions are. At least select has been done before, so we know how it should behave! Designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard. For example, Apple introduced the scroll wheel with ...
...d the support of forEach to NodeList in order to make our life easier, like so: NodeList.prototype.forEach = function (callback) { Array.prototype.forEach.call(this, callback); } If you need to support legacy browsers, ensure the browsers support these features. If not, you can iterate through the list or you may need to use a library or pollyfill. Building event callbacks The groundwork is done. We can now start to define all the functions that will be used each time the user interacts with our control. // This function will be used each time we want to deactivate a custom control // It takes one parameter // select : the DOM node with the `select` class to deactivate function deactivateSelect(select) { // If the control is not active there is nothing to do if (!select.classList.c...
...ate its value according to user input and make it possible to send the value along with form data. The easiest way to do this is to use a native control under the hood. Such a control will keep track of the value with all the built-in controls provided by the browser, and the value will be sent as usual when a form is submitted. There's no point in reinventing the wheel when we can have all this done for us. As seen previously, we already 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. // It takes two parameters: // select : the DOM node with the class `select` containing the value to update // index : the index ...
...And 3 more matches
Bytecode Descriptions
MoreIter Stack: iter => iter, name Get the next property name for a for-in loop. iter must be a PropertyIteratorObject produced by JSOp::Iter. This pushes the property name for the next loop iteration, or MagicValue(JS_NO_ITER_VALUE) if there are no more enumerable properties to iterate over. The magic value must be used only by JSOp::IsNoIter and JSOp::EndIter. IsNoIter Stack: val => val, done Test whether the value on top of the stack is MagicValue(JS_NO_ITER_VALUE) and push the boolean result. IterNext Stack: val => val No-op instruction to hint to IonBuilder that the value on top of the stack is the string key in a for-in loop. EndIter Stack: iter, iterval => Exit a for-in loop, closing the iterator. iter must be a PropertyIteratorObject pushed by JSOp::Iter. Iteration Che...
...be Yield, InitialYield, or Await. Format: JOF_ICINDEX FinalYieldRval Stack: gen => Suspend and close the current generator, async function, or async generator. gen must be the generator object for the current frame. If the current function is a non-async generator, then the value in the frame's return value slot is returned to the caller. It should be an object of the form {value: returnValue, done: true}. 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 already be resolved or rejected. Yield Operands: (uint24_t resumeIndex) Stack: rval1, gen => rval2, gen, resumeKind Suspend execution of the current generator or async generator, returning rval1. For non-async generators, rval1 shoul...
...tion or async generator, the frame's return value slot must contain the current frame's result promise, which must already be resolved or rejected. Yield Operands: (uint24_t resumeIndex) Stack: rval1, gen => rval2, gen, resumeKind Suspend execution of the current generator or async generator, returning rval1. For non-async generators, rval1 should be an object of the form {value: valueToYield, done: true}. For async generators, rval1 should be the value to yield, and the caller is responsible for creating the iterator result object (under js::AsyncGeneratorYield). This instruction must appear only in scripts for generators and async generators. gen must be the generator object for the current stack frame. The resume point indicated by resumeIndex must be the next instruction in the script, ...
...And 3 more matches
nsITraceableChannel
utputstream;1', 'nsIBinaryOutputStream', 'setOutputStream'); var StorageStream = CC('@mozilla.org/storagestream;1', 'nsIStorageStream', 'init'); function TracingListener() { this.receivedChunks = []; // array for incoming data. ...
...am = CC('@mozilla.org/storagestream;1', 'nsIStorageStream', 'init'); function TracingListener() { this.receivedChunks = []; // array for incoming data. ...
...// array for incoming data. ...
...And 3 more matches
Iterators and generators - JavaScript
ion_protocols for...of function* and Generator yield and yield* Iterators In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value The next value in the iteration sequence. done This is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value. Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded addition...
... The most common iterator in JavaScript is the Array iterator, which simply returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary. ...
...spaced step apart. Its final return value is the size of the sequence it created, tracked by the variable iterationCount. ...
...And 3 more matches
function* - JavaScript
mmediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. ...
...If a value is returned, it will be set as the value property of the object returned by the generator. Much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. ...
...ned, it will be set as the value property of the object returned by the generator. Much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. When a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done: true}. Examples Simple example function* idMaker() { var index = 0; while (true) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ... Example with yield* function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } function* gen...
...And 3 more matches
Legacy layout methods - Learn web development
ula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> </div> <div> <h2>Second column</h2> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
...ula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> </div> <div> <h2>Second column</h2> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
... becoming too wide. Next, update the fourth CSS rule (with the .col selector) like so: .col { float: left; margin-left: 2.08333333%; width: 6.25%; background: rgb(255, 150, 150); } Now comes the slightly more laborious part -- we need to update all our .col.span rules to use percentages rather than pixel widths. This takes a bit of time with a calculator; to save you some effort, we've done it for you below. Update the bottom block of CSS rules with the following: /* Two column widths (12.5%) plus one gutter width (2.08333333%) */ .col.span2 { width: 14.58333333%; } /* Three column widths (18.75%) plus two gutter widths (4.1666666) */ .col.span3 { width: 22.91666666%; } /* And so on... */ .col.span4 { width: 31.24999999%; } .col.span5 { width: 39.58333332%; } .col.span6 { width: 4...
...And 2 more matches
Ember app structure and componentization - Learn web development
he default welcome page we saw in the previous article, when we first navigated to our server at localhost:4200. However, we don't want this. Instead, we want it to contain the TodoMVC app structure. To start with, delete the contents of application.hbs and replace them with the following: <section class="todoapp"> <h1>todos</h1> <input class="new-todo" aria-label="What needs to be done?" placeholder="What needs to be done?" autofocus > </section> Note: aria-label provides a label for assistive technology to make use of -- for example, for a screenreader to read out. This is useful in such cases where we have an <input> being used with no corresponding HTML text that could be turned into a label. When you save application.hbs, the development server you started ear...
...ou started earlier will automatically rebuild the app and refresh the browser. The rendered output should now look like this: It doesn't take too much effort to get our HTML looking like a fully-featured to-do list app. ...
...uild the app and refresh the browser. The rendered output should now look like this: It doesn't take too much effort to get our HTML looking like a fully-featured to-do list app. ...
...And 2 more matches
Introduction to cross browser testing - Learn web development
n browsers with limited capabilities. People with disabilities, who use the Web with the aid of assistive technologies like screenreaders, or don't use a mouse (some people use only the keyboard). Remember that you are not your users -- just because your site works on your Macbook Pro or high-end Galaxy Nexus, doesn't mean it will work for all your users -- there's a whole lot of testing to be done! Note: Make the web work for everyone provides more useful perspective on the different browsers people use, their market share, and related cross browser compatibility issues. We should explain a few bits of terminology here. To start with, when we talk about sites "working cross browser", we are really saying that they should provide an acceptable user experience across different browsers. ...
...across different browsers. It is potentially OK for a site to not deliver the exact same experience on all browsers, as long as the core functionality is accessible in some way. On modern browsers you might get something animated, 3D and shiny, whereas on older browsers you might just get a flat graphic representing the same information. As long as the site owner is happy with this, then you have done your job. On the other hand, it is not OK for a site to work fine for sighted users, but be completely inaccessible for visually impaired users because their screen reader application can't read any of the information stored on it. Second, when we say "across an acceptable number of web browsers", we don't mean 100% of the browsers in the world -- this is just about impossible. You can make som...
... but differences and bugs still creep through sometimes. some browsers may have different levels of support for technology features than others. This is inevitable when you are dealing with bleeding edge features that browsers are just getting round to implementing, or if you have to support really old browsers that are no longer being developed, which may have been frozen (i.e. no more new work done on them) a long time before a new feature was even invented. As an example, if you want to use cutting edge JavaScript features in your site, they might not work in older browsers. If you need to support older browsers, you might have to not use those, or convert your code to old fashioned syntax using some kind of cross-compiler where needed. some devices may have constraints that cause a web s...
...And 2 more matches
Setting up your own test automation environment - Learn web development
oject folder, then enter the following command: node google_test_multiple If you are using a Mac and do decide to test Safari, you might get an error message along the lines of "Could not create a session: You must enable the 'Allow Remote Automation' option in Safari's Develop menu to control Safari via WebDriver." If you get this, follow the given instruction and try again. So here we've done the test as before, except that this time we've wrapped it inside a function, searchTest(). We've created new browser instances for multiple browsers, then passed each one to the function so the test is performed on all three browsers! Fun huh? Let's move on, look at the basics of WebDriver syntax, in a bit more detail. WebDriver syntax crash course Let's have a look at a few key features of t...
.../tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html'); Interacting with the document Now we've got a document to test, we need to interact with it in some way, which usually involves first selecting a specific element to test something about. You can select UI elements in many ways in WebDriver, including by ID, class, element name, etc. The actual selection is done by the findElement() method, which accepts as a parameter a selection method. For example, to select an element by ID: const element = driver.findElement(By.id('myElementId')); One of the most useful ways to find an element by CSS -- the By.css method allows you to select an element using a CSS selector Enter the following at the bottom of your quick_test.js code now: const button = driver.f...
...r a certain length of time, and then carries on executing the code. This also makes use of the util library, which defines common conditions to use along with wait(). Shutting down drivers after use After you've finished running a test, you should shut down any driver instances you've opened, to make sure that you don't end up with loads of rogue browser instances open on your machine! This is done using the quit() method. Simply call this on your driver instance when you are finished with it. Add this line to the bottom of your quick_test.js test now: driver.quit(); When you run it, you should now see the test execute and the browser instance shut down again after the test is complete. This is useful for not cluttering up your computer with loads of browser instances, especially if you h...
...And 2 more matches
Debugging on Mac OS X
item, select 'Add files to "<project-name>"', select all the files and directories in your source directory, untick "Copy items if needed", then click Add. (These will then be progressively added under the root item <project-name> in the left-hand pane. Note that subdirectories may initially appear to be empty, but they too will progressively be populated as Xcode processes the sourse files. Once done, you should be able to open any file quickly by hitting Cmd-Shift-O and typing in the name of a file.) In the Product menu, select Scheme > New Scheme and name your scheme (for example, "Debug"). After you click OK, Xcode should open the settings window for the new scheme. (If not, then open its settings from the Product > Edit Scheme menu.) Select "Run" on the left-hand side of the settings wi...
... Having a profile for debugging purposes It is recommended to create a separate profile to debug with, whatever your task, so that you don't lose precious data like Bookmarks, saved passwords, etc. So that you're not bothered with the profile manager every time you start to debug, expand the "Executables" branch of the "Groups & Files" li...
...ou don't lose precious data like Bookmarks, saved passwords, etc. So that you're not bothered with the profile manager every time you start to debug, expand the "Executables" branch of the "Groups & Files" list and double click on the Executable you added for Mozilla. Click the plus icon under the "Arguments" list and type "-P <profile name>" (e.g. "-P MozillaDebug"). Close the window when you're done. Running a debug session Make sure breakpoints are active (which implies running under the debugger) by opening the Product menu and selecting "Debug / Activate Breakpoints" (also shown by the "Breakpoints" button in the top right section of the main window). Then click the "Run" button or select "Run" from the Product menu. Setting breakpoints Setting a breakpoint is easy. Just open the sour...
...And 2 more matches
Intensive JavaScript - Firefox Developer Tools
e main thread and the worker thread can't call each other directly, but communicate using an asynchronous messaging API. ...
...emoveEventListener("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. Then we need a new file "calculate.js", that looks like this: self.addEventListener("message", go); function go(message) { var iterations = message.data.iterations; var multiplier = message.data.multiplier; primes = calculatePrimes(iterations, multiplier); self.postMessage({ "command":"done", "primes": primes }); } function c...
...The code that actually performs the computations is exactly the same as the original code. So how does this version perform? Switch the radio button to "Use a worker", and capture a new profile. You should see something like this: In this profile we pushed the button three times. Compared with the original, each button-press is visible in the overview as two ve...
...And 2 more matches
Element.classList - Web APIs
Web › API › Element › classList
his.length; i !== Len; ++i) f( this[i], i, this); else for (var i=0,Len=this.length,tArg=arguments[1]; i !== Len; ++i) f.call(tArg, this[i], i, this); }; if (!DOMTokenListProto.entries) DOMTokenListProto.entries = function(){ var nextIndex = 0, that = this; return {next: function() { return nextIndex<that.length ? ...
...= Len; ++i) f( this[i], i, this); else for (var i=0,Len=this.length,tArg=arguments[1]; i !== Len; ++i) f.call(tArg, this[i], i, this); }; if (!DOMTokenListProto.entries) DOMTokenListProto.entries = function(){ var nextIndex = 0, that = this; return {next: function() { return nextIndex<that.length ? ...
..., that = this; return {next: function() { return nextIndex<that.length ? {value: [nextIndex, that[nextIndex++]], done: false} : {done: true}; }}; }; if (!DOMTokenListProto.values) DOMTokenListProto.values = function(){ var nextIndex = 0, that = this; return {next: function() { return nextIndex<that.length ? {value: that[nextIndex++], done: false} : {done: true}; }}; }; if (!DOMTokenListProto.keys) DOMTokenListProto.keys = function(){ var nextIndex = 0, that = this; return {next: function() { return nextIndex<that.length ? ...
...And 2 more matches
Element.scrollHeight - Web APIs
s egestas. Praesent dictum ipsum aliquet erat eleifend sit amet sollicitudin felis tempus. Aliquam congue cursus venenatis. Maecenas luctus pellentesque placerat. Mauris nisl odio, condimentum sed fringilla a, consectetur id ligula. Praesent sem sem, aliquet non faucibus vitae, iaculis nec elit. Nullam volutpat, lectus et blandit bibendum, nulla lorem congue turpis, ac pretium tortor sem ut nibh. ...
...at eleifend sit amet sollicitudin felis tempus. Aliquam congue cursus venenatis. Maecenas luctus pellentesque placerat. Mauris nisl odio, condimentum sed fringilla a, consectetur id ligula. Praesent sem sem, aliquet non faucibus vitae, iaculis nec elit. Nullam volutpat, lectus et blandit bibendum, nulla lorem congue turpis, ac pretium tortor sem ut nibh. Donec vel mi in ligula hendrerit sagittis. Donec faucibus viverra fermentum. ...
...Proin et tortor dolor. Ut aliquet, dolor a mattis sodales, odio diam pulvinar sem, egestas pretium magna eros vitae felis. Nam vitae magna lectus, et ornare elit. ...
...And 2 more matches
Using files from web applications - Web APIs
If you want to use the DOM File API from extensions or other browser chrome code, you can; however, note there are some additional features to be aware of. See Using the DOM File API in chrome code for details. ...
... on the design of your application, but making an element receive drop events is easy: let dropbox; dropbox = document.getElementById("dropbox"); dropbox.addEventListener("dragenter", dragenter, false); dropbox.addEventListener("dragover", dragover, false); dropbox.addEventListener("drop", drop, false); In this example, we're turning the element with the ID dropbox into our drop zone. This is done by adding listeners for the dragenter, dragover, and drop events. We don't actually need to do anything with the dragenter and dragover events in our case, so these functions are both simple. They just stop propagation of the event and prevent the default action from occurring: function dragenter(e) { e.stopPropagation(); e.preventDefault(); } function dragover(e) { e.stopPropagation(); ...
...rc = e.target.result; }; })(img); reader.readAsDataURL(file); } } Here our loop handling the user-selected files looks at each file's type attribute to see if its MIME type begins with the string "image/"). For each file that is an image, we create a new img element. CSS can be used to establish any pretty borders or shadows and to specify the size of the image, so that doesn't need to be done here. Each image has the CSS class obj added to it, making it easy to find in the DOM tree. We also add a file attribute to each image specifying the File for the image; this will let us fetch the images for actual upload later. We use Node.appendChild() to add the new thumbnail to the preview area of our document. Next, we establish the FileReader to handle asynchronously loading the image and...
...And 2 more matches
Timing element visibility with the Intersection Observer API - Web APIs
ly the Intersection Observer API to your own site. There's a good reason why the notion of tracking visibility of ads is being used in this example. It turns out that one of the most common uses of Flash or other script in advertising on the Web is to record how long each ad is visible, for the purpose of billing and payment of revenues. Without the Intersection Observer API, this winds up being done using intervals and timeouts for each individual ad, or other techniques that tend to slow the page down. Using this API lets everything get streamlined by the browser to reduce the impact on performance substantially. Let's get started! Site structure: The HTML The site's structure is not too complicated. We'll be using CSS Grid to style and lay out the site, so we can be pretty straightforw...
...le at the current time, so that they will not add up the duration of time the page was tabbed away the next time they're updated. Handling intersection changes Once per pass through the browser's event loop, each IntersectionObserver checks to see if any of its target elements have passed through any of the observer's intersection ratio thresholds. For each observer, a list of targets that have done so is compiled, and sent to the observer's callback as an array of IntersectionObserverEntry objects. Our callback, intersectionCallback(), looks like this: function intersectionCallback(entries) { entries.forEach(function(entry) { let adBox = entry.target; if (entry.isIntersecting) { if (entry.intersectionRatio >= 0.75) { adBox.dataset.lastViewStarted = entry.time; ...
...milliseconds the timer has been visible since the last time it became visible. This is added to the current value of the ad's totalViewTime to bring the total up to date. Note the use of parseFloat() here; because these values are strings, JavaScript tries to do a string concatenation instead of addition without it. Finally, the last-viewed time for the ad is updated to the current time. This is done whether the ad was running when this function was called or not; this causes the ad's timer to always be running when this function returns. This makes sense because this function is only called if the ad is visible, even if it's just now become visible. Drawing an ad's timer Inside each ad, for demonstration purposes, we draw the current value of its totalViewTime, converted into minutes and s...
...And 2 more matches
Authoring MathML - MathML
ed. Client-side Conversion In a Web environment, the most obvious method to convert a simple syntax into a DOM tree is to use Javascript and of course many libraries have been developed to perform that task. pros: This is very easy setup: only a few Javascript and CSS files to upload and/or a link to add to your document header. ...
..."<" for tags or "$" for money amounts) You may need to synchronize the Javascript converter with other Javascript programs on your page. ...
...=https://fred-wang.github.io/mathjax.js/mpadded-min.js foo.tex # Add the MathJax fallback If your LaTeX document is big, you might want to split it into several small pages rather than putting everything in a single large page. For example, this will split the pages at the \section level: latexmlc --dest foo.html --splitat=section foo.tex Server-side Conversion pros: Conversion is done server-side and the MathML output can be cached, which is more efficient and cleaner than client-side conversion. cons: This might be a bit more difficult to set up, since you need some admin right on your server. TeXZilla, LaTeXML and Mathoid and can be used to to perform server-side LaTeX-to-MathML conversion. Instiki and MediaWiki are two wiki engines that support LaTeX-to-M...
...And 2 more matches
test/utils - Archive of obsolete content
Before and After Helper functions before() and after() are available for running a function before or after each test in a suite. They're useful when you need to guarantee a particular state before running a test, and to clean up after your test. ...
... each test in a suite. They're useful when you need to guarantee a particular state before running a test, and to clean up after your test. ...
...('sdk/places/bookmarks'); exports.testCountBookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeAllBookmarks(); }); require('sdk/test').run(exports); Both before and after may be asynchronous. ...
...(exports, function (name, assert) { removeAllBookmarks(); }); require('sdk/test').run(exports); Both before and after may be asynchronous. To make them asynchronous, pass a third argument done, which is a function to call when you have finished: let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testCountBookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert, done) { removeAllBookmarksAsync(function () { done(); }); }); require('sdk/test').run(exports); Globals Functions before(exports, beforeFn) Runs beforeFn before each test in the file. May be asynchronous if beforeFn accepts...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
ing generated, remotely retrieved code, is generally not secure. It might be possible to execute any retrieved JSONP code in an unprivileged Sandbox (which is complicated!), but if you have a choice, just avoid JSONP altogether! Passing around functions/code as strings Often you'll want to pass functions or code to other functions, most notoriously setTimeout and addEventListener. Often this is done passing around strings. // DO NOT USE! setTimeout("doSomething();", 100); addEventListener("load", "myAddon.init(); myAddon.onLoad();", true); setInterval(am_I_a_string_or_function_reference_qmark, 100); That in itself is certainly not elegant, but it may also become a security issue if you pass code that was externally retrieved (or at least contains bits of externally retrieved data): // DO...
... Alternative: Use (anonymous) functions You can always create a small anonymous function to pass around instead. Closures will ensure the code is still valid, even if your outer function already retur...
... Alternative: Use (anonymous) functions You can always create a small anonymous function to pass around instead. Closures will ensure the code is still valid, even if your outer function already returned from execution. addEventListener("load", function() { myA...
...var _original = gBrowser.addTab; // Override a function. gBrowser.addTab = function() { // Execute some action before the original function call. try { myAddon.onAddTab(arguments[0]); } catch (ex) { /* might handle this */ } // Execute original function. var rv = _original.apply(gBrowser, arguments); // Execute some action afterwards. try { myAddon.doneAddTab(rv); } catch (ex) { /* might handle this */ } // return the original result return rv; }; })(); This is admittedly a bit more verbose, but at the same time it should be easier to understand. You don't have to parse what the resulting function will look like in your mind. There won't be any problems if various Add-ons override the same function (using this method). You...
Local Storage - Archive of obsolete content
e data there, so that if the user chooses to install the extension again, all the previous data will be recovered. This is the default behavior when Firefox is uninstalled: the profile information remains intact and it will be there waiting for you if Firefox is installed again. Others feel concerned about privacy and storing private information locally without deleting it. A good argument can be done for both, so it is up to you to choose what to do in this case. The FUEL library has an uninstall event you can use to perform these operations. Logging Good logging is essential in all kinds of software projects. Any extension that is more complex than a Hello World needs some way to log errors and trace execution without having to fire up a debugger. It used to be the case that custom loggin...
...g4Moz.Level["All"]; root.addAppender(appender); After that, you can create a logger object for any object in your project like this: this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject"); this._logger.level = Log4Moz.Level["All"]; Note: We recommend that you create a logger instance in the constructor of every object and store it in a private variable. ...
...or warn levels, and in general you should use logging freely in order to have as much information as possible to fix bugs and know what is going on. Don't log inside functions that are called too often, such as mouseover event handlers, or certain HTTP activity listeners. This impacts performance and fills the log with useless messages. We normally add a comment that indicates that logging is not done there for performance reasons. SQLite SQLite storage was introduced in Firefox 2, and it's the preferred storage mechanism in Firefox. It is the storage system used for the Places API that manages bookmarks and history. It's also used for storing cookies, form inputs, and others. SQLite is a lightweight SQL based storage system. It is ideal for embedding in other programs, and is currently in ...
... can take when creating the local database you'll be using for your extension: Generate the database file (through mozIStorageService.openDatabase(), all tables (through mozIStorageConnection.createTable(), and initial data when your extension starts up for the first time. If you need a complex database this can be heavy in terms of time and code, but this will only happen once and this can be done in a lazy or asynchronous way. Have an initial database file in your defaults directory that you can copy to the user's profile. This way you just need to do a file copy. You can reach the defaults directory at ProfD/extensions/YOUR_EXTENSION_ID.xpi/defaults for packed extensions or ProfD/extensions/YOUR_EXTENSION_ID/defaults for unpacked extensions. Packed extensions have appear with Gecko 2.0 ...
Introduction to CSS layout - Learn web development
viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
...icula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <div class="positioned">Sticky</div> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
...y ordinary, except for the uses of the display property. The <form>, <div>s, and <label>s and <input>s have been told to display like a table, table rows, and table cells respectively -- basically, they'll act like HTML table markup, causing the labels and inputs to line up nicely by default. All we then have to do is add a bit of sizing, margin, etc. to make everything look a bit nicer and we're done. You'll notice that the caption paragraph has been given display: table-caption; -- which makes it act like a table <caption> -- and caption-side: bottom; to tell the caption to sit on the bottom of the table for styling purposes, even though the markup is before the <input> elements in the source. This allows for a nice bit of flexibility. html { font-family: sans-serif; } form { display:...
...egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
Multiple-column layout - Learn web development
egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis ...
... egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis ...
... egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis ...
...ing subhead</h2> Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis ...
Graceful asynchronous programming with Promises - Learn web development
e 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. We're able to chain multiple asynchronous actions to occur one after another this way because each .then() block returns a new promise that resolves when the .then() block is done running. Clever, right? Using arrow functions, you can simplify the code even further: chooseToppings() .then(toppings => placeOrder(toppings) ) .then(order => collectOrder(order) ) .then(pizza => eatPizza(pizza) ) .catch(failureCallback); Or even this: chooseToppings() .then(toppings => placeOrder(toppings)) .then(order => collectOrder(order)) .then(pizza => eatPizza(pizza)) .catch(fai...
... Unfortunately, we need to do slightly more than this. Fetch promises do not fail on 404 or 500 errors -- only on something catasrophic like a network failure. Instead, they succeed, but with the response.ok property set to false. To produce an error on a 404, for example, we need to check the value of response.ok, and if false, throw an error, only returning the blob if it is true. This can be done like so -- add the following lines below your first line of JavaScript. let promise2 = promise.then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return response.blob(); } }); Each call to .then() creates a new promise. This is very useful; because the blob() method also returns a promise, we can handle the Blob object...
...this allows us to control error handling exactly how we want. In a real app, your .catch() block could retry fetching the image, or show a default image, or prompt the user to provide a different image URL, or whatever. Note: You can see our version of the example live (see the source code also). Chaining the blocks together This is a very longhand way of writing this out; we've deliberately done this to help you understand what is going on clearly. As shown earlier on in the article, you can chain together .then() blocks (and also .catch() blocks). The above code could also be written like this (see also simple-fetch-chained.html on GitHub): fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return ...
...ething like: let a = fetch(url1); let b = fetch(url2); let c = fetch(url3); Promise.all([a, b, c]).then(values => { ... }); When the promise is fulfilled, the values passed into the fulfilment handler would contain three Response objects, one for each of the fetch() operations that have completed. However, we don't want to do this. Our code doesn't care when the fetch() operations are done. Instead, what we want is the loaded data. That means we want to run the Promise.all() block when we get back usable blobs representing the images, and a usable text string. We can write a function that does this; add the following inside your <script> element: function fetchAndDecode(url, type) { return fetch(url).then(response => { if(!response.ok) { throw new Error(`HTTP error! ...
Styling Vue components with CSS - Learn web development
hes to styling apps: External CSS files. Global styles in Single File Components (.vue files). Component-scoped styles in Single File Components. To help familiarize you with each one, we'll use a combination of all three to give our app a nicer look and feel. Styling with external CSS files You can include external CSS files and apply them globally to your app. Let's look at how this is done. To start with, create a file called reset.css in the src/assets directory. Files in this folder get processed by Webpack. This means we can use CSS pre-processors (like SCSS) or post-processors (like PostCSS). While this tutorial will not be using such tools, it's good to know that when including such code in the assets folder it will be processed automatically. Add the following contents to ...
... margin-bottom: 1rem; } </style> If you check the app, you'll see that our todo list is now in a card, and we have some better formatting of our to-do items. Now we can go through and begin editing our components to use some of these styles. Adding CSS classes in Vue We should apply the button CSS classes to the <button> in our ToDoForm component. Since Vue templates are valid HTML, this is done in the same way to how you might do it in plain HTML -- by adding a class="" attribute to the element. Add class="btn btn__primary btn__lg" to your form's <button> element: <button type="submit" class="btn btn__primary btn__lg"> Add </button> While we're here, there's one more semantic and styling change we can make. Since our form denotes a specific section of our page, it could benefit fro...
...void repeating ourselves, let's wrap our label in an <h2>. There are a few other global CSS styles which we can add as well. We'll also add the input__lg class to our <input> element. Update your ToDoForm template so that it looks like this: <template> <form @submit.prevent="onSubmit"> <h2 class="label-wrapper"> <label for="new-todo-input" class="label__lg"> What needs to be done? </label> </h2> <input type="text" id="new-todo-input" name="new-todo" autocomplete="off" v-model.lazy.trim="label" class="input__lg" /> <button type="submit" class="btn btn__primary btn__lg"> Add </button> </form> </template> Let's also add the stack-large class to the <ul> tag in our App.vue file. This will help improve the ...
...-height: 1.31579; } } Now we need to add some CSS classes to our template to connect the styles. To the root <div>, add a custom-checkbox class. To the <input>, add a checkbox class. Last of all, to the <label> add a checkbox-label class. The updated template is below: The app should now have custom checkboxes. Your app should look something like the screenshot below. Summary Our work is done on the styling of our sample app. In the next article we'll return to adding some more functionlity to our app, namely using a computed property to add a count of completed todo items to our app. Previous Overview: Client-side JavaScript frameworks Next In this module Introduction to client-side frameworks Framework main features React Getting started with React Beginning ...
Handling common HTML and CSS problems - Learn web development
s appropriate. It is really easy and convenient to use, although it does have some downsides (see the link above for details), and it is arguable that parsing every stylesheet in your site and add prefixes at run time can be a drain on the computer's processing power for a large site. Another solution is to add prefixes automatically during development, and this (and other things besides) can be done using tools like Autoprefixer and PostCSS. These tools can be used in a variety of ways, for example Autoprefixer has an online version that allows you to enter your non-prefixed CSS on the left, and gives you a prefix-added version on the right. You can choose which browsers you want to make sure you support using the notation outlined in Autoprefixer options; also see Browserslist queries, whic...
... is based on, for more detail. As an example, the following query will select the last 2 versions of all major browsers and versions of IE above 9. last 2 versions, ie > 9 Autoprefixer can also be used in other, more convenient ways -- see Autoprefixer usage. For example, you can use it with a task runner/build tool such as Gulp or Webpack to automatically add prefixes once development has been done. (Explaining how these work is somewhat beyond the scope of this article.) You can also use a plugin for a text editor such as Atom or Sublime text. For example, in Atom: You can install it by going to Preferences > Install, searching for Autoprefixer, then hitting install. You can set a browser query by pressing the Autoprefixer Settings button and entering the query in the text field in th...
...tend to be more commonly associated with: Lack of (or differences in) support for modern layout features. Layouts not looking good in mobile browsers (i.e. responsive design problems). Note: Historically web developers used to use CSS files called resets, which removed all the default browser styling applied to HTML, and then applied their own styles for everything over the top -- this was done to make styling on a project more consistent, and reduce possible cross browser issues, especially for things like layout. However, it has more recently been seen as overkill. The best equivalent we have in modern times is normalize.css, a neat bit of CSS that builds slightly on the default browser styling to make things more consistent and fix some layout issues. You are advised to apply normali...
...ss to all your HTML pages. Note: When trying to track down a tricky layout issue, a good technique is to add a brightly colored outline to the offending element, or all the elements nearby. This makes it a lot easier to see where everything is placed. See Debug your CSS with outline visualizations for more details. Support for new layout features Much of the layout work on the web today is done using floats -- this is because floats are well-supported (way back to IE4, albeit with a number of bugs that would also need to be investigated if you were to try to support IE that far back). However, they are not really meant for layout purposes -- using floats the way we do is really a hack -- and they do have some serious limitations (e.g. see Why Flexbox?) More recently, dedicated layout m...
Introducing a complete toolchain - Learn web development
this as our development environment. Transformation: Tooling that allows us to use the latest features of a language (e.g. JavaScript) or another language entirely (e.g. JSX or TypeScript) in our development process, and then transforms our code so that the production version still runs on a wide variety of browsers, modern and older. Post development: Tooling that comes into play after you are done with the body of development to ensure that your software makes it to the web and continues to run. In this case study we'll look at adding tests to your code, and deploying your app using Netlify so it is available for all the web to see. Let's start working on these, beginning with our development environment. Creating a development environment This part of the toolchain is sometimes seen t...
...an look at this in the same way as setting up your physical work environment. The chair needs to be comfortable, and set up in a good position to help with your posture. You need power, Wifi, and USB ports! There might be important decorations or music that help with your mental state -- these are all important to doing your best work possible, and they should also only need to be set up once, if done properly. In the same way, setting up your development environment, if done well, needs doing only once and should be reusable in many future projects. You will probably want to review this part of the toolchain semi-regularly and consider if there's any upgrades or changes you should introduce, but this shouldn't be required too often. Your toolchain will depend on your own needs, but for this...
...w. You can check whether you've already got it installed globally using the following command: prettier -v If installed, you'll get a version number returned like 2.0.2; if not, it'll return something along the lines of "command not found". If this is the case, install it using the following command: npm install prettier -g Now that Prettier is installed, running and tidying your code can be done on the command line on an individual file basis from anywhere on your computer, for example: prettier --write ./src/index.html Note: In the command above, I use Prettier with the --write flag. Prettier understands this to mean "if there's problems in my code format, go ahead and fix them, then save my file". This is fine for our development process, but we can also use prettier without the fla...
...that you can quickly use it to check any file you want. For the sake of simplicity, in this chapter we're not going to explore all the features of eslint, but we will put a configuration in place that works for our particular project and its requirements. However, bear in mind that if you want to refine and enforce a rule about how your code looks (or validates), it's very likely that it can be done with the right eslint configuration. A little later in this chapter, we'll provide the eslint config. Once a working configuration is in place, running the command can generate some useful information. Here is an example eslint output: ./my-project/src/index.js 2:8 error 'React' is defined but never used no-unused-vars 22:20 error 'body' is defined but never used no-unused-vars 96:19 er...
Extending a Protocol
IPDL basics While you are compiling, let's cover some IPDL basics. In IPDL there two kinds of "actors" - a "parent" and "child" - these actors are literally implemented as C++ classes, so they are more than just abstract ideas. Usually, a child wants to send messages to the parent to do something off main thread for us. And we generally want the parent to let a child know when some work is done - and send some confirmation or result data back to the child. Sometimes, the parent will want to notify all its children of something. So communication can go in both directions. In this tutorial, we are just going to cover a child talking to a parent, and the parent responding with some data. In order to manage parent-child relationships, IPDL uses a tree herirachy to manage the creation o...
... mean, PWindowGlobal is in charge of contructing the parent/child relationship. Without this, we can't send messages. Anyway, let's put the above into practice by creating our custom protocol: PEcho.ipdl. Custom protocol - PEcho.ipdl This next part requires us to both specify the protocol and actually implement everything in C++. It's quite involved and, unfortunately, all steps need to be done before we can successfully recompile. We will try to compile our code as we go, noting what we need to do along the way. To be sure, IPDL looks like a crazy mix of WebIDL, C++ header files, and ES6. The syntax should hopefully be fairly obvious though. Unfortunately, it's not really fully documented anywhere - and the IPDL parser gets easily confused (hence us excluding comments below). C...
...puts("WindowGlobalParent::AllocPEchoParent was called"); RefPtr<EchoParent> actor = new EchoParent(); return actor.forget(); } bool WindowGlobalParent::DeallocPEchoParent( PEchoParent* aActor) { RefPtr actor = dont_AddRef(static_cast(aActor)); return true; } The "puts()" there will help us see what's going on once we get things going. Naturally, we want to remove that once we done implementing. Implementing methods on WindowGlobalChild.cpp So, now we need to do the child. Open up dom/ipc/WindowGlobalChild.cpp and let's implement: AllocPEchoChild() DeallocPEchoChild(PEchoChild* aActor) already_AddRefed<EchoChild> WindowGlobalChild::AllocPEchoChild() { RefPtr<EchoChild> actor = new EchoChild(); return actor.forget(); } bool WindowGlobalChild::DeallocPEchoChild...
... ...
source-editor.jsm
name constants. To stop listening for the event, call removeEventListener(). void addEventListener( String aEventType, Function aCallback ); Parameters aEventType The name of the event type to listen for; see Event name constants for possible values. aCallback The function to call when the specified event occurs. canRedo() Determines whether or not there are changes that can be redone. Boolean canRedo(); Parameters None. Return value true if there are changes that can be redone, otherwise false. canUndo() Determines whether or not there are changes that can be undone. Boolean canUndo(); Parameters None. Return value true if there are changes that can be undone, otherwise false. destroy() Destroys the editor, releasing resource it's allocated and removing event ...
... void destroy(); Parameters None. dropSelection() Deselects the currently selected text. void dropSelection(); Parameters None. endCompoundChange() Ends a compound change that was previously started by calling startCompoundChange(). ...
...used to configure the editor. See The editor configuration object for details. aCallback A function that will be called when the editor has been fully loaded and initialized. hasFocus() Determines whether or not the editor is currently focused. Boolean hasFocus(); Parameters None. Return value true if the editor is currently focused, otherwise false. redo() Redoes the most recently undone change in the editor. Boolean redo(); Parameters None. Return value true if a change was redone, otherwise false. removeBreakpoint Removes the breakpoint from the specified line of code. Boolean removeBreakpoint( Number aLineIndex ); Parameters aLineIndex The 0-based line number from which to remove the breakpoint. Return value true if a breakpoint was removed, otherwise false...
...dChange() Begins a compound change in the editor. All changes made between a call to startCompoundChange() and its corresponding call to endCompoundChange() are considered to be a single operation on the undo stack. void startCompoundChange(); Parameters None. undo() Undoes the most recent change made in the editor. Boolean undo(); Parameters None. Return value true if a change was undone or false if there were no changes to undo. The editor configuration object When you call init() to initialize the editor, you pass in an object that contains properties configuring the editor's features. That object may contain any combination of the following properties: Constant Type Description contextMenu String | Element A reference to the context menu to dis...
Application Translation with Mercurial
"de" for German). The localization lead for your language knows the branch. The default localization branch is aurora. Next check what is still untranslated by going to Localization status page and click on the page for your language. In the section "Applications & Sign-offs", you will find different products and branches which are currently in translation. gaia-* denotes branches of Firefox OS, the operating system for mobile devices. ...
...ortable with. This example uses Notepad++. Progress tracking tool To track which strings and files already have been translated and later also to see which new strings have already 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. This can be done in a text editor or word processor or any other tool in which you can attach different kind of states to the individual texts to translate. The Firefox extension Scrapbook is used in this guide. Install it into your default Firefox profile (you will have more than one profile when following this guide). Getting the current Texts in English and your Locale Obtaining the English texts with the so...
...il address which later will be public on the internet after your translation patch got accepted and uploaded. Save the file and close it. Enabling Mercurial queues (revertable patches) Some time will pass between the moment in which you start the localization, finish it, test it, improve it, upload it for review and get review (maybe not approved on first try). Other localizers will likely have done changes to the translation, either adding new texts, removing obsolete ones or improving the current texts. This can cause conflicts between the changes you created and theirs. For this reason, updating patches kann be necessary so Mercurial is still able to find the lines in the files which it has to replace or where it has to add them. Mercurial queues allow to revert changes and also pull chan...
...owsing-v1.patch This creates a patch file called firefox-29-aboutPrivateBrowsing-v1.patch containing the changes in the parent directory of de-mozilla-aurora (in this example: C:\Mozilla\). Proof-reading and altering the patch Now proof-read the patch. This detects often more than 90 percent of the possible reasons for the reviewer to not accept the patch. If you find that changes have to be done, edit the real aboutPrivateBrowsing.dtd file from the localization repository, save it and follow the steps from Exporting the changes as patch (see above). Validating the translation in the product This guide hasn't yet a section about the validation of the translation. Please follow the instructions from the QA phase section of the Localization quick start guide. Submitting the patch for rev...
Localizing with Koala
files and strings. Let's see how that works. Running a comparison Open Koala's start page. Select Firefox (3.6) in Application column. Select en-US (included) in Original Locale column. Select x-testing (3.6) in User Locale column. The buttons on the right become active. Click "Compare". A dialog will appear letting you know that Koala is comparing en-US with x-testing. When the comparison is done, you should see a new line in "Last used compares" section of Koala's startpage. It's a handy shortcut to run the comparison in the future. If the sidebar with the results of the comparison doesn't show up automatically: Open the Projects sidebar by choosing View > Tabs & Sidebars > Projects from the menu. Switch to "Koala file view" in the sidebar (choose it from the list that appears when you...
...ou can right-click it and choose "add entity" as you did previously, or just double-click the entity name to add it to the file. Note how Koala is smart enough to insert this entity before searchEndCap.label. This is helpful for keeping the localization files clean and tidy at all times. The string to translated is selected so that you can translate it without any further clicking. When you are done with translating the cmd_engineManager.label entity, save the file. Now let's create the other file. Double-click on search.properties and click "OK" when Koala asks if you want to create this file. From the sidebar, add the cmd_addFoundEngine string to the newly-created search.properties file in your locale file structure. Translate the cmd_addFoundEngine string. Notice that the .properties fil...
... try issuing "hg status" inside C:\mozilla\l10n\locale\x-testing\3.6: C:\mozilla\l10n\locale\x-testing\3.6> hg status ? browser\chrome\browser\search.properties ? browser\chrome\browser\searchbar.dtd The question marks ("?") in front of the file names indicate that the files are not tracked by Mercurial in this repository (yet). To start tracking them, you will need to "hg add" them. This can be done from Koala. Once you "hg add" every new file in the repository that you want to track in Mercurial, you will need to "hg commit" these new files so as to create a new revision in the repository's history. This process need to be repeated for every new file that you add. Also, removing files works in a similar manner: not only do you have to delete the file, but also you need to tell Mercurial to ...
...hrome/browser folder in the sidebar and choose "commit folder". (You could also commit each file individually if you felt like it.) Koala will ask you to type in a commit message. It is a good practice to be descriptive about the changes you made in this revision. A good way of doing that is to ask yourself a question: "If I was a new person to this project and new nothing about the work already done in this repository, would this message help me understand what changes were made in this revision?". Type a good commit message and click "OK". Koala will execute "hg commit" in the background and will let you know that the files were successfully committed. If you now go to the command line, "hg status" will not display anything (because there are no uncommitted changes in the repository). If ...
Release phase
Here, we'll continue to stay true to the original intent of this guide and only present you with the technical information you need to become an official release. We'll primarily focus on getting your release repository setup and the Mercurial commands you'll need to know to use that repository. For more information on the release part of the L10n process, visit the Mozilla wiki here. ...
...rg/releases/l10n-central/x-testing). You should now be able to push to the remote repository! Commit, outgoing, and push You should try to commit your work regularly as you progress through the localization files. Keep in mind that the hg commit command will save your changes locally (in the local clone). With the hg push command you can send the changesets to the remote server. ...
...don't see this message, try running the same command in a more verbose mode (with the debugging information): $ ssh -vvv hg.mozilla.org This should tell you why your connection is not succeeding. If you can't figure it out on your own, copy the output of the above command, paste it on http://pastebin.mozilla.org and ask in #l10n on the irc.mozilla.org server. Technical and sign-off reviews You've done some localization work and your ready for it to be released. The merge date for migrating from one product release channel to the next is rapidly approaching. You need to make sure that your work can effectively be compiled into a build for the next release channel. Do you know whether to ask for technical review of your work or a sign-off review? Do you know what what exactly is reviewed in each...
...lity. Only performed on the first revision a new locale wants to have released to the public. Must be approved prior to migrating your revision from one release channel to the next (e.g., Aurora to Beta). Performed as a QA measure for maintaining a localization from release-to-release. Only new L10n work is evaluated. This is done by generating a diff between the new release revision being considered and the previously approved release revision. Focus is still on technical accuracy and completion of L10n work; not translation quality. Release revisions are evaluated, not entire L10n repos. Sign-offs do not need to be approved before revision merge between release channels, although it is recom...
Web Replay
participate in the recording: any events they execute are live. See the sections below for details on how these affect the process' behavior. To make it easier to ensure that the non-deterministic components do not have an effect on recorded behavior, certain code regions can be marked as disallowing events -- while executing them no thread, lock, or atomic events should be recorded. This is done in code associated with the non-deterministic components, such as during GC or Ion compilation, to help track down behaviors that should go unrecorded. Replaying A replaying content process behaves in the same way as a recording process, except for the following: The calls and mach messages which were intercepted during recording are also intercepted here. When a call/message is intercepted...
...a separate thread that does not participate in the recording, so that the calling thread may enter the correct idle state even while its progress is blocked on the call completing. Once all thread are idle, the main thread computes the memory diff, reads the stacks from each thread and their register state (which each thread recorded by calling setjmp before idling). Restoring snapshots is also done from the main thread. As for taking a snapshot, all other threads enter an idle state. The dirty memory information computed since the last snapshot was taken is used to restore the heap to the state at that last snapshot, and then the memory diffs can be used to restore an earlier snapshot if necessary. Threads are individually responsible for restoring their stacks; when they wake up from th...
...e state they see the main thread has prepared a new stack to restore to, so they longjmp to the new register state and copy in the new stack's contents. Managing system resources When the child process restores a snapshot, the state of any system resources it has open is unchanged. Care must be taken to make sure these resources are coherent to the process after the restore completes. This is done in the following ways: Instead of creating or destroying threads on demand, while recording/replaying all threads which will be needed are created during process initialization. If during the recording the content tries to create more threads than were spawned up front, then the recording fails. These threads idle until the recording/replaying content tries to 'create' them, then they run th...
...lying object of a Debugger.Object is inaccessible; object.unsafeDereference is null. As described above under "Debugger integration", child objects besides scripts and script sources become invalid when the debugger resumes execution, and must be reconstructed each time the replaying process pauses. Inspecting a replaying process Access to JS objects in the replaying process is currently only done through the JS Debugger interface -- Debugger.Object, Debugger.Frame.eval, and so forth. This interface overlays a separate implementation from the C++ Debugger, implemented in devtools/server/actors/replay/debugger.js. This communicates with the replaying process via JSON and is fairly easy to extend for new features (such as web console support). Appendix: Impacts on Gecko development Web R...
nsIFaviconService
e the corresponding favicon data to be loaded from this service. For pages where we don't have a favicon, this will be a chrome URI of the default icon for a web page. getFaviconLinkForIcon() This method, for a given icon URI will return a URI that will result in the image. In most cases, this is an annotation URI. For chrome, this will do nothing and return the input URI. No validity checking is done. If you pass an icon URI that we've never seen, you'll get back a URI that references an invalid icon. The moz-anno protocol handler's special case for "favicon" annotations will resolve invalid icons to the default icon, although without caching. For invalid chrome URIs, you'll get a broken image. nsIURI getFaviconLinkForIcon( in nsIURI aFaviconURI ); Parameters aFaviconURI The URI o...
.... For a normal page with a favicon we've stored, this will be an annotation URI which will then cause the corresponding favicon data to be loaded from this service. For pages where we don't have a favicon, this will be a chrome URI of the default icon for a web page. For chrome, the output will be the same as the input. For chrome, the output will be the same as the input. No validity checking is done. If you pass an icon URI that we've never seen, you'll get back a URI that references an invalid icon. The moz-anno protocol handler's special case for "favicon" annotations will detect most invalid icons and it will resolve to the default icon, although without caching. For invalid chrome URIs, you'll get a broken image. isFailedFavicon() This method checks to see if this favicon is in the faile...
...FaviconData() instead. This method stores the data of a given favicon. You must specify the MIME type unless you're clearing the data. You can set the data even if you haven't called setFaviconUrlForPage() yet. It will be stored but will not be associated with any page. However, any favicons not associated with a visited web page, bookmark, or "place:" URI will be expired when history cleanup is done. This might be done at any time on a timer, so you should not let the message loop run between calls or your icon may get deleted. It is best to set the favicon data, and then associate it with a page. This will make the notifications more efficient since the icon will already have data when the set favicon observer messages goes out. The expiration time is stored. This will be used if you call s...
...onForPage() instead. This method declares that a given page uses a favicon with the given URI. You needn't have any specified data at this point. An entry linking the favicon with the page will be create with no data. You can populate it later with SetFaviconData(). However, any favicons not associated with a visited web page, a bookmark, or a "place:" URI will be expired when history cleanup is done * (typically at app shutdown, but also possibly if the user clears their * cache or history). This will send out history notifications if the new favicon has any data. This means that you should try to set data first if you have it, otherwise the page might not get a notification sent for it since data setting does not send notifications. void setFaviconUrlForPage( in nsIURI aPageURI, in nsIU...
Using COM from js-ctypes
lavent topic Bugzilla :: Bug 505907 - Support C++ calling from JSctypes Converting COM code to C code To convert COM code to js-ctypes, we need to write C++ VTable pointers in C. After that, we can pass a pointer . Speech Synthesis Example Let's start with following C++ code, which invokes Microsoft Speech API and says "Hello, Firefox!" with system default voice, then wait until the speaking done. #include <sapi.h> int main(void) { if (SUCCEEDED(CoInitialize(NULL))) { ISpVoice* pVoice = NULL; HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void**)&pVoice); if (SUCCEEDED(hr)) { pVoice->Speak(L"Hello, Firefox!", SPF_DEFAULT, NULL); pVoice->Release(); ...
...e; HRESULT (__stdcall *Speak)(struct MyISpVoice*, LPCWSTR pwcs, DWORD dwFlags, ULONG* pulStreamNumber); void* SpeakStream; void* GetStatus; void* Skip; void* SetPriority; void* GetPriority; void* SetAlertBoundary; void* GetAlertBoundary; void* SetRate; void* GetRate; void* SetVolume; void* GetVolume; void* WaitUntilDone; void* SetSyncSpeakTimeout; void* GetSyncSpeakTimeout; void* SpeakCompleteEvent; void* IsUISupported; void* DisplayUI; /* end ISpVoice */ }; int main(void) { if (SUCCEEDED(CoInitialize(NULL))) { struct MyISpVoice* pVoice = NULL; HRESULT hr = CoCreateInstance(&CLSID_SpVoice, NULL, CLSCTX_ALL, &IID_ISpVoice, (voi...
...e working C code. It could be converted into js-ctypes in almost straightforward way. CLSID and IID Needs CLSID and IID of SpVoice and ISpVoice description here. COM types and functions Needs COM types (GUID) and functions (CoInitialize etc) description here. Converted js-ctypes code Here's converted code. This example uses busy loop and thus Firefox won't respond until the speaking is done. If this code were used in a production add-on, then to avoid Firefox locking up, run this code from a ChromeWorker. let { ctypes } = Components.utils.import("resource://gre/modules/ctypes.jsm", {}); // SOME GROUNDWORK let is64bit; if (ctypes.voidptr_t.size == 4 /* 32-bit */) { is64bit = false; } else if (ctypes.voidptr_t.size == 8 /* 64-bit */) { is64bit = true; } let WINABI = is64bit...
...s': ctypes.voidptr_t }, { 'Skip': ctypes.voidptr_t }, { 'SetPriority': ctypes.voidptr_t }, { 'GetPriority': ctypes.voidptr_t }, { 'SetAlertBoundary': ctypes.voidptr_t }, { 'GetAlertBoundary': ctypes.voidptr_t }, { 'SetRate': ctypes.voidptr_t }, { 'GetRate': ctypes.voidptr_t }, { 'SetVolume': ctypes.voidptr_t }, { 'GetVolume': ctypes.voidptr_t }, { 'WaitUntilDone': ctypes.voidptr_t }, { 'SetSyncSpeakTimeout': ctypes.voidptr_t }, { 'GetSyncSpeakTimeout': ctypes.voidptr_t }, { 'SpeakCompleteEvent': ctypes.voidptr_t }, { 'IsUISupported': ctypes.voidptr_t }, { 'DisplayUI': ctypes.voidptr_t } // end ISpVoice ]); // FUNCTIONS // http://msdn.microsoft.com/en-us/library/windows/desktop/ms695279%28v=vs.85%29.aspx let CoInitializeEx = lib.d...
Using js-ctypes
the library in its standard locations. Windows On Windows, the following locations are searched for the library, in this order: The application's directory. The system directory. The 16-bit system directory. The Windows directory. The current working directory The directories listed in the PATH environment variable. Note: This information comes from this article on MSDN. After you're done When you're finished using a library, you should close it by calling the Library object's close() method: lib.close(); If you fail to close the library, it will be automatically closed when it is garbage collected. Using the library You may need to declare new types. These can be simple types or more complex types such as structures. See Declaring types for details. You will almost certainly...
..., ctypes.int32_t); var MB_OK = 0; var ret = msgBox(0, "Hello world", "title", MB_OK); lib.close(); In line 3, the user32.dll system library is loaded. Line 6 declares msgBox() to be a method that calls the Windows function MessageBoxW. Line 15 calls the msgBox() routine, which displays the alert. The last thing we do is call lib.close() to close the library when we're done using it. Instead of defining the whole path, you may also just give the file name. ABOUT DECLARING THE FUNCTION How we knew how to declare the function was by going to MSDN site and looking at the MessageBox (MessageBoxW is just a unicode version of same function) function. Also learn about the lib.declare function used here: lib.declare. Learn about the data types used here: Data Types. We s...
...r block, which we aren't using, and another integer, which is used to return the hit item. See Apple's documentation for StandardAlert for details. After that, we simply set up our parameters by using makeStr() to generate the two Str255 strings we need, then call stdAlert(), which produces the following alert window: The last thing we do is call carbon.close() to close the library when we're done using it. Standard Alert in 64bit OS X Carbon is not available in 64bit versions of OS X, therefore Core Foundation must be used. The below will do the same as StandardAlert from above, it will use the Core Foundation function of CFUserNotificationDisplayNotice. Cu.import('resource://gre/modules/ctypes.jsm'); var libcf = ctypes.open('/System/Library/Frameworks/CoreFoundation.framework/CoreFoun...
... const UniChar *chars, * CFIndex numChars * ); */ var CFStringCreateWithCharacters = libcf.declare('CFStringCreateWithCharacters', ctypes.default_abi, CFStringRef, // return CFAllocatorRef, // alloc UniChar.ptr, // *chars CFIndex // numChars ); // HELPER FUNCTIONS function makeCFStr(jsStr) { // js str is just a string // returns a CFStr that must be released with CFRelease when done return CFStringCreateWithCharacters(null, jsStr, jsStr.length); } // MAIN var myCFStrs = { head: makeCFStr('Core Foundation Says...'), body: makeCFStr('We just called the equivalent of the "StandardAlert Carbon function" for 64bit OSX from JavaScript!') }; var rez = CFUserNotificationDisplayNotice(0, kCFUserNotificationCautionAlertLevel, null, null, null, myCFStrs.head, myCFStrs.body, null);...
Using IndexedDB - Web APIs
with createObjectStore(), createIndex() takes an optional options object that refines the type of index that you want to create. Adding objects that don't have a name property still succeeds, but the objects won't appear in the "name" index. We can now retrieve the stored customer objects using their ssn from the object store directly, or using their name by using the index. To learn how this is done, see the section on using an index. Using a key generator Setting up an autoIncrement flag when creating the object store would enable the key generator for that object store. By default this flag is not set. With the key generator, the key would be generated automatically as you add the value to the object store. The current number of a key generator is always set to 1 when the object store f...
...ther than individual requests can certainly aid your sanity. Now that you have a transaction, you'll need to get the object store from it. Transactions only let you have an object store that you specified when creating the transaction. Then you can add all the data you need. // Do something when all the data is added to the database. ...
...a float) const DB_STORE_NAME = 'publications'; var db; // Used to keep track of which view is displayed to avoid uselessly reloading it var current_view_pub_key; function openDb() { console.log("openDb ..."); var req = indexedDB.open(DB_NAME, DB_VERSION); req.onsuccess = function (evt) { // Equal to: db = req.result; db = this.result; console.log("openDb DONE"); }; req.onerror = function (evt) { console.error("openDb:", evt.target.errorCode); }; req.onupgradeneeded = function (evt) { console.log("openDb.onupgradeneeded"); var store = evt.currentTarget.result.createObjectStore( DB_STORE_NAME, { keyPath: 'id', autoIncrement: true }); store.createIndex('biblioid', 'biblioid', { unique: true }); stor...
...uccess"; $('#msg').html('<span class="action-success">' + msg + '</span>'); } function displayActionFailure(msg) { msg = typeof msg != 'undefined' ? ...
ReadableStreamDefaultReader.cancel() - Web APIs
, a previously-created custom ReadableStream is read using a ReadableStreamDefaultReader created using getReader(). (this code is based on our Simple random stream example). Each chunk is read sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. ...
...usly-created custom ReadableStream is read using a ReadableStreamDefaultReader created using getReader(). (this code is based on our Simple random stream example). Each chunk is read sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. ...
...nd print the entire stream to another part of the UI. When the stream is done (if (done)), we run reader.cancel() to cancel the stream, signalling that we don't need to use it any more. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. ...
...tream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); reader.cancel(); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChil...
A basic 2D WebGL animation example - Web APIs
y - aVertexPosition.x * uRotationVector.x ); gl_Position = vec4(rotatedPosition * uScalingFactor, 0.0, 1.0); } </script> The main program shares with us the attribute aVertexPosition, which is the position of the vertex in whatever coordinate system it's using. We need to convert these values so that both components of the position are in the range -1.0 to 1.0. This can be done easily enough by multiplying by a scaling factor that's based on the context's aspect ratio. We'll see that computation shortly. We're also rotating the shape, and we can do that here, by applying a transform. We'll do that first. The rotated position of the vertex is computed by applying the rotation vector, found in the uniform uRotationVector, that's been computed by the JavaScript code. The...
...In this case, we set the viewport based on the size of the <canvas>, call clearColor() to set the color to use when clearing content, then we clear the buffer with clear(). Next, the current rotation vector is computed by converting the current rotation in degrees (currentAngle) into radians, then setting ...
...program we established previously. Then we obtain the locations of each of the uniforms used to share information between the JavaScript code and the shaders (with getUniformLocation()). The uniform named uScalingFactor is set to the currentScale value previously computed; this, as you may recall, is the value used to adjust the coordinate system based on the aspect ratio of the context. This is done using uniform2fv() (since this is a 2-value floating-point vector). uRotationVector is set to the current rotation vector (currentRotation), also using uniform2fv(). uGlobalColor is set using uniform4fv() to the color we wish to use when drawing the square. This is a 4-component floating-point vector (one component each for red, green, blue, and alpha). Now that that's all out of the way, we c...
...ult, accessing aVertexPosition now obtains data from the vertex buffer. 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(). At this point, the frame has been drawn. All that's left to do is to schedule to draw the next one. 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. Our requestAnimationFrame() callback receives as input a single parameter, currentTime, which specifies the time at which the frame drawing began. We use that and the saved time at which the last frame was drawn, previousTime, along with the number of ...
WebGL model view projection - Web APIs
t of as a representation of a directional vector. If this homogeneous coordinate is multiplied against a matrix with a translation then the translation is effectively stripped out. When numbers are extremely large (or extremely small) on computers they begin to become less and less precise because there are only so many ones and zeros that are used to represent them. The more operations that are done on larger numbers, the more and more errors accumulate into the result. When dividing by w, this can effectively increase the precision of very large numbers by operating on two potentially smaller, less error-prone numbers. The final benefit of using homogeneous coordinates is that they fit very nicely for multiplying against 4x4 matrices. A vertex must match at least one of the dimensions of a...
... by starting with the set of all objects in the scene. Then any objects which are entirely outside the viewing frustum are removed from the set. Next, objects which partially extrude outside the viewing frustum are clipped by dropping any polygons which are entirely outside the frustum, and by clipping the polygons which cross outside the frustrum so that they no longer exit it. Once that's been done, we have the largest set of polygons which are entirely within the viewing frustum. This list is usually further reduced using processes like back-face culling (removing polygons whose back side is facing the camera) and occlusion culling using hidden-surface determination (removing polygons which can't be seen because they're entirely blocked by polygons that are closer to the lens). Perspectiv...
...e-tuned control over what points get placed inside and outside of clip space. In the previous examples the corners of the cube occasionally get clipped. The perspective projection matrix is a type of projection matrix that accomplishes all of these requirements. The math also starts to get a bit more involved and won't be fully explained in these examples. In short, it combines dividing by w (as done with the previous examples) with some ingenious manipulations based on similar triangles. If you want to read a full explanation of the math behind it check out some of the following links: OpenGL Projection Matrix Perspective Projection Trying to understand the math behind the perspective projection matrix in WebGL One important thing to note about the perspective projection matrix used b...
...ddle Relating the coordinate systems At this point it would be beneficial to take a step back and look at and label the various coordinate systems we use. First off, the cube's vertices are defined in model space. To move the model around the scene. these vertices need to be converted into world space by applying the model matrix. model space -> model matrix -> world space The camera hasn't done anything yet, and the points need to be moved again. Currently they are in world space, but they need to be moved to view space (using the view matrix) in order to represent the camera placement. world space -> view matrix -> view space Finally a projection (in our case the perspective projection matrix) needs to be added in order to map the world coordinates into clip space coordinates. view ...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
\\ a_{4} & a_{8} & a_{12} & a_{16} \end{matrix} \right ] Is represented in array form like this: let matrixArray = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16]; In this array, the leftmost column contains the entries a1, a2, a3, and a4. The topmost row contains the entries a1, a5, a9, and a13. Keep in mind that most WebGL and WebXR programming is done using third-party libraries which expand upon the basic functionality of WebGL by adding routines that make it much easier to perform not only core matrix and other operations, but often also to simulate these standard cinematography techniques. You should strongly consider using one instead of directly using WebGL. This guide uses WebGL directly since it's useful to understand to some extent wha...
...ically have a horizontal field of view of around 135? (about 2.356 radians) and a vertical FOV of about 180? (? or around 3.142 radians). Making the camera's FOV smaller reduces the arc that will be included in the viewport, thus enlarging that content when rendered to the view. There are differences between this and an optical zoom effect, but the result is generally close enough to get the job done. The following function returns a projection perspective matrix that integrates the specified field of view angle as well as the given near and far clipping plane distances: function createPerspectiveMatrix(viewport, fovDegrees, nearClip, farClip) { const fovRadians = fov * (Math.PI / 180.0); const aspectRatio = viewport.width / viewport.height; const transform = mat4.create(); mat4.pe...
...capturing the scope of a tall object or scene, such as a forest or a mountain, but is also a popular way to introduce a character or locale of importance or which inspires awe. it's also of course useful for implementing support for a player looking up and down. Thus, tilting the camera can be achieved by rotating the camera around the X axis, so that it pivots to look up and down. This can be done using the appropriate method in your matrix math library, such as the rotateX() method in glMatrix's mat4 class: mat4.rotateX(viewMatrix, viewMatrix, angle); Positive values for angle will tilt the camera downward, while negative values of angle will tilt upward. Dollying (Moving in or out) A dolly shot is one in which the entire camera is moved forward and backward. In classic filmmaking, th...
...priate method in your matrix math library, such as the rotateX() method in glMatrix's mat4 class: mat4.rotateX(viewMatrix, viewMatrix, angle); Positive values for angle will tilt the camera downward, while negative values of angle will tilt upward. Dollying (Moving in or out) A dolly shot is one in which the entire camera is moved forward and backward. In classic filmmaking, this is typically done with the camera mounted on a track or on a moving vehicle. The resulting motion can create impressively smooth effects, especially if moving along with the person or object that's the focus of your shot. While a dolly shot and a zoom seem like they ought to look about the same, they don't. The fact that zooming alters the camera's focal length means that the spatial relationship between the ta...
Rendering and the WebXR frame animation callback - Web APIs
ata it needs in order to render the scene, you can set up the renderer to start running. This begins with getting the reference space in which you want to draw, with its origin and orientation set at the viewer's starting position and viewing direction. Once that's in hand, you request that the browser call your rendering function the next time it needs a framebuffer to render your scene. This is done by calling the XRSession method requestAnimationFrame(). Kicking off the renderer thus looks like this: let worldRefSpace; async function runXR(xrSession) { worldRefSpace = await xrSession.requestReferenceSpace("immersive-vr"); if (worldRefSpace) { viewerRefSpace = worldRefSpace.getOffsetReferenceSpace( new XRRigidTransform(viewerStartPosition, viewerStartOrientation)); an...
...it to your frame rendering code with a timestamp. You use that timestamp and your own data to determine how to render the scene. After rendering the scene twice--once into the left half of the framebuffer and once into the right half of the framebuffer--the framebuffer is sent to the XR hardware, which displays each half of the framebuffer to the corresponding eye. This is often (but not always) done by drawing the image to a single screen and using lenses to transfer the correct half of that image to each eye. You can learn more about how 3D is represented by WebXR in Representing 3D with WebXR in Viewpoints and viewers: Simulating cameras in WebXR. Drawing the scene When the time comes to prepare the framebuffer so the browser can paint the next frame of your scene, the function you prov...
...s the viewer's pose--their position and orientation--using the frame's getViewerPose() method, passing in the viewer's reference space from the viewerRefSpace previously obtained while setting up the WebXR session. With the viewer's pose in hand, we can then begin to render the frame. The first step is to obtain access to the framebuffer into which the WebXR device wants the frame drawn; this is done by getting the target WebGL layer from the session's renderState object's baseLayer property, then getting the framebuffer from that XRWebGLLayer object. We then call gl.bindFrameBuffer() to bind that framebuffer as the target for all upcoming drawing commands. The next step is to erase the framebuffer. While you can in theory skip this step--if and only if your rendering code is guaranteed to w...
...lly, providing a potentially much faster rendering approach, especially as your object count goes up. Optimizing by rendering in object-first order An advantage of WebXR's approach of using a single WebGL framebuffer to contain both the left and right eye's views in a single framebuffer makes it possible to substantially improve rendering performance by rearranging the order in which things are done. Instead of setting up the viewport for a given view (such as the left eye), then rendering every object visible to the left eye, one by one, reconfiguring buffers for each object as you go, you can instead render each object twice in a row, once for each eye, thereby only needing to set up the buffers, uniforms, and so forth once for both eyes. The resulting pseudocode looks like this: for eac...
XMLHttpRequest.readyState - Web APIs
s in. An XHR client exists in one of the following states: Value State Description 0 UNSENT Client has been created. open() not called yet. 1 OPENED open() has been called. 2 HEADERS_RECEIVED send() has been called, and headers and status are available. 3 LOADING Downloading; responseText holds partial data. 4 DONE The operation is complete. UNSENT The XMLHttpRequest client has been created, but the open() method hasn't been called yet. OPENED open() method has been invoked. During this state, the request headers can be set using the setRequestHeader() method and the send() method can be called which will initiate the fetch. HEADERS_RECEIVED send() has been called and the response headers h...
...invoked. During this state, the request headers can be set using the setRequestHeader() method and the send() method can be called which will initiate the fetch. HEADERS_RECEIVED send() has been called and the response headers have been received. LOADING Response's body is being received. If responseType is "text" or empty string, responseText will have the partial text response as it loads. ...
...s body is being received. If responseType is "text" or empty string, responseText will have the partial text response as it loads. DONE The fetch operation is complete. This could mean that either the data transfer has been completed successfully or failed. The state names are different in versions of Internet Explorer earlier than 11. Instead of UNSENT, OPENED, HEADERS_RECEIVED, LOADING and DONE, the names READYSTATE_UNINITIALIZED (0), READYSTATE_LOADING (1), READYSTATE_LOADED (2), READYSTATE_INTERACTIVE (3) and READYSTATE_COMPLETE (4) are used. Example 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.l...
...ERACTIVE (3) and READYSTATE_COMPLETE (4) are used. ...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
o get information, but sometimes the hacks are more effective. For example, screen readers look for screen draws of a vertical blinking line, to determine the location of the caret. Without doing this, screen readers would not be able to let the user know where there caret has moved to in most programs, because so many applications do not use the system caret (Gecko does not). This is so commonly done, that no one even bothers to support the MSAA caret, after all the hack is general solution works with pretty much all applications. MSAA provides information in several different ways: A COM interface (IAccessible) that allows applications to expose the tree of data nodes that make up each window in the user interface currently being interacted with and Custom interface extensions via inter...
...A if you're not going to take it all the way via testing with assistive technologies and working with AT vendors. Don't use MSAA for exposing documents or other specialized data, if it's important that the user get access to formatting information. You will have to expose interfaces that contain more info than MSAA does. This information may be in the form of extensions to MSAA, like Mozilla has done with ISimpleDOMNode (you can QI to it from IAccessible). This is likely to be a painful road even if you are a major player, in terms of getting the cooperation of AT vendors. It may be a good enough solution; however, if what you need is JAWS, Dragon and ZoomText support. ZoomText and Dragon can get by with your MSAA support., and JAWS can be scripted (even by external developers) to support alt...
...ect and its child ROLE_TEXT objects all have STATE_LINKED set. For multi-line links with a line break in the middle, make sure there is no whitespace at the beginning or end of any of the accessible names, and make sure there is a \r\n where the line breaks occur in the accessible name for the ROLE_LINK. For an example of how to do this properly, see Internet Explorer or Gecko. Again, if it's not done exactly this way, some links will not be read. For links inside dialogs, just expose a single ROLE_LINK object and work on a scripting or code change solution with the assistive technology vendor. Issues with Tree Views Problem: Tree views are difficult to support MSAA in, because the nodes may be constantly changing or lazily instantiated. The screen reader vendors actually use the SysTreeVie...
...for IAccessible There are two main kinds of classes in Mozilla's accessibility class hierarchy, platform-specifc and cross-platform. All of the platform-specific classes have the word "Wrap" appended to them. The Wrap classes contain implementations and interfaces specific to MSAA or ATK. These platform-specific classes inherit from cross-platform classes, where the most of the implementation is done. For example, nsAccessibleWrap inherits from nsAccessible. Every accessible object in the MSAA tree has an implementation dertived from nsAccessible, which exposes accessibility information through nsIAccessible, in a generic cross-platform manner. This default implementation for nsIAccessible knows how to use nsAccessibleTreeWalker to walk Mozilla's content DOM and frame tree, exposing only the...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
d can often be used to add small touches to the UI and improve user experience. ...
...ches to the UI and improve user experience. ...
... Result Special characters As this is CSS; not HTML, you can not use markup entities in content values. If you need to use a special character, and can not enter it literally into your CSS...
... Result Special characters As this is CSS; not HTML, you can not use markup entities in content values. ...
Getting Started - Developer guides
est.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.onreadystatechange = nameOfTheFunction; What should this function do? First, the function needs to check the request's state. If the state has the value of XMLHttpRequest.DONE (corresponding to 4), that means that the full server response was received and it's OK for you to continue processing it. if (httpRequest.readyState === XMLHttpRequest.DONE) { // Everything is good, the response was received. } else { // Not ready yet. } The full list of the readyState values is documented at XMLHTTPRequest.readyState and is as follows: 0 (uninitialized) or (reques...
..., makeRequest); function makeRequest() { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } httpRequest.onreadystatechange = alertContents; httpRequest.open('GET', 'test.html'); httpRequest.send(); } function alertContents() { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } })(); </script> In this example: The user clicks the "Make a request" button; The event handler calls the makeRequest() function; The request is made and then (onreadystatechange) the execution is passed to alertContent...
...ocal to a closure containing the AJAX functions avoids this. In the event of a communication error (such as the server going down), an exception will be thrown in the onreadystatechange method when accessing the response status. ...
...d string and the original user data. So if our user typed "Jane" in the text box, the server's response would look like this: {"userData":"Jane","computedString":"Hi, Jane!"} To use this data within alertContents(), we can't just alert the responseText, we have to parse it and alert computedString, the property we want: function alertContents() { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { var response = JSON.parse(httpRequest.responseText); alert(response.computedString); } else { alert('There was a problem with the request.'); } } } The test.php file should contain the following: $name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name'; $computedString = "Hi, " . $name . "!"; $array = ['userName' =...
Creating a cross-browser video player - Developer guides
button will use the Fullscreen API, another W3C API that controls the ability of web browsers to show apps using your computer's full screen. Setup Before dealing with the individual buttons, a number of initialisation calls are required. To begin with, it's a good idea to first check if the browser actually supports the <video> element and to only setup the custom controls if it does. This is done by simply checking if a created <video> element supports the canPlayType() method, which any supported HTML5 <video> element should. var supportsVideo = !!document.createElement('video').canPlayType; if (supportsVideo) { // set up custom controls // ... } Once it has been confirmed that the browser does indeed support HTML5 video, it's time to set up the custom controls. A number of vari...
...deoContainer'); var video = document.getElementById('video'); var videoControls = document.getElementById('video-controls'); As mentioned earlier, the browser's default controls now need to be disabled, and the custom controls need to be displayed: // Hide the default controls video.controls = false; // Display the user defined video controls videoControls.style.display = 'block'; With that done, a variable pointing to each of the buttons is now required: var playpause = document.getElementById('playpause'); var stop = document.getElementById('stop'); var mute = document.getElementById('mute'); var volinc = document.getElementById('volinc'); var voldec = document.getElementById('voldec'); var progress = document.getElementById('progress'); var progressBar = document.getElementById('prog...
...hen the <progress> element was defined above in the HTML, only two attributes were set, value and min, both being given a value of 0. The function of these attributes is self-explanatory, with min indicating the minimum allowed value of the progress element and value indicating its current value. It also needs to have a maximum value set so that it can display its range correctly, and this can be done via the max attribute, which needs to be set to the maximum playing time of the video. This is obtained from the video's duration attribute, which again is part of the Media API. Ideally, the correct value of the video's duration attribute is available when the loadedmetadata event is raised, which occurs when the video's metadata has been loaded: video.addEventListener('loadedmetadata', functi...
...he loadedmetadata event is raised, which occurs when the video's metadata has been loaded: video.addEventListener('loadedmetadata', function() { progress.setAttribute('max', video.duration); }); Unfortunately in some mobile browsers, when loadedmetadata is raised -- if it even is raised -- video.duration may not have the correct value, or even any value at all. So something else needs to be done. More on that below. Another event, timeupdate, is raised periodically as the video is being played through. This event is ideal for updating the progress bar's value, setting it to the value of the video's currentTime attribute, which indicates how far through the video the current playback is. video.addEventListener('timeupdate', function() { progress.value = video.currentTime; progress...
Constraint validation - Developer guides
lidation on the server side. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without JavaScript) or by bad people trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side. Intrinsic and basic constraints In HTML5, basic constraints are declared in two ways: By choosing the most semantically appropriate value for the type attribute of the <input> element, e.g., choosing the email type automatically creates a constraint that checks whether the value is a valid e-mail address. By setting values on validation-related attributes, allowing basic...
...lized to a single character (as opposed to CRLF pairs) for <textarea>. tooShort constraint violation maxlength text, search, url, tel, email, password; also on the <textarea> element An integer length The number of characters (code points) must not exceed the value of the attribute. ...
... password; also on the <textarea> element An integer length The number of characters (code points) must not exceed the value of the attribute. tooLong constraint violation Constraint validation process Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the <form> element itself. The constraint validation is done in the following ways: By a call to the checkValidity() or reportValidity() method of a form-associated DOM interface, (HTMLInputElement, HTMLSelectElement, HTMLButtonElement, HTMLOutputElement or HTMLTextAreaElement), which evaluates the constraints only on this element, allowing a script to get this information. The checkValidity() method returns a Boolean indicating whether the element's va...
...ckValidity() or reportValidity() method of a form-associated DOM interface, (HTMLInputElement, HTMLSelectElement, HTMLButtonElement, HTMLOutputElement or HTMLTextAreaElement), which evaluates the constraints only on this element, allowing a script to get this information. The checkValidity() method returns a Boolean indicating whether the element's value passes its constraints. (This is typically done by the user-agent when determining which of the CSS pseudo-classes, :valid or :invalid, applies.) In contrast, the reportValidity() method reports any constraint failures to the user. By a call to the checkValidity() or reportValidity() method on the HTMLFormElement interface. By submitting the form itself. Calling checkValidity() is called statically validating the constraints, while calling...
HTTP Index - HTTP
Web › HTTP › Index
ference, Request header The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending on the context where the request is done: when fetching a CSS stylesheet a different value is set for the request than when fetching an image, video or a script. 48 Accept-CH Client hints, HTTP, HTTP Header The Accept-CH header is set by the server to specify which Client Hints headers client should include in subsequent requests. 49 Accept-CH-Lifetime Client hints, HTTP, header The Accept-CH-Li...
...e control over the data stored locally by a browser for their origins. 69 Connection HTTP, Headers, Reference, Web The Connection general header controls whether or not the network connection stays open after the current transaction finishes. If the value sent is keep-alive, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. 70 Content-Disposition HTTP, Reference, header In a multipart/form-data body, the HTTP Content-Disposition general header is a header that can be used on the subpart of a multipart body to give information about the field it applies to. The subpart is delimited by the boundary defined in the Content-Type header. Used on the body itself, Content-Disposition has no effect. ...
...urce. 209 GET HTTP, Reference, Request method The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data. 210 HEAD HTTP, Reference, Request method The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method. Such a request can be done before deciding to download a large resource to save bandwidth, for example. 211 OPTIONS HTTP, Reference, Request method The HTTP OPTIONS method is used to describe the communication options for the target resource. The client can specify a URL for the OPTIONS method, or an asterisk (*) to refer to the entire server. 212 PATCH HTTP, HTTP method, Reference, Requ...
...long the path to the target resource, providing a useful debugging mechanism. 216 HTTP resources and specifications Guide, HTTP HTTP was first specified in the early 1990s. Designed with extensibility in mind, it has seen numerous additions over the years; this lead to its specification being scattered through numerous specification documents (in the midst of experimental abandoned extensions). This page lists relevant resources about HTTP. 217 HTTP response status codes HTTP, Landing, Overview, Reference, Status code, Web HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses (100-199),Successful responses (200-299),Redirects (300-399),Client e...
SyntaxError: missing ) after condition - JavaScript
(3 > Math.PI { console.log("wait what?"); } // SyntaxError: missing ) after condition To fix this code, you would need to add a parenthesis that closes the condition. ...
...at?"); } // SyntaxError: missing ) after condition To fix this code, you would need to add a parenthesis that closes the condition. ...
...tion. ...
...g("wait what?"); } Misused is keyword If you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in JavaScript. ...
Array.prototype.values() - JavaScript
r.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" Array.prototype.values is default implementation of Array.prototype[Symbol.iterator]. ...
... Array.prototype[Symbol.iterator]. ...
...prototype[Symbol.iterator] //true Iteration using .next() var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // Object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // Object { value: "d", done: false } iterator.next(); // Object { value: "e", done: false } iterator.next(); // Object { value: undefined, done: true } iteraror.next().value; // undefined One-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter of iterator) { console.log(let...
...See Iteration protocols. Value: there are no values stored in the array Iterator object; instead it stores the address of the array used in its creation and so depends on the values stored in that array. ...
Setting Up a Development Environment - Archive of obsolete content
n output similar to this: Creating XPI file. adding: install.rdf (deflated 50%) adding: chrome.manifest (deflated 50%) adding: content/browserOverlay.js (deflated 42%) adding: content/browserOverlay.xul (deflated 69%) adding: skin/browserOverlay.css (stored 0%) adding: locale/browserOverlay.dtd (deflated 52%) adding: locale/browserOverlay.properties (stored 0%) Creating XPI file. Done! Build finished successfully. If you inspect the bin directory, you should see the xulschoolhello2.xpi file. If you run make again, you'll only see the last line of the build process. That is because make can tell that the file in the bin directory is up to date, and nothing needs to be done. Making changes on source files will make make run the necessary steps to build the XPI again. You ...
...h_login; make" An example project with XPCOM components is included in the XPCOM section. There is also a mention about building C++ XPCOM, which is something much more complicated. Signing extensions In order to provide additional security for your users, you can choose to add a signature to your extension. The signature verifies that you are the author of this extension, and it can only be done if you have a valid certificate provided by a trusted Certificate Authority. The only noticeable difference for the user is that the XPI installation dialog will say that the extension was created by you, making the dialog a little easier to trust. It's not common to sign extensions because most users will trust the official add-ons site (AMO) rather than rely on extension signatures. On the oth...
...files := $(signature_extra_files) \ $(signature_rsa_file) $(signature_files): $(build_dir) $(xpi_built) @signtool -d $(signature_dir) -k $(cert_name) \ -p $(cert_password) $(build_dir) Keep in mind that your password should not be in your Makefiles, and you must be very careful with the certificate information. Ideally this should be handled by a single person, and only done near the end of the release process. You should also have a different make command, such as make signed in order to distinguish the signed and unsigned development builds. Firefox profile management It is good development practice to keep your test environment separate from everything else. You don't want unstable extensions to break your everyday Firefox profile, risking data loss. It's much b...
XPCOM Objects - Archive of obsolete content
onents implement this interface. All of this documentation is generated from the one present in the Firefox source files, so it's in general very complete and well written. It's a shame XUL Planet is no longer with us. Interfaces can be awkward to handle. If you want to call a method or use an attribute of interface X in a component, you first need to "cast" the component to interface X. This is done via the QueryInterface method that is included in all XPCOM components. this._prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); this._prefValue = this._prefService.getBoolPref("somePreferenceName"); this._prefService.QueryInterface(Ci.nsIPrefBranch2); this._prefService.addObserver("somePreferenceName", this, false); this._prefService.QueryInterface(Ci.nsI...
...his: void setCharPref(in string aPrefName, in string aValue); One of the most important details to notice is that both paratemers have the in keyword. This specifies that these are input parameters, values that the method will use to perform its actions. When is a parameter not an in parameter? In some methods the out keyword is used for parameters that are return values in reality. This is done for certain value types that are not valid as return values in IDL, such as typed arrays. void getChildList(in string aStartingAt, out unsigned long aCount,[array, size_is(aCount), retval] out string aChildArray); This method returns an array of strings. The first parameter is an input that tells the method where to start looking. The second one will hold the length of the return array, and...
...re either pre-existing or you make up. The service also allows you to get all components registered in a category and invoke methods on them. One common use for this service is registering a component as a Content Policy. With it you can detect and filter URL loads. This is covered further ahead in another section of the tutorial. ...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
'); // for MCD .cfg files it used to be in previous releases (up until 7.0) in /usr/lib/thunderbird-X.0/default/pref/autoconf.js The first pref just tells us that we won't encode the file (no more rotary 13 or 7 cf below), the second pref is the name of the file to be read: /usr/lib/thunderbird/thunderbird.cfg. (or firefox.cfg if for firefox...) File Encoding If needed, the encoding can be done with the Perl script: moz-byteshift.pl available at http://www.alain.knaff.lu/howto/Mozi...z-byteshift.pl. For Netscape 4.x the convert function from the Client Customization Kit (CCK) could also do that (and other things like personalize auto-installation...): http://developer.netscape.com/docs/manuals/deploymt/config.htm. AutoConfig Directives Here we want to set users central mail preferenc...
...c=fr", \ "sn=http_server", "cn") ) var running_ldap_server = "ldap2.int-evry.fr"; else if (getLDAPAttributes("ldap0.int-evry.fr", \ "ou=browser,ou=information,dc=int-evry,dc=fr", \ "sn=http_server", "cn") ) var running_ldap_server = "ldap0.int-evry.fr"; else alert("No LDAP server available!"); Here's a complete example of the Unix netscape.cfg file. with (PrefConfig) { // Must be done inside the PrefConfig module // create some variables we might want to use later on... var env_user = getenv("USER"); // Windows username var env_home = getenv("HOME"); // User HomeDir var env_mozilla_home = getenv("MOZILLA_HOME"); var env_mozdebug = getenv("MOZILLA_DEBUG"); //check which LDAP server is running (needs a better procedure!) if (getLDAPAttributes("ldap1.int-evry.fr", ...
...var platform = getPlatform(); // E.G. SunOS4.1.3_U1 var env_user = getenv("USER"); // Unix username var env_home = getenv("HOME"); // User HomeDir var env_display = getenv("DISPLAY"); // X11 Display var env_editor = getenv("EDITOR"); // use in mail edit? var env_visual = ge...
Bookmark Keywords - Archive of obsolete content
ess bar itself a power tool. Searches, lookups, package tracking, and even word definitions can all be retrieved from user-customized bookmarks. The key to this ability, if you'll pardon the pun, is the ability to add a keyword to any Mozilla bookmark. Under ordinary circumstances, this might be used to reduce typing of a common URL: http://www.cnn.com/ could be given the keyword cnn. Once that's done, all it takes to go to the CNN home page would be to type <tt>cnn</tt> into the address bar. Mozilla will automatically expand the keyword to the corresponding bookmarked URL, and load up the site. That's pretty interesting on its own, but Mozilla takes it a step further by allowing the user to define an "entry point" for added information. For example, a keyworded bookmark could be set up so tha...
...ghting. The %s is a little flag that means "insert user input here." It doesn't have to go at the end of the location field-- it can be anywhere inside the field. You just need to fill in whatever piece of a URL it is you want to be able to "fill in" when you use the keymark. All we need now is a keyword, and our keymark will be ready to go. Fill in the value bz, as shown in Figure 5. With that done, all you have to do in the future is type <tt>bz</tt> followed by a space and the bug's number into Mozilla's address bar, and the browser will jump right to the bug with that number. This is illustrated in Figure 6. That's all it takes! Setting up a Google Keymark To set up a keymark that will search Google directly form the address bar, go to Google and run a search for any word. Once you g...
...er of potentially useful bookmarks were considered as possible examples. Instead of just throwing them away, we're providing them for you in the following table. Even better, you can file them for future use by right-clicking (or holding down the control key and clicking on the link) and filing the bookmarks using the "File Bookmark..." option in the contextual menu that pops up. Once that's been done, making the keymark work is a simple matter of going into the Bookmark manager and adding a keyword! Bookmark Suggested Keywords Find Bugzilla entry bug, bugzilla, bz Search Devmo devmo, de Google Search google, gg Dictionary Search dictionary, dict, define, word Thesaurus Search thesaurus, like FedEx Tracking fedex UPS Tracking ups Of course, these are just a beginning. Any We...
In-Depth - Archive of obsolete content
ough the rest of this file, you'll also notice that there are regions for the different states of #back-button. Change those to match your new image as well. Just continue this process for everything that you wish to change and you'll have a new skin in no time. Organizing Images To organize all of your icons you can store them all in one image and then tell Mozilla which portions to use. This is done using the -moz-image-region style. A bunch of 20px X 20px icons in a grid format Above is the source image of some icons setup to use the -moz-image-region style. Each row is a different icon in one of its 4 different states (Normal, Hover, Mouse Down, and Disabled). To cut the pieces out you need to define rectangles in the css file like this: #button-send { -moz-image-region: rect(294px 23px...
...} #button-send:hover { -moz-image-region: rect(294px 46px 315px 23px); } #button-send:hover:active { -moz-image-region: rect(294px 69px 315px 46px); } #button-send[disabled="true"] { -moz-image-region: rect(294px 92px 315px 69px) !important; } The properties for Rect are listed in a clockwise fashion - Top, Right, Bottom, Left. Adding an image to the right of a toolbar This tutorial is done with Mozilla 1.2 in mind. The layout of files can and probably will change over time, but the basics should remain the same. By default, Mozilla 1.2 doesn't support images on the right hand side of the toolbars, but that can be changed with some XBL hacking. Place this xml file in \classic\skin\classic\communicator\toolbar\toolbarBindings.xml (You will need to create the sub directory). What this...
...to toolbar-primary-icon. Note: In versions of Firefox prior to Firefox 3 beta 3, the navigation toolbar's ID is "nav-bar". Put these 3 together and you get: #navigation-toolbar > .toolbar-holder > .toolbar-primary-icon Inside this section of the CSS is where you add an image. Set the background-image to a url of your choosing, such as url("chrome://navigator/skin/icons/dino.png");. When it's all done you should have something that looks like this: #navigation-toolbar > .toolbar-holder > .toolbar-primary-icon { background-image: url("chrome://navigator/skin/icons/dino.png"); } Put the image in that directory, fire up mozilla, and take a look at your creation. If the navigation toolbar dissapears or something, go back and double check everything. Especially the -moz-binding commands. ...
generateCRMFRequest() - Archive of obsolete content
Warning: The features mentioned in this article are deleted proprietary Mozilla extensions, and are not supported in any other browser. They won't work in Firefox 34 or later. Use <keygen> or the future Web Crypto API instead. crmfObject = crypto.generateCRMFRequest("requestedDN", "regToken", "authenticator", "escrowAuthorityCert", "CRMF Generation Done Code", keySize1, "keyParams1", "keyGenAlg1", ..., keySizeN, "keyParamsN", "keyGenAlgN"); This method will generate a sequence of CRMF requests that has N requests. One request for each key pair that is generated. The first three parameters will be applied to every request. The ...
...n no key escrow will be performed. This value specifies which KRA certificate should be used to wrap the private key being escrowed. The user will be prompted for confirmation whenever a key will be escrowed. Only key exchange keys will be escrowed. If a dual use key is being generated, it will not be escrowed. The value of this argument is a base-64 encoded certificate. "CRMF Generation Done Code" This parameter is JavaScript to execute when the CRMF generation is complete. keySizeN The size in bits of the Nth key to generate "keyParamsN" This string is an optional algorithm dependent parameter value. For Diffie-Hellman it is used to specify p and g parameters. For DSA, it will be used to specify pqg. If the key generation requires parameters and the value ...
...sign-nonrepudiation" "ec-nonrepudiation" The generateCRMFRequest() method will cause the user to be presented with a key generation dialog. The dialog describes the key generation process and gives the user the opportunity to cancel the operation. The method generateCRMFRequest() will return an instance of a CRMF Request object. The JavaScript passed in as the "CRMF Generation Done Code" parameter should look at the attribute request of the returned object to get the result of the CRMF generation. The string found by accessing crmfObject.request is the base-64 encoded CRMF message to be sent to the CA/RA, or an error string. The possible error strings are: Error String Description "error:invalidParameter:XXX" The parameter XXX was an invalid value. ...
Using XPInstall to Install Plugins - Archive of obsolete content
ded plugin installation process makes use of the XPInstall APIs to install to the current browser's Plugins directory, install to a secondary location, and to write to the Windows System Registry to disclose this secondary location. This section traces some of the XPInstall APIs that can do this. A complete template of an XPI Package is also presented in this section. Not all the work needs to be done in JavaScript -- if you have a native installer (EXE) that recognizes Netscape Gecko browsers, and you merely wish to wrap the EXE installer in an XPI Package for a streamlined delivery to the client, you can easily do so. This section refers extensively to the XPInstall API Documentation. Initializing Installation with Plugin Identifier All XPInstall installations are initiated with the initI...
...les (ActiveX controls) it installs to a special directory within C:\WINNT\System32\, called C:\WINNT\System32\MyPlugin. XPInstall is able to determine what directory this is by the getFolder API call. We have written our own JavaScript function to contain all the secondary installation code -- function createSecondaryInstall() And finally, it writes the required registry keys to Windows. This is done via the created function, called function registerPLID(). Certainly, this script is Windows-centric, but it is easy to port it to any other platform. Easier, perhaps, since the lengthy Win32 Registry manipulation need not occur on Linux or Mac OSX. The getFolder API provides you with enough "syntactic sugar" to determine other locations on the user's computer on different platforms and OS's. A s...
...ms. Some Installation Concerns This section gathers together some of the chief concerns about deploying XPI packages, notably: how ought a plugin download via XPI be initiated? And what about uninstalling plugins? Triggering an XPInstall Download with a TriggerScript A Trigger Script is web-page delivered piece of JavaScript that can automatically initiate an XPInstall download. This can be done conditionally, since Trigger Scripts can also detect what software has already been installed to the user's machine via XPInstall. This feature is useful for Web sites because: HTML pages and JavaScript already have a way of detecting what plugins are installed. Additionally, via the InstallTrigger object which is exposed in Web pages, they can find out what the last version of the XPI Package ...
Building accessible custom components in XUL - Archive of obsolete content
ue; setTimeout(function(){ var textbox = document.createElementNS(XUL_NS, "textbox"); label.parentNode.replaceChild(textbox, label); textbox.value = value; textbox.origValue = value; textbox.flex = 1; textbox.focus(); textbox.select(); textbox.addEventListener("blur", editable_cell_blur, true); textbox.addEventListener("keypress", editable_cell_keypress, true); }, 0); } function done_edit(textbox, keepValue) { var value = textbox.value; var label = document.createElementNS(XUL_NS, "label"); label.setAttributeNS(X2_NS, "role", "wairole:gridcell"); textbox.parentNode.replaceChild(label, textbox); if (keepValue) { label.value = value; } else { label.value = textbox.origValue; } label.flex = 1; label.addEventListener("keypress", cell_keypress...
... label.setAttributeNS(X2_NS, "role", "wairole:gridcell"); textbox.parentNode.replaceChild(label, textbox); if (keepValue) { label.value = value; } else { label.value = textbox.origValue; } label.flex = 1; label.addEventListener("keypress", cell_keypress, true); return label; } function editable_cell_blur(e) { var textbox = e.target; setTimeout(function() { done_edit(textbox, true); }, 0); } function editable_cell_keypress(e) { var textbox = e.target; switch (e.keyCode) { case KEY_ENTER: setTimeout(function() { var label = done_edit(textbox, true); label.focus(); }, 0); break; case KEY_ESCAPE: setTimeout(function() { var label = done_edit(textbox, false); label.focus(); }, 0); break; } } </code> With thi...
...el.focus(); }, 0); break; } } </code> With this new code, we can now navigate to a specific cell within the spreadsheet and press ENTER to edit the value. The start_edit function replaces the label with a textbox, which allows the user to change the cell value. <caption>Editing a cell</caption> Once we're satisfied with our changes, we can press ENTER again to accept the value. The done_edit function recreates the original label element and sets the new value. Note that the role is once again "cell", since we explicitly set it when we recreated the label element. <caption>After editing a cell</caption> Further reading Accessible HTML spreadsheet demo on mozilla.org Future Enhancements Now that we know how to create an accessible spreadsheet, it should be possible to u...
OpenClose - Archive of obsolete content
a menu by pressing the Escape key. This will close a single menu, but if this menu has a parent menu, the parent menu will remain open. A user may also cancel selecting from a menu by clicking outside the menu. In this case, not only will that menu close, but all parent menus will close as well. A menu may be closed by a script by setting the open property to false, the reverse of what would be done to open the menu. The open property applies to the menu or button, not to the menupopup. somemenu.open = false; This command will close only a single level of menus, so any parent menus will need to be closed with a similar command if desired. However, any child menus of 'somemenu' in the example will be closed, as 'somemenu' will no longer be open. For instance, let's say that a File menu has...
...were adding during the popupshowing event. Menus and popups are also closed when the document or window they are contained within is closed, or if the menupopup element is removed from the document. These are situations when the popuphiding or popuphidden events may not fire as the element the events would be fired on are no longer available. If you need to perform uninitialization that would be done during these events, this could be done during an unload event. Testing Menu Open State To check if a menu is open, check the state of the menu's open property. If the open property is set to true, then the menu is open, otherwise the menu is closed. var open = somemenu.open; Opening a Popup For opening menupopups that use the menu tag, the button tag and the toolbarbutton tag, see Opening ...
...For opening menupopups that use the menu tag, the button tag and the toolbarbutton tag, see Opening Menus above. Popups attached using the popup attribute will be opened when the user clicks the mouse with the left mouse button. There isn't a means of replicating this action with the keyboard, so you should always provide an alternate means of accessing the functionality of the menu. This can be done by either placing alternate commands elsewhere in the user interface, or by providing a keyboard shortcut to open the menu. Once the menu is open, the keyboard can be used to navigate and select items as usual. Popups attached using the context attribute are opened when the user performs an action that attempts to open a context menu. This action will vary on each platform, but it general it inv...
Creating an Installer - Archive of obsolete content
ct in local or remote content, meaning that it is suitable for a download from a Web site. Let's create an example install trigger. This involves the use of the function InstallTrigger.install(). This function takes two arguments, the first is a list of packages to install, and the second is a callback function which will be called when the installation is complete. Here is an example: function doneFn ( name , result ){ alert("The package " + name + " was installed with a result of " + result); } var xpi = new Object(); xpi["Calendar"] = "calendar.xpi"; InstallTrigger.install(xpi,doneFn); First, we define a callback function doneFn() which will be called when the install is complete. You can name the function whatever you like of course. This function has two arguments. The first is the...
... You can name the function whatever you like of course. This function has two arguments. The first is the name of the package that was just installed. This is important if you are installing multiple components. The second argument is a result code. If the result is 0, the installation completed successfully. If the result is non-zero, an error occured and the value is an error code. The function doneFn() here just displays an alert box to the user. Next, we create an array xpi which will hold the name (Calendar) and URL (calendar.xpi) of the installer. You can add an additional similar such line for each package you wish to have installed. Finally, we call the install function. When this section of script is executed, the file calendar.xpi will be installed. Our find files example Let's ...
...r. Next, we create an array xpi which will hold the name (Calendar) and URL (calendar.xpi) of the installer. You can add an additional similar such line for each package you wish to have installed. Finally, we call the install function. When this section of script is executed, the file calendar.xpi will be installed. Our find files example Let's try this with the find files dialog. function doneFn ( name , result ){ if (result) alert("An error occured: " + result); } var xpi = new Object(); xpi["Find Files"] = "findfile.xpi"; InstallTrigger.install(xpi,doneFn); The XPI Archive Note: If you want to create a new XULRunner application, extension, or theme, see Bundles. The installer XPI file is required to contain one file called install.js which is a JavaScript file which is execut...
Document Object Model - Archive of obsolete content
change the name with the code 'name = 7', without having to specify any object to use. In a browser context, the window is the global object, and the same is also true for XUL. Naturally, this global object will be different for each window. Each frame will also have a separate window object. The window is often referred to using the window property, although this is optional. Sometimes, this is done just to clarify the scope of the method you are referring to. For example, the following two lines which open a new window are functionally equivalent: window.open("test.xul","_new"); open("test.xul","_new"); When you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object. In XUL, each function...
...er id="progmeter" value="50%" style="margin: 4px;" hidden="true"/> We've added the hidden attribute and set the value to true. This causes the element to be hidden when it first appears. Next, let's add a function that is called when the Find button is pressed. We'll put scripts in a separate file findfile.js. In the last section, we added the script element in the XUL file. If you haven't done this, do that now, as shown below. An oncommand handler will also be added to the Find button. <script src="findfile.js"/> . . . <button id="find-button" label="Find" oncommand="doFind();"/> Now, create another file called findfile.js in the same directory as findfile.xul. We'll add the doFind() function is this file. The script tag does allow code to be contained directly inside of i...
...tax element.hidden where 'element' is a reference to the element. You might note that most of the properties listed in the reference correlate to common attributes on elements. There are differences, of course, for example, while getAttribute("hidden") will return the string 'true' for a hidden element, whereas the hidden property returns a boolean true value. In this case, the type conversion is done for you so the property is more convenient. As with each document, there is a different element object for XUL elements as for HTML and XML elements. Every XUL element implements the XULElement (reference broken) interface. A XUL element is any element declared with the XUL namespace. So, XUL elements will have that interface even if added to other XML documents, and non-XUL elements will not ha...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
th="150" height="115"> <h3>Clown Trigger</h3> <p> Our clown trigger is a bold little fish, though for a few weeks he slept a lot and didn't look well in general. He's much better now. </p> </div> Basically, that's all that was needed. The reason for the class value being card is that the original idea was to style each fish's description like a trading card. Although this design approach was abandoned fairly quickly, the class name stuck, kind of like a barnacle. Giving the Fish Some Style With the markup all set, it was time to style. The idea was to have the fish listed in a side-by-side arrangement, sort of like a two-column table, only without the table. This was most easily accomplished by floating the div elements themselves. Since I wanted them to be side by side, it was important to...
...set up to float, the next step was to place the images appropriately. This involved floating the image inside the floated div. It just seemed like a Fish Cam page should have a lot of floating for some reason. I also added a border to the image, so that it would have a nice frame. div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; border: 1px solid #339;} That done, it was time to style the fish names. These are enclosed in h3 elements, so the field was pretty wide open in terms of what we could do. Since the image was floated, any background or border we set on the h3 would "slide under" the image; this is an expected effect with floated elements. Rather than try to fight it or push the image below the h3's element box, I let the image mostly overlap the h...
...argin: 1em 2% 0 2%;} div.card img {float: left; position: relative; z-index: 10; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {margin: 0 0 0 4px; padding: 0.2em 0 1px 150px; border: 1px solid #339; border-left: 5px double #339; background: #EEC url(body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} div.card p {margin: 0.5em 0.5em 0.5em 160px;} And voila! The cards are done. Conclusion Redesigning a classic is something like being asked to reviseMoby Dick for modern audiences: you're thrilled at the opportunity, but afraid of doing injustice to the original. I'd like to think that the final result was in keeping with the original spirit of the Amazing Netscape Fish Cam page while giving it a nice new CSS-driven look. I hope that our little cruise through this asp...
Implementation Status - Archive of obsolete content
4 Processing Model (Events) partial The xforms-recalculate, xforms-revalidate, and xforms-refresh events are not as separated as they should be. ...
... 4.4.15 xforms-select xforms-deselect supported 4.4.16 xforms-in-range supported 4.4.17 xforms-out-of-range supported 4.4.18 xforms-scroll-first xforms-scroll-last supported 4.4.19 xforms-submit-done supported 4.5 Error Indications partial We don't support the xforms-version-exception event, yet 4.5.1 xforms-binding-exception supported 4.5.2 xforms-compute-exception supported 4.5.3 xforms-link-error partial No...
...2 xforms-submit partial We currently limit (for security reasons) submission only back to the server that served the document. But the user can choose to remove this restriction on a site by site basis via a preference. Click for more details. ...
Index - Game development
d unwilling) to make. The concern is mostly with switching to another option. Fortunately, I do not have any experience with this, but I have heard it is an excruciating game of Whack-a-Mole. 3 Examples Demos, Example, Games, Web This page lists a number of impressive web technology demos for you to get inspiration from, and generally have fun with. A testament to what can be done with JavaScript, WebGL, and related technologies. 4 Index Meta Found 74 pages: 5 Introduction to HTML5 Game Development (summary) Firefox OS, Games, HTML5, Mobile Games built with HTML5 work on smartphones, tablets, PCs and Smart TVs.Update your game whenever you want.Players can play the game anywhere, anytime. 6 Introduction to game developme...
...game more interesting we can introduce the ability to lose -- if you don't hit the ball before it reaches the bottom edge of the screen it will be game over. 50 Initialize the framework 2D, Beginner, Canvas, Games, HTML, JavaScript, Phaser, Tutorial Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML -- the Phaser framework will generate the required <canvas> element. 51 Load the assets and print them on screen 2D, Beginner, Canvas, Games, JavaScript, Phaser, Sprites, Tutorial Our game will feature a ball rolling around the screen, bouncing off a paddle, and destroying bricks to earn points -- familiar, huh? In this article we'll look at how to add sprites into...
...still isn't that interesting as the ball goes through them. We need to think about adding collision detection so it can bounce off the bricks and break them. 63 Create the Canvas and draw on it 2D, Beginner, Canvas, Games, HTML, JavaScript, Tutorial Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML and the <canvas> element. 64 Finishing up Beginner, Canvas, Games, JavaScript, Tutorial, lives, requestAnimationFrame There's always room for improvements in any game we write. For example, we can offer more than one life to the player. They could make a mistake or two and still be able to finish the game. We could also improve our code rendering. 65 Gam...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
oding or compression technology. 83 Compile CodingScripting, Glossary Compiling is the process of transforming a computer program written in a given language into an equivalent program of another language. A compiler is a software to execute this task. Sometimes, this task is also referred to as "assembling" or "build", which typically indiciates more than just compilation is done, e.g. packaging it in a binary format. 84 Compile time CodingScripting, Glossary, JavaScript The compile time is the time from when the program is first loaded until the program is parsed. 85 Computer Programming CodingScripting, Computer Programming, Programming Language, programming Computer programming is a process of composing and organizing a collect...
...eously, resulting in a faster page load time and improved user experience. 121 Dominator CodingScripting, Glossary In graph theory, node A dominates node B if every path from the root node to B passes through A. 122 Dynamic programming language CodingScripting, Glossary A dynamic programming language is a programming language in which operations otherwise done at compile-time can be done at run-time. For example, in JavaScript it is possible to change the type of a variable or add new properties or methods to an object while the program is running. 123 Dynamic typing CodingScripting, Glossary, ProgrammingLanguage Dynamically-typed languages are those (like JavaScript) where the interpreter assigns variables a type at runtime based ...
...de syntax works, or illustrate the design of an item of code architecture. It won't work if you try to run it as code. 346 Public-key cryptography Cryptography, Glossary, Public-key cryptography, Security Public-key cryptography -- or asymmetric cryptography -- is a cryptographic system in which keys come in pairs. The transformation performed by one of the keys can only be undone with the other key. One key (the private key) is kept secret while the other is made public. 347 Python CodingScripting, Glossary, Language, Python, programming Python is a high level general-purpose programming language. It uses a multi-paradigm approach, meaning it supports procedural, object-oriented, and some functional programming constructs. 348 QUIC Glos...
CSS and JavaScript accessibility best practices - Learn web development
onable to expect you to make it 100% accessible to blind people, however you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies. The problem with too much JavaScript The problem often comes when people rely on JavaScript too much. Sometimes you'll see a website where everything has been done with JavaScript -- the HTML has been generated by JavaScript, the CSS has been generated by JavaScript, etc. This has all kinds of accessibility and other issues associated with it, so it is not advised. As well as using the right element for the right job, you should also make sure you are using the right technology for the right job! Think carefully about whether you need that shiny JavaScript...
...is clicked, without needing the onclick/focus() block. Safari will only highlight the form element with the link on its own, so needs the onclick/focus() block to actually focus it. Firefox doesn't focus the inputs properly at all in this context, so Firefox users can't take advantage of this at present (although everything else works fine). The Firefox issue should be fixed soon -- work is being done to give Firefox behaviour parity with other browsers (see bug 277178). In addition, the errorField is placed at the top of the source order (although it is positioned differently in the UI using CSS), meaning that users can find out exactly what's wrong with their form submissions and get to the input elements in question by going back up to the start of the page. As a final note, we have used...
...Img; imgThumb.onfocus = showImg; imgThumb.onblur = hideImg; The first two lines run the functions when the mouse pointer hovers over and stops hovering over the thumbnail, respectively. This won't allow us to access the zoomed view by keyboard though -- to allow that, we've included the last two lines, which run the functions when the image is focused and blurred (when focus stops). This can be done by tabbing over the image, because we've included tabindex="0" on it. The click event is interesting -- it sounds mouse-dependent, but most browsers will activate onclick event handlers after Enter/Return is pressed on a link or form element that has focus, or when such an element is tapped on a touchscreen device. This doesn't work by default however when you allow a non-default-focusable event...
Advanced form styling - Learn web development
Previous Overview: Forms Next In this article, we will see what can be done with CSS to style the types of form control that are more difficult to style -- the "bad" and "ugly" categories. As we saw in the previous article, text fields and buttons are perfectly easy to style; now we will dig into styling the bits that are more problematic. Prerequisites: Basic computer literacy, and a basic understanding of HTML and CSS. Objective: To understand what parts of forms are hard to style, and why; to learn what can be done to customize them. To recap what we said in the previous article, we have: The bad: Some elements are more difficult to style, requiring more complex CSS or some more specific tricks: Checkboxes and radio buttons <input type="search"...
...ew these checkboxes in a browser that doesn't support appearance, your custom design will be lost, but they will still look like checkboxes and be usable. Note: While Internet Explorer doesn't support any version of appearance, the input[type=checkbox]::-ms-check enables the targeting of checkboxes in IE only. This technique works for radio buttons too, despite the name -ms-check. What can be done about the "ugly" elements? Now let's turn our attention to the "ugly" controls -- the ones that are really hard to thoroughly style. In short, these are drop-down boxes, complex control types like color and datetime-local, and feedback--oriented controls like <progress> and <meter>. The problem is that these elements have very different default looks across browsers, and while you can style th...
... If you want to test these examples across a number of browsers simultaneously, you can find it live here (also see here for the source code). Also bear in mind that we've added some JavaScript to the page that lists the files selected by the file picker, below the control itself. This is a simplified version of the example found on the <input type="file"> reference page. As you can see, we've done fairly well at getting these to look uniform across modern browsers. We've applied some global normalizing CSS to all the controls and their labels, to get them to size in the same way, adopt their parent font, etc., as mentioned in the previous article: button, label, input, select, progress, meter { display: block; font-family: inherit; font-size: 100%; padding: 0; margin: 0; box-...
Test your skills: Links - Learn web development
ult mail application, with the recipient set as "whales@example.com". You'll get a bonus point if you also set it so that the subject line of the email is automatically filled in as "Question about Whales". Note: The first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens the page in a new tab. This is not strictly best practice, but we've done it here so that the page doesn't open in the embedded <iframe>, getting rid of your example code in the process! Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Links 2 In this task we want you to fill in the four links so that they link to the appropriate places: The first ...
...google.co.uk, and the image search is located in a subdirectory called imghp. The fourth link should link to the paragraph at the very bottom of the current page. It has an ID of bottom. Note: The first three links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab. This is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Links 3 The following links link to an info page about Narwhals, a support email address, and a PDF factfile that is 4...
...e want you to: Take the existing paragraphs with poorly-written link text, and rewrite them so that they have good link text. Add a warning to any links that need a warning added. Note: The first and third links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab. This is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your w...
From object to iframe — other embedding technologies - Learn web development
browser that doesn't support <iframe>s these days. sandbox This attribute, which works in slightly more modern browsers than the rest of the <iframe> features (e.g. IE 10 and above) requests heightened security settings; we'll say more about this in the next section. Note: In order to improve speed, it's a good idea to set the iframe's src attribute with JavaScript after the main content is done with loading. This makes your page usable sooner and decreases your official page load time (an important SEO metric.) Security concerns Above we mentioned security concerns -- let's go into this in a bit more detail now. We are not expecting you to understand all of this content perfectly the first time; we just want to make you aware of this concern, and provide a reference to come back to a...
... when they are served from a web server) designed to improve the security of your HTML document. When it comes to securing <iframe>s, you can configure your server to send an appropriate X-Frame-Options header. This can prevent other websites from embedding your content in their web pages (which would enable clickjacking and a host of other attacks), which is exactly what the MDN developers have done, as we saw earlier on. Note: You can read Frederik Braun's post On the X-Frame-Options Security Header for more background information on this topic. Obviously, it's rather out of scope for a full explanation in this article. The <embed> and <object> elements The <embed> and <object> elements serve a different function to <iframe> -- these elements are general purpose embedding tools for emb...
...ash, Adobe announced that they would stop supporting it at the end of 2020. As of January 2020, most browsers block Flash content by default, and by December 31st of 2020, all browsers will have completly removed all Flash functionality. Any existing Flash content will be inaccessable after that date. So what should you do? If you need interactivity, HTML and JavaScript can readily get the job done for you with no need for Java applets or outdated ActiveX/BHO technology. Instead of relying on Adobe Flash, you should use HTML5 video for your media needs, SVG for vector graphics, and Canvas for complex images and animations. Peter Elst was already writing some years ago that Adobe Flash is rarely the right tool for the job. As for ActiveX, even Microsoft's Edge browser no longer supports it. ...
Index - Learn web development
and navigating to the HTML file. There are many ways to achieve this. 21 How do you upload your files to a web server? Beginner, FTP, GitHub, Uploading, WebMechanics, hosting, rsync, sftp If you have built a simple web page (see HTML basics for an example), you will ...
...er, Components, Frameworks, JavaScript, Learn, Svelte, client-side, state With our markup and styling in place our Todo list app is starting to take shape, and we have everything ready so that we can start to focus on the features we have to implement. 296 Styling Vue components with CSS Beginner, CSS, Frameworks, JavaScript, Learn, Styling, client-side, vue Our work is done on the styling of our sample app. In the next article we'll return to adding some more functionlity to our app, namely using a computed property to add a count of completed todo items to our app. 297 TypeScript support in Svelte Beginner, Frameworks, JavaScript, Learn, Svelte, Typescript, client-side In this article we took our to-do list application and ported it to TypeScri...
...TML5. 311 CSS property compatibility table for form controls Advanced, CSS, Forms, Guide, HTML, Junk, NeedsUpdate, Web The following compatibility tables try to summarize the state of CSS support for HTML forms. Due to the complexity of CSS and HTML forms, these tables can't be considered a perfect reference. However, they will give you good insight into what can and can't be done, which will help you learn how to do things. 312 Client-side form validation Beginner, Example, Forms, Guide, HTML, JavaScript, Learn, Web, regex Client-side form validation sometimes requires JavaScript if you want to customize styling and error messages, but it always requires you to think carefully about the user. Always remember to help your users correct the data they pr...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
ere's a few hints for you: You can structure and style the button markup however you like; just make sure you use semantic HTML, with hooks to allow you to grab the button references using JavaScript. You probably want to create a variable that starts at 0, then increments by one every second using a constant loop. It is easier to create this example without using a Date() object, like we've done in our version, but less accurate -- you can't guarantee that the callback will fire after exactly 1000ms. A more accurate way would be to run startTime = Date.now() to get a timestamp of exactly when the user clicked the start button, and then do Date.now() - startTime to get the number of milliseconds after the start button was clicked. You also want to calculate the number of hours, minutes, ...
...he draw() function at a rate as near 60 FPS as possible. rAF = requestAnimationFrame(draw); Below the draw() function definition, add a call to the the draw() function to start the animation. draw(); Note: You can find the finished example live on GitHub. (You can see the source code, also.) Clearing a requestAnimationFrame() call Clearing a requestAnimationFrame() call can be done by calling the corresponding cancelAnimationFrame() method. (Note that the function name starts with "cancel", not "clear" as with the "set..." methods.) Just pass it the value returned by the requestAnimationFrame() call to cancel, which you stored in the variable rAF: cancelAnimationFrame(rAF); Active learning: Starting and stopping our spinner In this exercise, we'd like you to test out t...
... if isOver is true, remove the keydown event listener using removeEventListener() so that once the winning press has happened, no more keyboard input is possible to mess up the final game result. You also use setTimeout() to call reset() after 5 seconds -- as explained earlier, this function resets the game back to its original state so that a new game can be started. That's it--you're all done! Note: If you get stuck, check out our version of the reaction game (see the source code also). Conclusion So that's it -- all the essentials of async loops and intervals covered in one article. You'll find these methods useful in a lot of situations, but take care not to overuse them! Because they still run on the main thread, heavy and intensive callbacks (especially those that manipulate ...
Making decisions in your code — conditionals - Learn web development
s and indentation. A real example To understand this syntax better, let's consider a real example. Imagine a child being asked for help with a chore by their mother or father. The parent might say "Hey sweetheart! If you help me by going and doing the shopping, I'll give you some extra allowance so you can afford that toy you wanted." In JavaScript, we could represent this like so: let shoppingDone = false; if (shoppingDone === true) { let childsAllowance = 10; } else { let childsAllowance = 5; } This code as shown always results in the shoppingDone variable returning false, meaning disappointment for our poor child. It'd be up to us to provide a mechanism for the parent to set the shoppingDone variable to true if the child did the shopping. Note: You can see a more complete version...
...else It is perfectly OK to put one if...else statement inside another one -- to nest them. For example, we could update our weather forecast application to show a further set of choices depending on what the temperature is: if (choice ===...
...else It is perfectly OK to put one if...else statement inside another one -- to nest them. For example, we could update our weather forecast application to show a further set of choices depending on what the temperature is: if (choice === 'sunny') { if (temperatu...
Manipulating documents - Learn web development
In this article we'll look at how to use the DOM in detail, along with some other interesting APIs that can alter your environment in interesting ways. ...
... document using Document.stylesheets, which returns an array-like object with CSSStyleSheet objects. You can then add/remove styles as wished. However, we're not going to expand on those features because they are a somewhat archaic and difficult way to manipulate style. There are much easier ways. The first way is to add inline styles directly onto elements you want to dynamically style. This is done with the HTMLElement.style property, which contains inline styling information for each element in the document. You can set properties of this object to directly update element styles. As an example, try adding these lines to our ongoing example: para.style.color = 'white'; para.style.backgroundColor = 'black'; para.style.padding = '10px'; para.style.width = '250px'; para.style.textAlign = ...
...h have their advantages and disadvantages. The first method takes less setup and is good for simple uses, whereas the second method is more purist (no mixing CSS and JavaScript, no inline styles, which are seen as a bad practice). As you start building larger and more involved apps, you will probably start using the second method more, but it is really up to you. At this point, we haven't really done anything useful! There is no point using JavaScript to create static content -- you might as well just write it into your HTML and not use JavaScript. It is more complex than HTML, and creating your content with JavaScript also has other issues attached to it (such as not being readable by search engines). In the next couple of sections we will look at a couple of more practical uses of DOM APIs...
Basic math in JavaScript — numbers and operators - Learn web development
uals 6". But the browser does "10 divided by 8 equals 1.25", then "50 plus 1.25 plus 2 equals 53.25". This is because of operator precedence -- some operators are applied before others when calculating the result of a calculation (referred to as an expression, in programming). Operator precedence in JavaScript is the same as is taught in math classes in school -- Multiply and divide are always done first, then add and subtract (the calculation is always evaluated from left to right). If you want to override operator precedence, you can put parentheses round the parts that you want to be explicitly dealt with first. So to get a result of 6, we could do this: (num2 + num1) / (8 + 2); Try it and see. Note: A full list of all JavaScript operators and their precedence can be found in Expres...
...at you want to be explicitly dealt with first. So to get a result of 6, we could do this: (num2 + num1) / (8 + 2); Try it and see. Note: A full list of all JavaScript operators and their precedence can be found in Expressions and operators. Increment and decrement operators Sometimes you'll want to repeatedly add or subtract one to or from a numeric variable value. This can be conveniently done using the increment (++) and decrement (--) operators. We used ++ in our "Guess the number" game back in our first splash into JavaScript article, when we added 1 to our guessCount variable to keep track of how many guesses the user has left after each turn. guessCount++; Note: These operators are most commonly used in loops, which you'll learn about later on in the course. For example, say yo...
...d in loops, which you'll learn about later on in the course. For example, say you wanted to loop through a list of prices, and add sales tax to each one. You'd use a loop to go through each value in turn and do the necessary calculation for adding the sales tax in each case. The incrementor is used to move to the next value when needed. We've actually provided a simple example showing how this is done -- check it out live, and look at the source code to see if you can spot the incrementors! We'll look at loops in detail later on in the course. Let's try playing with these in your console. For a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. The following will return...
Inheritance in JavaScript - Learn web development
be passed to the function when it is invoked. We want the Teacher() constructor to take the same parameters as the Person() constructor it is inheriting from, so we specify them all as parameters in the call() invocation. The last line inside the constructor simply defines the new subject property that teachers are going to have, which generic people don't have. As a note, we could have simply done this: function Teacher(first, last, age, gender, interests, subject) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; this.subject = subject; } But this is just redefining the properties anew, not inheriting them from Person(), so it defeats the point of what we are trying to do. It also takes more lines of code. Inheriting fr...
...ut it just yet -- you are still learning, and familiarity will come with practice. ECMAScript 2015 Classes ECMAScript 2015 introduces class syntax to JavaScript as a way to write reusable classes using easier, cleaner syntax, which is more similar to classes in C++ or Java. In this section we'll convert the Person and Teacher examples from prototypal inheritance to classes, to show you how it's done. Note: This modern way of writing classes is supported in all modern browsers, but it is still worth knowing about the underlying prototypal inheritance in case you work on a project that requires supporting a browser that doesn't support this syntax (most notably Internet Explorer). Let's look at a rewritten version of the Person example, class-style: class Person { constructor(first, las...
...before accessing 'this' or returning from derived constructor For sub-classes, the this intialization to a newly allocated object is always dependant on the parent class constructor, i.e the constructor function of the class from which you're extending. Here we are extending the Person class -- the Teacher sub-class is an extension of the Person class. So for Teacher, the this initialization is done by the Person constructor. To call the parent constructor we have to use the super() operator, like so: class Teacher extends Person { constructor(subject, grade) { super(); // Now 'this' is initialized by calling the parent constructor. this.subject = subject; this.grade = grade; } } There is no point having a sub-class if it doesn't inherit properties from the parent class. ...
Componentizing our React app - Learn web development
s a new prop of completed. The first (Eat) should have a value of true; the rest should be false: <Todo name="Eat" completed={true} /> <Todo name="Sleep" completed={false} /> <Todo name="Repeat" completed={false} /> As before, we must go back to Todo.js to actually use these props. Change the defaultChecked attribute on the <input /> so that its value is equal to the completed prop. Once you're done, the Todo component's <input /> element will read like this: <input id="todo-0" type="checkbox" defaultChecked={props.completed} /> And your browser should update to show only Eat being checked: If you change each <Todo /> component's completed prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly. Gimme some id, please Right now, our <Todo /> component gi...
... Copy the <form> tags and everything between them from inside App.js, and paste them inside Form()'s return statement. Export Form at the end of the file. ...
...first made for the <Todo /> component, in that each button will be the same. That's fine! We're going to fix up this component later on, in Back to the filter buttons. Importing all our components Let's make use of our new components. Add some more import statements to the top of App.js, to import them. Then, update the return statement of App() so that it renders our components. ...
Deployment and next steps - Learn web development
not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at different options for deploying our Svelte applications, further resources, and more. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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. Compiling our app So far we've been running our app in developme...
...global.css'> <link rel='stylesheet' href='build/bundle.css'> <script defer src='build/bundle.js'></script> Do this now. Now we just have to commit and push our changes to GitLab. Do this by running the following commands: > git add public/index.html > git add .gitlab-ci.yml > git commit -m "Added .gitlab-ci.yml file and fixed index.html absolute paths" > git push Counting objects: 5, done. Delta compression using up to 8 threads. Compressing objects: 100% (5/5), done. Writing objects: 100% (5/5), 541 bytes | 541.00 KiB/s, done. Total 5 (delta 3), reused 0 (delta 0) To gitlab.com:opensas/mdn-svelte-todo.git 7dac9f3..5725f46 master -> master Whenever there's a job running GitLab will display an icon showing the process of the job. Clicking on it will let you inspect the outp...
...utomatically rebuilt and deployed to GitLab Pages. Learning more about Svelte In this section we'll give you some resources and projects to go and check out, to take your Svelte learning further. Svelte documentation To go further and learn more about Svelte, you should definitely visit the Svelte homepage. There you'll find many articles explaining Svelte's philosophy. If you haven't already done it, make sure you go through the Svelte interactive tutorial. We already covered most of its content, so it won't take you much time to complete it -- you should consider it as practise! You can also consult the Svelte API docs and the available examples. To understand the motivations behind Svelte, you should read Rich Harris's Rethinking reactivity presentation on YouTube. He is the creator o...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
oughout the course of this article: MoreActions: Displays the Check All and Remove Completed buttons, and emits the corresponding events required to handle their functionality. NewTodo: Displays the <input> field and Add button for adding a new todo. TodosStatus: Displays the "x out of y items completed" status heading. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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. REPL To code along with us using the REPL, start a...
...no text content) using disabled={!name}. We are also taking...
...h('addTodo', name) name = '' nameEl.focus() // give focus to the name input } const onCancel = () => { name = '' nameEl.focus() // give focus to the name input } </script> <form on:submit|preventDefault={addTodo} on:keydown={e => e.key === 'Escape' && onCancel()}> <h2 class="label-wrapper"> <label for="todo-0" class="label__lg">What needs to be done?</label> </h2> <input bind:value={name} bind:this={nameEl} type="text" id="todo-0" autoComplete="off" class="input input__lg" /> <button type="submit" disabled={!name} class="btn btn__primary btn__lg">Add</button> </form> Try the app out -- type a new todo name in to the <input> field, press tab to give focus to the Add button, and then hit Enter or Escape to see how the input recovers foc...
Handling common JavaScript problems - Learn web development
gle file using a solution like Browserify. In general, reducing the number of HTTP requests is very good for performance. Make your files even smaller by minifying them before you load them onto your production server. Minifying squashes all the code together onto a huge single line, making it take up far less file size. It is ugly, but you don't need to read it when it is finished! This is best done using a minification tool like Uglify (there's also an online version -- see JSCompress.com) When using APIs, make sure you turn off the API features when they are not being used; some API calls can be really expensive on processing power. For example, when showing a video stream, make sure it is turned off when you can't see it. When tracking a device's location using repeated Geolocation calls...
...ting whether the Promise object and fetch() function exist in the browser. If both do, the function returns true. If the function returns false, then we run the code inside the second part of the conditional -- this runs a function called loadScript(), which loads the polyfills into the page, then runs main() after the loading has finished. ...
...turns true. If the function returns false, then we run the code inside the second part of the conditional -- this runs a function called loadScript(), which loads the polyfills into the page, then runs main() after the loading has finished. loadScript() looks like this: function loadScript(src, done) { const js = document.createElement('script'); js.src = src; js.onload = function() { done(); }; js.onerror = function() { done(new Error('Failed to load script ' + src)); }; document.head.appendChild(js); } This function creates a new <script> element, then sets its src attribute to the path we specified as the first argument ('polyfills.js' when we called it in the code above). When it has loaded, we run the function we specified as the second argument (main()). If an e...
Command line crash course - Learn web development
a waste of time -- instead, you can type one command, with the different items in the path separated by forward slashes, just like you do when specifying paths to images or other assets in CSS, HTML, or JavaScript code: cd Desktop/project/src Note that including a leading slash on your path makes the path absolute, for example /Users/your-user-name/Desktop. Omitting the leading slash like we've done above makes the path relative to the your present working directory. This is exactly the same as you would see with URLs in your web browser. A leading slash means "at the root of the web site", whereas omitting the slash means "the URL is relative to my current page". Note: On windows you use backslashes instead of forward slashes, e.g. cd Desktop\project\src -- this may seem really odd, but i...
...for a letter "d" on the very left-hand side of the lines. Those are the ones we can cd into. Below is a screenshot with a "vanilla" macOS terminal at the top, and a customised terminal with some extra icons and colors to keep it looking lively -- both showing the results of running ls -l: Note: To find out exactly what options each command has available, you can look at its man page. This is done by typing the man command, followed by the name of the command you want to look up, for example man ls. This will open up the man page in the terminal's default text file viewer (for example, less in my terminal), and you should then be able to scroll through the page using the arrow keys, or some similar mechanism. The man page lists all the options in great detail, which may be a bit intimidati...
... in the first location specified, in the second location specified. For example, cp mdn-example.txt mdn-example.txt.bak creates a copy of mdn-example.txt called mdn-example.txt.bak (you can of course call it something else if you wish). rm -- removes the specified file. For example, rm mdn-example.txt deletes a single file called mdn-example.txt. Note that this delete is permanent and can't be undone via the recycle bin that you might have on your desktop user interface. Note: Many terminal commands allow you to use asterisks as "wild card" characters, meaning "any sequence of characters". This allows you to run an operation against a potentially large number of files at once, all of which match the specified pattern. As an example, rm mdn-* would delete all files beginning with mdn-. rm m...
Creating a Language Pack
relative to MOZ_OBJDIR ac_add_options --enable-application=[browser or mail] The given path should have your localization directory as child (i.e., a subdirectory ab-CD where ab-CD is your locale code). You still need to specify which application you're localizing (e.g., for Firefox, that's browser, Thunderbird would be mail). Configure step You need to prepare the build directory, which is done with ./mach configure You only need to run this if the version number of Firefox changes. WINDOWS: Replace make with mozmake in the commands below! Creating a langpack We will now merge the localized files from x-testing locale with the en-US files from the original source. Every time you want to create a langpack, you need to be in the directory obj-firefox-build/browser/locales. It i...
...ng success message: Downloaded http://ftp.mozilla.org/pub/mozilla.o....en-US.mac.dmg to /Users/your_id/Mozilla/vc/firefox/browser/locales/../../dist/firefox-3.6b5pre.en-US.mac.dmg The en-US binary has been downloaded. Let's unpack it $ make unpack Again, for 64-bit Mac, append MOZ_PKG_PLATFORM=mac to this command. At the end of the process, you should see the following success message. ... done unpacking Let's check which revision the binary was built from. $ make ident fx_revision 237dccbcb967 buildid 20091126033851 You can now go back to your source hg clone. $ cd ../../../mozilla-aurora And update the source code to this revision. $ hg update -r 237dccbcb967 3 files updated, 0 files merged, 0 files removed, 0 files unresolved The source code has been updated to the revisio...
...ds. Remember that you need to be in the directory firefox-build/browser/locales. $ make merge-x-testing LOCALE_MERGEDIR=$(PWD)/mergedir $ make installers-x-testing LOCALE_MERGEDIR=$(PWD)/mergedir At the end of the process, you should see the following success message. ...
JavaScript-DOM Prototypes in Mozilla
rototype names. What's the difference? Class constructor names are names of real classes, and class prototype names are names of "classes" that are inherited by real classes, but are not real classes. A few examples of class constructor names would be HTMLImageElement, HTMLDocument, Element, NodeList, and two examples of class prototype names would be Node and CharacterData. This registration is done with the nsScriptNameSpaceManager, which is in charge of keeping track of what names are registered in the global namespace, and what kinds of names those names are (i.e. class constructor name, class prototype name). When a class constructor name is registered (nsGlobalNameStruct::eTypeClassConstructor), the nsScriptNameSpaceManager is given a DOM class info ID (a 32 bit ID that identifies class...
...ed (nsGlobalNameStruct::eTypeClassProto), the nsScriptNameSpaceManager is given the nsIID of the interface that is inherited by the class which the registered name is a prototype of (e.g. NS_GET_IID(nsIDOMNode) for Node). nsScriptNameSpaceManager also deals with other types of names, but those are unrelated to the DOM object prototype setup, so we will ignore those here. Once the registration is done, the nsDOMClassInfo code uses the registry every time a named property is resolved on a global object (because of this, the nsScriptNameSpaceManager needs to be pretty fast at looking things up in its registry; that's why it is a hash table). When a property is resolved on the global object, the nsDOMClassInfo code will ask the nsScriptNameSpaceManager if the name is a known name (in nsWindowSH::...
...Script wrapper for a DOM object), XPConnect will call the scriptable helper method nsDOMClassInfo::PostCreate() which will make sure the prototype chain of the wrapper JSObject is properly set up. In this call, the nsDOMClassInfo code just needs to resolve the name of the class on the global object, and the prototype will be set up by the resolving code (nsWindowSH::GlobalResolve()). This is also done only once per class, nsDOMClassInfo::PostCreate() checks if the prototype of the prototype of the wrapper JSObject (i.e. obj.__proto__.__proto__) has been set up already, if it has, then there's nothing left to do in nsDOMClassInfo::PostCreate(). Original Document Information Author(s): Fabian Guisset Last Updated Date: February 2, 2002 Copyright Information: Copyright (C) Fabian Guisset ...
Following the Android Toasts Tutorial from a JNI Perspective
text context = getApplicationContext(); CharSequence text = "Hello, Firefox!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); NativeWindow code As mentioned earlier, toasts are a very popular feature, so Mozilla developers chose to bring it to the privileged JavaScript scope via the NativeWindow object. The Java code example above can be done with privileged JavaScript from Firefox for Android with the following code: window.NativeWindow.toast.show("Hello, Firefox!", "short"); Converting Java to JNI.jsm The first step is to look at the Java code and see all the different types, methods, constructors, and fields that are being used. In the toast code we have the following: Types - Context, CharSequence, int, Toast, and void Met...
...For example, if the class is blah.foo.bar then the signature of this will be this in slash notation with an L and ; around it. So this would be Lblah/foo/bar;. If there is a sub class such as blah.foo.bar.subclass then a dollar sign is used in the slash notation, so this would be Lblah/foo/bar$subclass;. When declaring methods, the signatures of the types go right next to each ...
...re 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. Load the class The first step is to load the class. Every constructor, method, and field belongs to a class. In our case, we have a class called Toast, and to this belongs makeText, show, and LENGTH_SHORT. To load the class the following is done: let Toast = JNI.LoadClass(my_jenv, SIG.Toast.substr(1, SIG.Toast.length - 2), { // declares of constructors, static_methods, methods, fields, and static_fields go here }); The variable name of Toast was used, but it does not matter, you can use whatever you want. The first argument to LoadClass is the Java environment variable, my_jenv. The second argument is the class sig without the su...
Sqlite.jsm
The Sqlite.jsm JavaScript code module is a promise-based wrapper around the Storage/SQLite interface. Sqlite.jsm offers some compelling advantages over the low-level Storage XPCOM interfaces: Automatic statement management. Sqlite.jsm will create, manage, and destroy statement instances for you. You don't need to worry about caching created statement instances, destroying them when you are done, etc. This translates to fewer lines of code to talk to SQLite. All operations are asynchronous. Use of synchronous Storage APIs is discouraged because they block the main thread. All the functionality in Sqlite.jsm is asynchronous. Easier memory management. Since Sqlite.jsm manages statements for you, it can perform intelligent actions like purging all cached statements not in use, freeing memory...
...il the API of an opened connection instance. Connection Management These APIs are used to manage and inspect the state of the connection. close() Close this database connection. This must be called on every opened connection or else application shutdown will fail due to waiting on the opened connection to close (Gecko doesn't force close connections because it doesn't know that you are really done with them). This function returns a promise that will be resolved when the database has closed. If a transaction is in progress at the time this function is called, the transaction will be forcibly rolled back. If statements are in progress at the time this function is called, they will be cancelled. Callers should not attempt to use the connection after calling this method as the connection ...
...tion is a promise that is resolved when the transaction has been committed or is rejected if the transaction was rolled back. Examples Open, Execute, Close In this example, we open a connection, execute a simple statement, then close the connection. const conn = await Sqlite.openConnection({path: "MyDB.sqlite"}); const result = await conn.execute("SELECT 1"); await conn.close(); alert("We are done!"); This isn't a terrific example because it doesn't include error handling. Bound Parameters Here are some examples demonstrating bound parameters. Assume we open an opened connection in the conn variable. let dataToInsert = [ ["foo", "bar"], ["biz", "baz"], {"yo", "ho"], ]; async function doInsert() { for (let data of dataToInsert) { await conn.executeCached("INSERT INTO myTabl...
DMD
Note that on Mac this step can take 30+ seconds. Desktop Firefox (Windows) Build Build with these options: ac_add_options --enable-dmd If building via try server, modify browser/config/mozconfigs/win32/common-opt. Also, add this line to build/mozconfig.common: MOZ_CRASHREPORTER_UPLOAD_FULL_SYMBOLS=1 Launch On a local build, use mach run --dmd; use --mode to choose the mode. On a build done by the try server, follow these instructions instead. Trigger Follow the Trigger instructions for Linux. Fennec In order to use DMD on Fennec you will need root access on the Android device. Instructions on how to root your device is outside the scope of this document. Build Build with these options: ac_add_options --enable-dmd Prep In order to prepare your device for running Fennec w...
...to the device and make it executable. Since you cannot mark files in /sdcard/ as executable, we will use /data/local/tmp for this purpose: adb push dmd_fennec /data/local/tmp adb shell cd /data/local/tmp chmod 755 dmd_fennec The final step is to make Android use the above wrapper script while launching Fennec, so that the environment variable is present when Fennec starts up. Assuming you have done a local build, the app identifier will be org.mozilla.fennec_$USERNAME ($USERNAME is your username on the host machine) and so we do this as shown below. If you are using a DMD-enabled try build, or build from other source, adjust the app identifier as necessary. adb shell su # You need root access for the setprop command to take effect setprop wrap.org.mozilla.fennec_$USERNAME "/data/local/t...
...ble::Run() (/home/njn/moz/mi2/xpcom/base/nsMemoryInfoDumper.cpp:58) 0x7f6860fefe03 } You can tell which memory reporter made the report by the name of the MallocSizeOf function near the top of the stack trace. In this case it was the cycle collector's reporter. By default, DMD does not record an allocation stack trace for most blocks, to make it run faster. The decision on whether to record is done probabilistically, and larger blocks are more likely to have an allocation stack trace recorded. All unreported blocks that lack an allocation stack trace will end up in a single record. For example: Unreported { 420,010 blocks in heap block record 2 of 5,495 29,203,408 bytes (27,777,288 requested / 1,426,120 slop) Individual block sizes: 2,048 x 3; 1,024 x 103; 512 x 147; 496 x 7; 480 x 3...
Gecko Profiler FAQ
stence. We have this hooked up for nsThreads, and as of very recently also for rayon threads (used in stylo). We have not attempted to register other threads with the profiler. Bug 1341811 suggests hooking platform thread spawning functions but nobody has looked at it yet. Profiling all nsThreads - how bad is the overhead? [mstange] I don't know. I think Julian Seward has done some measurements on this, I think. [ehsan] Try clicking the toolbar icon for the extension, expanding the Settings section, and enter the secret cheat code "," in the Threads field and click on "Apply (Restart Profiler)". This will capture all of the threads that the Gecko Profiler has been hooked to. This mode is usually recommended when you want to find a thread you wa...
...ile. However, the profiler add-on currently doesn't have a checkbox to enable this feature. Are the timer probes synchronized, or random/independent? (I'd guess they're independent). When profiling hundred(s) of threads at low intervals, does this distort the measurement or operation? (I.e. I want to profile all threads, not just Main plus a couple of others) We haven't done any measurements of how frequent sampling distorts measurement or operation. There is only one sampler thread. It runs a loop that works like this: Iterate over all threads. For each thread, suspend it, walk its stack, resume it. Sleep until the next sample is due. Then go to the previous step. I there an equivalent to ITIMER...
...o figure out how to write a micro-benchmark that reproduces the exact issue. It's better to start getting used to profiling and analyzing real pages more. :-) What's the best way to profile startup performance? Install the Gecko profiler add-on. Quit the browser. Start the browser with the environment variable MOZ_PROFILER_STARTUP=1 set. As soon as startup is done, collect a profile. What's the best way to do repeatable tests? ie: I want to measure perf of loading the same page with different stylo configurations. Probably by using Talos, especially if you want to measure and not profile. You can make your own Talos pageload test which has just the one page that you're interested in in its manifest. What ac...
NSS API Guidelines
This will help you understand existing NSS code. It should also help you understand how to write new code, and where to place it. ...
...ich flags a problem, adds its own error number to the stack. At the bottom of the stack is the fundamental error, for example: file not found, and on top is an error precisely relating to what you are doing. Note: Error stacks are vertical, and never horizontal. If multiple things go wrong simultaneously, and you want to report them all, use another mechanism. Errors, though not integers, are done as external constants, instead of preprocessor definitions. This is so any additional error doesn't trigger the entire tree to rebuild. Likewise, the external references to errors are made in the prototypes files, with the functions which can return them. Error stacks are thread-private. The usual semantic is that public routines clear the stack first, private routines don't. Usually, every pub...
...ng freed are opaque. Dup, Copy, and Reference Functions Functions that return a new reference or copy of a given object should have the form LAYER_DupDataType(). For instance, CERT_DupCertifiate() will remain the same, but PK11_ReferenceSlot() will become PK11_DupSlot(), and PK11_CloneContext() will become PK11_DupContext(). Search Functions There are several different kinds of searches done via the security library. The first is a search for exactly one object, meeting a given criteria. These types of searches include CERT_FindCertByDERCert(), PK11_FindAnyCertFromDERCert(), PK11_FindKeyByCert(), PK11_GetBestSlot(). These functions should all have the form LAYER_FindDataType[ByDataType](). The second kind of search, looks for all the objects that match a given criteria. These functi...
Hacking Tips
he above directory. The other being disable this check in "about:config", by temporarily switching "security.fileuri.strict_origin_policy" to false Note 2: The files can be very big and take a long time to load in the browser. Therefore it might be good to reduce the logged file. This will remove entries that took only a minor time (=entries that will only show up with les than 1px). This can be done with the reduce.py script in https://github.com/haytjes/tracelogger/tree/master/tools_v2. You need to download "engine.js", "reduce.py", "reduce.js", "reduce-tree.js" and "reduce-corrections.js". Running this tool is a matter of running "python reduce.py JS_SHELL /tmp/tl-data.json tl-reduced". Where JS_SHELL is a real shell. Using callgrind (JS shell) As SpiderMonkey just-in-time compiler are ...
... can be selected with the IONFLAGS environment variable, and compilation spew can be filtered with IONFILTER. IONFLAGS contains the names of each channel separated by commas. The logs channel produces 2 files in /tmp/, one (/tmp/ion.json) made to be used with iongraph (made by Sean Stangl) and another one (/tmp/ion.cfg) made to be used with c1visualizer. These tools will show the MIR & LIR steps done by IonMonkey during the compilation. If you would like to use iongraph, you must install Graphviz. Compilation logs and spew can be filtered with the IONFILTER environment variable which contains locations as output in other spew channels. Multiple locations can be separated with comma as a separator of locations. $ IONFILTER=pdfjs.js:16934 IONFLAGS=logs,scripts,osi,bailouts ./js --ion-offthrea...
...const libdir='$JS_SRC/jit-test/lib/'; const scriptdir='$JS_SRC/jit-test/tests/saved-stacks/'" -f $JS_SRC/jit-test/tests/saved-stacks/async.js (note that the above is an example; simply setting JS_SHELL and JS_SRC will not work). Or if this is an intermittent, run it in a loop capturing an rr log for every one until it fails: n=1; while rr ...same.as.above...; do echo passed $n; n=$(( $n + 1 )); done Wait until it hits a failure. Now you can run rr replay to replay that last (failed) run under gdb. rr with reftest To break on the write of a differing pixel: Find the X/Y of a pixel that differs Use 'run Z' where Z is the mark in the log for TEST-START. For example in '[rr 28496 607198]REFTEST TEST-START | file:///home/bgirard/mozilla-central/tree/image/test/reftest/bmp/bmpsuite/b/wrappe...
Garbage collection
ect) belongs to at most one compartment. (Some cells are shared across all compartments in a Zone.) An object may not hold a direct pointer to an object in another compartment. Instead, it must store a wrapper for the other object. This allows compartments to be used for security checks: objects in the same compartment have the same access requirements, so no checks are needed, but checks may be done when traversing cross-compartment wrappers. The engine may GC a single compartment without GCing the others. The engine can also GC a set of compartments without GCing the rest. Cross-compartment wrappers are used as roots for single- and multi-compartment GCs. Compartments are a fundamental cross-cutting concept in SpiderMonkey (see also Compartments), though anything related to memory is now...
...color terms). Say object A is black and contains a pointer field. Let object B be white. Now let the incremental slice stop, so the mutator resumes. If the mutator stores B into A, so that A contains a pointer to B, and deletes all existing pointers to B, then: B is live, because A is black and contains a pointer to B. B will not be marked, because B is only reachable through A and we are all done with A, because A is black. Thus, B is live but will be collected. The write barrier is a piece of code that runs just before a pointer store occurs and records just enough information to make sure that live objects don't get collected. The SpiderMonkey incremental write barrier SpiderMonkey uses a (relatively!) simple, common incremental write barrier called a snapshot-at-the-beginning allo...
...ct are overwritten. Thus, if whenever we're about to overwrite a pointer to an object we mark the object black first, then no objects can get 'lost'. Now consider allocations. A newly allocated object wasn't present at the beginning of the GC, so the snapshot-at-the-beginning barrier doesn't do it any good. But we do need to make sure the object doesn't get collected if it's live. This is easily done by simply marking new objects immediately upon allocation during an incremental GC, thus the name allocate-black. The SpiderMonkey incremental read barrier The textbook version of incremental GC has only a write barrier. SpiderMonkey also needs a read barrier for weak references (see Dictionary). This is because weak references have a similar problem as is solved by the incremental write barrie...
Handling Mozilla Security Bugs
up of module owners and peers, and that it may grow further over time. New members can be added to the Mozilla security bug group as follows: New people can apply to join the security bug group, or may be recruited by existing members. Applicants for membership must have someone currently in the security bug group who is willing to vouch for them and nominate them for membership. Nomination is done by the "voucher" sending e-mail to the security bug group private mailing list. The applicant's nomination for membership will then be considered for a period of a few days, during which members of the security bug group can speak out in favor of or against the applicant. At the end of this period, the security module owner will decide to accept the applicant or not, based on feedback and objec...
...rity bug group, the group members, bug reporter, and others associated with the bug will decide by consensus, either through comments on the bug or the group mailing list, whether an immediate warning to users is appropriate and how it should be worded. The goals of this warning are: To inform Mozilla users and testers of potential security risks in the versions they are using, and what can be done to mitigate those risks. To establish, for each bug, the amount of information a distributor can reveal immediately (before a fix is available) without putting other distributors and their customers at risk. A typical warning will mention the application or module affected, the affected versions, and a workaround (e.g., disabling JavaScript). If the group decides to publish a warning, the modu...
... this purpose). Mozilla distributors who wish to inform their users of the existence of a vulnerability may repost any information from the Known Vulnerabilities page to their own websites, mailing lists, release notes, etc., but should not disclose any additional information about the bug. The original reporter of a security bug may decide when that bug report will be made public. Disclosure is done by clearing the bug's "Security-Sensitive" flag, after which the bug will revert to being an ordinary bug. We believe that investing this power in the bug reporter simply acknowledges reality, as nothing prevents the person reporting a security bug from publicizing information about the bug by posting it to channels outside the context of the Mozilla project. By not doing so, and by instead choos...
Feed content access API
ed; includes functions that let you fetch the text as plain text or HTML. nsIScriptableUnescapeHTML A utility class that unescapes HTML strings. Example: Reading a feed from the Web It's actually quite easy to read and parse a feed. Use an XMLHttpRequest to load the feed, then pass its string to an nsIFeedProcessor to parse the feed. ...
...tch(e) { alert(e); } } The nsIFeedProcessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parseFromString() method. However, you could also parse it from a file using parseFromStream(), or directly from an URL using parseAsync(). The actual processing of the parsed feed is done by a method called handleResult() on the FeedTestResultListener object. That code looks like this: FeedTestResultListener.prototype = { handleResult: function(result) { var feed = result.doc; feed.QueryInterface(Components.interfaces.nsIFeed); // Open a new window var win = window.open("", "FeedTest_Window"); var doc = win.document.wrappedJSObj...
...To get the title of the feed, you look at the feed.title property. The title is an nsIFeedTextConstruct that can represent the text in various formats; we get its text...
Avoiding leaks in JavaScript XPCOM components
gs not to do Everybody writing, reviewing, or checking in JavaScript code to Mozilla CVS should understand why these things are bad. Don't store temporary objects permanently in global variables Storing temporary objects permanently in global variables will leak memory in garbage-collected languages. That it leaks in the XPCOM+JavaScript world isn't at all special. The most common way this is done in JavaScript is on implementations of observer interfaces like nsIObserver in JavaScript. If you implement nsIObserver in JavaScript and register that observer (without using weak references) with a service (for example, with the observer service bug 239833 or with the pref service bug 256822), the service will do exactly what you tell it to do: notify the observer you just created until you unr...
...nced by those variables are reachable from the function. To understand closures a little better before examining how they can cause leaks, consider the following example, in which there are two pairs of function objects, and each pair has an instance of the private_data variable: // This function returns an array containing two functions. function function_array() { // Once this function is done running, this variable is still // accessible to the functions created here. var private_data = 0; var result = new Array(); result[0] = function() { return (private_data += 1); } result[1] = function() { return (private_data *= 2); } return result; } // This function returns the string "Results: 1, 2, 4, 0, 5, 1, 10." function test() { var fns1 = function_array(); ...
.... But the browsers are themselves XBL bindings, and much of the memory associated with the page displayed in the tab is reachable from the JavaScript properties of the browser element. This means that without some workaround, all of the browsers will remain in memory until the parent window is closed. The workaround is simple: we have a destroy method on browser that tabbrowser can call when it's done with a browser. This destroy method assigns null to the problematic properties so that the large objects are no longer reachable from the wrapper of the browser element (which will still leak until the window containing the tabbrowser is closed, but it's a much smaller leak). Further reading Finding leaks in Mozilla - How to debug leaks when they do occur. ...
Introduction to XPCOM for the DOM
can have bad consequences. That is why each time a pointer to an interface is assigned the address of an object, we have to increase the reference count of that object by one. The function that does this is called "AddRef" and is defined in the nsISupports interface. When the pointer no longers holds the address of that object, it has to decrease the reference count of that object by one. ...
...In the second case, if we forget to Release the object, it will never delete itself, which will cause "memory leaks", i.e. the memory is never returned because we keep the object around even if we don't need it. ...
... nsCOMPtr<nsIFoo> ifooptr; GetInterfaceIFoo(getter_AddRefs(ifooptr)); ifooptr->FunctionOfnsIFoo(); The peculiar syntax, getter_AddRefs(pointer), is the nsCOMPtr counterpart to the usual "&" (address-of) C operator. It means that the Getter method will call the AddRef method for you. This is a contract between the caller, who says "I don't add a reference to this object because you have already done it", and the callee who says "I add a reference to this object, so don't do it!". If both the caller and the callee perform the AddRef, the object will be leaked, because one of the two references will never be released! Please note that all Getter functions have to AddRef the returned pointer. If you're just using the Getter function though, you don't need to worry about it. More about this in ...
Observer Notifications
gister for the topics using the nsIObserverService. Application startup These are the topics that you can observe on startup, in order of appearance. If your component requires access to the user profile, or any services which require access to the profile (preferences, bookmarks, and so on) then a common pattern is to register with the nsICategoryManager for the app-startup topic which can be done in the component's registration code, and then in that notification register with the observer service for the profile-after-change notification. See Receiving startup notifications for more information about how this works. Starting in Firefox 3.5 components can simply register for the profile-after-change notification in nsICategoryManager. Topic Description * Eve...
... only when a cookie is created due to the presence of Set-Cookie header in the response header of any network request. This notification will come only after the "http-on-examine-response" is fired, but it will not always appear. Download Manager These topics indicate that events related to the Download Manager have occurred. Topic Description download-manager-ui-done Called when the list of downloads in the Download Manager windows finishes updating. This can happen multiple times, such as when the window first opens, when multiple items are removed, and when entering private browsing mode. download-manager-remove-download Called when a download of the list is removed or all the list is cleared. The subject will be the download id wrapped in n...
...y process and cannot be opened. places-favicons-expired Sent when all favicons have been expired. places-init-complete The Places database has been successfully initialized. You should wait until this notification occurs before querying the places database. places-maintenance-finished Sent when maintenance of the Places database is complete; this is done periodically in the background to keep the Places database tidy. places-shutdown Sent when Places shuts down. If you are referencing instances of mozIStorageStatement referencing Places databases when this notification occurs, you should call their mozIStorageStatement.finalize() method places-sync-finished Sent when the Places database has been successfully flushe...
nsIMacDockSupport
nd "New Private Window". If permanent private browsing mode is enabled then the "New Private Window" menu item is hidden. This is created by using the dockMenu attribute of nsIMacDockSupport here: http://mxr.mozilla.org/mozilla-release/source/browser/base/content/browser.js#1562 This is seen here: If you were to copy and follow that example you would replace the default native menu. ...
...("menu_mac_dockmenu");66 let nativeMenu = Cc["@mozilla.org/widget/standalonenativemenu;1"].createInstance(Ci.nsIStandaloneNativeMenu); console.log('dockMenuElement:', dockMenuElement); nativeMenu.init(dockMenuElement); dockSupport.dockMenu = nativeMenu; This replaces the default menu with this one menuitem that says "Show Most Recent Window". Notice the activateApplication(true), if this is not done then Firefox will not be activated. The result of this code is shown below. Notice how the "New Window" and "New Private Window" menuitem's are missing. Therefore, if you would like to add or remove items to the menu it is recommended to manipulate the default menu item which is on the hidden window of Firefox. Note: The hidden window of Firefox (Services.appShel.hiddenDOMWindow) loads on browse...
...s are missing. Therefore, if you would like to add or remove items to the menu it is recommended to manipulate the default menu item which is on the hidden window of Firefox. Note: The hidden window of Firefox (Services.appShel.hiddenDOMWindow) loads on browser startup, so if you would like to access it on startup of the browser make sure to check and wait for the window to be loaded. This can be done by adding a event listenr for load of the hidden window. This is the recommended way to add to the native menu, just maniuplate the default menu DOM element. var macMenuItem = Services.appShell.hiddenDOMWindow.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macMenuItem.setAttribute('label', 'Show Most Recent Window'); macMenuItem.setAttribute...
nsIMsgFolder
d NotifyFolderEvent(in nsIAtom event); void ListDescendents(in nsISupportsArray descendents); void Shutdown(in boolean shutdownChildren); void setInVFEditSearchScope(in boolean aSearchThisFolder, in boolean aSetOnSubFolders); void copyDataToOutputStreamForAppend(in nsIInputStream aIStream, in long aLength, in nsIOutputStream outputStream); void copyDataDone(); void setJunkScoreForMessages(in nsISupportsArray aMessages, in ACString aJunkScore); void applyRetentionSettings(); boolean fetchMsgPreviewText([array, size_is (aNumKeys)] in nsMsgKey aKeysToFetch, in unsigned long aNumKeys, in boolean aLocalOnly, in nsIUrlListener aUrlListener); void addKeywordsToMessages(in nsISupportsArray aMessages, in ACString aKeywords...
...This is intended for new mail a...
...This is intended for new mail alerts, title tips on f...
nsITransactionListener
lse false. aMergeResult The nsresult returned after the merge attempt. didRedo() Called after a nsITransactionManager calls the nsITransaction.Redo() method of a transaction. void didRedo( in nsITransactionManager aManager, in nsITransaction aTransaction, in nsresult aRedoResult ); Parameters aManager The nsITransactionManager redoing the transaction. aTransaction The transaction being redone. ...
...aUndoResult The nsresult returned after undoing the transaction. willBeginBatch() Called before a nsITransactionManager begins a batch. boolean willBeginBatch( in nsITransactionManager aManager ); Parameters aManager The nsITransactionManager beginning a batch. Return value willDo() Called before a nsITransactionManager calls a transaction's nsITransaction.doTransaction() method. ...
...n at the top of the undo stack. aTransactionToMerge The transaction to merge. Return value willRedo() Called before a nsITransactionManager calls the nsITransaction.Redo() method of a transaction. boolean willRedo( in nsITransactionManager aManager, in nsITransaction aTransaction ); Parameters aManager The nsITransactionManager redoing the transaction. aTransaction The transaction being redone. Return value willUndo() Called before a nsITransactionManager calls the nsITransaction.Undo() method of a transaction. boolean willUndo( in nsITransactionManager aManager, in nsITransaction aTransaction ); Parameters aManager The nsITransactionManager undoing the transaction. aTransaction The transaction being undone. Return value See also nsITransaction nsITransactionList nsITransact...
nsIXULTemplateQueryProcessor
anslateRef(). The builder will then call compileQuery() for each query in the template to compile the queries. When results need to be generated, the builder will call generateResults(). The initializeForBuilding(), compileQuery() and addBinding() methods may not be called after generateResults() has been called until the builder indicates that the generated output is being removed by calling the done() method. Currently, the datasource supplied to the methods will always be an nsIRDFDataSource or a DOM node, and will always be the same one in between calls to initializeForBuilding() and done(). Method overview void addBinding(in nsIDOMNode aRuleNode, in nsIAtom aVar, in nsIAtom aRef, in AString aExpr); PRInt32 compareResults(in nsIXULTemplateResult aLeft, in nsIXULTemplateResult aRight, ...
...one(). ...
...nt to indicate what variable is expected to contain the results. nsISupports compileQuery( in nsIXULTemplateBuilder aBuilder, in nsIDOMNode aQuery, in nsIAtom aRefVariable, in nsIAtom aMemberVariable ); Parameters aBuilder The template builder. aQuery <query> node to compile. aRefVariable The reference variable. aMemberVariable The member variable. Return value A compiled query object. done() Called when the template builder is being destroyed so that the query processor can clean up any state. The query processor should remove as much state as possible, such as results or references to the builder. This method will also be called when the template is going to be rebuilt. void done(); Parameters None. generateResults() Generate the results of a query and return them in an enumerato...
Working with data
s to browserconsole: `CData { length: 5 }` console.log(CStr_nullTerminated.toString()); // outputs to browser console: `"ctypes.char16_t.array(5)(["r", "a", "w", "r", "\x00"])"` The console.log shows that the length is greater then the length of "rawr" which is 4, doing a .toString on it shows there is a null terminator of \x00 on the end. ...
...he Int64 and UInt64 objects don't provide any methods for performing arithmetic, which means you'll have to do it yourself by pulling out the high and low 32-bit portions and doing math on them, then joining them back together if necessary to get the complete result. You'll also have to handle carry from the low to high word and back as appropriate. For example, adding two 64-bit integers can be done like this. This example is for unsigned numbers, but a similar approach can be taken for signed values. function add(a, b) { const MAX_INT = Math.pow(2, 32); var alo = ctypes.UInt64.lo(a); var ahi = ctypes.UInt64.hi(a); var blo = ctypes.UInt64.lo(b); var bhi = ctypes.UInt64.hi(b); var lo = alo + blo; var hi = 0; if (lo >= MAX_UINT) { hi = lo - MAX_UINT; lo -= MAX_UINT;...
...join() will throw an exception if the resulting number exceeds 64 bits in length. ...
Streams - Plugins
ata. The browser stores private data in stream->ndata; this value should not be changed by the plug-in. NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPError reason); The instance parameter is the current plug-in instance; the stream parameter specifies the stream to be deleted. The reason parameter specifies why the stream was destroyed. It can have one of these values: NPRES_DONE (Most common): Normal completion; all data was sent to the instance. NPRES_USER_BREAK: The user canceled the stream directly by clicking the Stop button or indirectly by some action, such as by deleting the instance or initiating higher-priority network operations. NPRES_NETWORK_ERR: The stream failed because of problems with the network, disk I/O error, lack of memory, or some other problem. ...
...ams the plug-in creates with NPN_NewStream or streams created by the browser with NPP_NewStream. NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPError reason); The instance parameter is the current plug-in; the stream parameter specifies the stream, created by either the browser or the plug-in. The reason parameter represents the reason the stream was stopped, as follows: NPRES_DONE (most common): The stream completed normally; the plug-in sent all data to the browser. NPRES_USER_BREAK: The plug-in terminated the stream because of a user request. NPRES_NETWORK_ERR: The stream failed because of network problems. For the complete list of codes, see "Result Codes." For an example that demonstrates using this function with NPN_NewStream and NPN_Write, see "Example of Sendin...
...e from my plug-in!</title></head><body><p><strong>This is a message from my plug-in!</strong></p></body>/html>"; int32 myLength = strlen(myData) + 1; /* Create the stream. */ err = NPN_NewStream(instance, "text/html", "_blank", &stream); /* Push data into the stream. */ err = NPN_Write(instance, stream, myLength, myData); /* Delete the stream. */ err = NPN_DestroyStream(instance, stream, NPRES_DONE); Your plug-in can create another instance of itself by specifying its own MIME type and a new target name in a call to NPN_NewStream. << PreviousNext >> ...
Using Fetch - Web APIs
you to handle these complications. The following example shows one way to do this by creating a line iterator (for simplicity, it assumes the text is UTF-8, and doesn't handle fetch errors). ...
...le these complications. The following example shows one way to do this by creating a line iterator (for simplicity, it assumes the text is UTF-8, and doesn't handle fetch errors). ...
...L) { const utf8Decoder = new TextDecoder('utf-8'); const response = await fetch(fileURL); const reader = response.body.getReader(); let { value: chunk, done: readerDone } = await reader.read(); chunk = chunk ? utf8Decoder.decode(chunk) : ''; const re = /\n|\r|\r\n/gm; let startIndex = 0; let result; for (;;) { let result = re.exec(chunk); if (!result) { if (readerDone) { break; } let remainder = chunk.substr(startIndex); ({ value: chunk, done: readerDone } = await reader.read()); chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : ''); startIndex = re.lastIndex = 0; continue; } yield chunk.substring(startIndex, result.index); startIndex = re.lastIndex; } if (startIndex < chunk.length) { // la...
IDBRequest - Web APIs
The IDBRequest interface of the IndexedDB API provides access to results of asynchronous requests to databases and database objects using event handler attributes. Each reading and writing operation on a database is done using a request. The request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the IDBRequest instance. All asynchronous operations immediately return an IDBRequest instance. ...
...ect does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the IDBRequest instance. All asynchronous operations immediately return an IDBRequest instance. Each request has a readyState that is set to the 'pending' state; this changes to 'done' when the request is completed or fails. When the state is set to done, every request returns a result and an error, and an event is fired on the request. When the state is still pending, any attempt to access the result or error raises an InvalidStateError exception. In plain words, all asynchronous methods return a request object. If the request has been completed successfully, the result is m...
...e the request failed and the result is not available, an InvalidStateError exception is thrown. IDBRequest.source Read only The source of the request, such as an IDBIndex or an IDBObjectStore. If no source exists (such as when calling IDBFactory.open), it returns null. IDBRequest.readyState Read only The state of the request. Every request starts in the pending state. The state changes to done when the request completes successfully or when an error occurs. IDBRequest.transaction Read only The transaction for the request. This property can be null for certain requests, for example those returned from IDBFactory.open unless an upgrade is needed. (You're just connecting to a database, so there is no transaction to return). Methods No methods, but inherits methods from EventTarget. ...
PaymentRequest.show() - Web APIs
, across all documents. Once one PaymentRequest's show() method has been called, any other call to show() will by rejected with an AbortError until the returned promise has been concluded, either by being fulfilled with a PaymentResponse indicating the results of the payment request, or by being rejected with an error. Note: In reality, despite the fact that the specification says this can't be done, some browsers, including Firefox, support multiple active payment requests at a time. If your architecture doesn't necessarily have all of the data ready to go at the moment it instantiates the payment interface by calling show(), specify the detailsPromise parameter, providing a Promise that is fulfilled once the data is ready. If this is provided, show() will not allow the user to interact w...
...ailsPromise parameter, providing a Promise that is fulfilled once the data is ready. If this is provided, show() will not allow the user to interact with the payment interface until the promise is fulfilled, so that data can be updated prior to the user engaging with the payment process. Processing the result and, if necessary, calling PaymentResponse.retry() to retry a failed payment can all be done either asynchronously or synchronously, depending on your needs. For the best user experience, asynchronous solutions are typically the best way to go. Most examples on MDN and elsewhere use async/await to wait asynchronously while results are validated and so forth. Syntax paymentPromise = paymentRequest.show(detailsPromise); Parameters detailsPromise Optional An optional Promise that yo...
...complete accordingly. If any fields have unacceptable values, or if an exception is thrown by the previous code, complete() is called with the string "fail", which indicates that the payment process is complete and failed. Instead of immediately failing, you could choose to call retry() on the response object to ask the user agent to try to process the payment again; this should usually only be done after the user has made any needed corrections to the order. Starting the payment process, in the end, is as simple as calling the processPayment() method. then/catch syntax You can also use the older promise-based approach to work with payments, using the then() and catch() functions on the promise returned by show(): function processsPayment() { const payRequest = new PaymentRequest(metho...
Using Pointer Events - Web APIs
olor; ctx.stroke(); ongoingTouches.splice(idx, 1, copyTouch(evt)); // swap in the new touch record log("."); } else { log("can't figure out which touch to continue: idx = " + idx); } } This function looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's PointerEvent.pointerId property. This property is a unique integer for each pointer event, and remains consistent for each event during the duration of each finger's contact with the surface. This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together. After d...
...The result is that we stop tracking that touch point. Handling cancel...
...g that touch point. Handling canceled touches If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the pointercancel event is sent, and we call the handleCancel() function below. function handleCancel(evt) { log("pointercancel: id = " + evt.pointerId); var idx = ongoingTouchIndexById(evt.pointerId); ongoingTouches.splice(idx, 1); // remove it; we're done } Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment. Convenience functions This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear. Selecting a color for each touch In order to make each touch's drawing look different, the colorForTouch() fun...
ReadableStream.getReader() - Web APIs
sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. ...
... read, at which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. ...
...e UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = value; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(...
ReadableStream.tee() - Web APIs
he UI. See Simple tee example for the full code. ...
... { const teedOff = stream.tee(); 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 already given you all its data. ...
...ion 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 already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list.appendChild(listItem); // Read some more, an...
ReadableStream - Web APIs
eam HTML fragments fetched from another resource to the browser. It demonstrates the usage of a ReadableStream in combination with a Uint8Array. ...
...strates the usage of a ReadableStream in combination with a Uint8Array. ...
...("https://www.example.org/").then((response) => { const reader = response.body.getReader(); const stream = new ReadableStream({ start(controller) { // The following function handles each data chunk function push() { // "done" is a Boolean and value a "Uint8Array" reader.read().then(({ done, value }) => { // Is there no more data to read? ...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. ...
... read, at which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. ...
...e UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild...
ReadableStreamDefaultReader - Web APIs
eam HTML fragments fetched from another resource to the browser. It demonstrates the usage of a ReadableStream in combination with a Uint8Array. ...
... the usage of a ReadableStream in combination with a Uint8Array. ...
...://www.example.org/").then((response) => { const reader = response.body.getReader(); const stream = new ReadableStream({ start(controller) { // The following function handles each data chunk function push() { // "done" is a Boolean and value a "Uint8Array" return reader.read().then(({ done, value }) => { // Is there no more data to read? ...
Using the Screen Capture API - Web APIs
ace is one which is in part or completely obscured, either by being overlapped by another object to some extent, or by being entirely hidden or offscreen. How these are handled by the Screen Capture API varies. Generally, the browser will provide an image which obscures the hidden portion of the logical display surface in some way, such as by blurring or replacing with a color or pattern. This is done for security reasons, as the content that cannot be seen by the user may contain data which they do not want to share. A user agent might allow the capture of the entire content of an obscured window after gaining permission from the user to do so. In this case, the user agent may include the obscured content, either by getting the current contents of the hidden portion of the window or by prese...
...am to the log box for educational purposes. If any of that fails, the catch() clause outputs an error message to the log box. Stopping display capture The stopCapture() method is called when the "Stop Capture" button is clicked. It stops the stream by getting its track list using MediaStream.getTracks(), then calling each track's {domxref("MediaStreamTrack.stop, "stop()")}} method. Once that's done, srcObject is set to null to make sure it's understood by anyone interested that there's no stream connected. function stopCapture(evt) { let tracks = videoElem.srcObject.getTracks(); tracks.forEach(track => track.stop()); videoElem.srcObject = null; } Dumping configuration information For informational purposes, the startCapture() method shown above calls a method named dumpOptions(), ...
...color: red; } .warn { color: orange; } .info { color: darkgreen; } Result The final product looks like this. If your browser supports Screen Capture API, clicking "Start Capture" will present the user agent's interface for selecting a screen, window, or tab to share. Security In order to function when Feature Policy is enabled, you will need the display-capture permission. This can be done using the Feature-Policy HTTP header or--if you're using the Screen Capture API in an <iframe>, the <iframe> element's allow attribute. For example, this line in the HTTP headers will enable Screen Capture API for the document and any embedded <iframe> elements that are loaded from the same origin: Feature-Policy: display-capture 'self' If you're performing screen capture within an <iframe>, y...
Using Service Workers - Web APIs
what they look like in image-list.js). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. If you just passed in the url, and then tried to access the other items in the JSON separately when the for() loop is being iterated through later on, it wouldn't work, as the promise wouldn't resolve at the same time as the iterations are being done (that is a synchronous process.) We actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 31-34). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object. To access the ...
... section later on.) Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers. Note: IndexedDB can be used inside a service worker for data storage if you require it. Custom responses to requests Now you've got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the fetch event. A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.) You can attach a fetch event listener to the service worker, ...
...simply responding with the resource whose url matches that of the network request, in each case: self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request) ); }); caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests. Let's look at a few other options we have when defining our magic (see our Fetch API documentation for more information about Request and Response objects.) The Response() constructor allows you to create a custom response. In this case, we are just returning a simple text string: new Response('Hello from your friendly neigh...
Touch events - Web APIs
yTouch(touches[i])); // swap in the new touch record console.log("."); } else { console.log("can't figure out which touch to continue"); } } } This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's Touch.identifier property. This property is a unique integer for each touch and remains consistent for each event during the duration of each finger's contact with the surface. This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together. After drawing the line...
...The result is that we stop tracking that touchpoint.
... touch otherwise needs to be canceled, the touchcancel event is sent, and we call the handleCancel() function below. function handleCancel(evt) { evt.preventDefault(); console.log("touchcancel."); var touches = evt.changedTouches; for (var i = 0; i < touches.length; i++) { var idx = ongoingTouchIndexById(touches[i].identifier); ongoingTouches.splice(idx, 1); // remove it; we're done } } Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment. Convenience functions This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear. Selecting a color for each touch To make each touch's drawing look different, the colorForTouch() function...
WebGL best practices - Web APIs
owser). getError(): causes a flush + round-trip to fetch errors from the GPU process). For example, within Firefox, the only time glGetError is checked is after allocations (bufferData, *texImage*, texStorage*) to pick up any GL_OUT_OF_MEMORY errors. getShader/ProgramParameter(), getShader/ProgramInfoLog(), other gets on shaders/programs: flush + shader compile + round-trip, if not done after shader compilation is complete. (See also parallel shader compilation below.) get*Parameter() in general: possible flush + round-trip. In some cases, these will be cached to avoid the round-trip, but try to avoid relying on this. checkFramebufferStatus(): possible flush + round-trip. getBufferSubData(): usual finish + round-trip. (This is okay for READ buffers in conjuncti...
... your WebGL shaders; although some early examples used this, it's not necessary, since this condition is always true in WebGL shaders. Prefer doing more work in vertex (not fragment) shaders Do as much as you can in the vertex shader, rather than in the fragment shader. This is because per draw call, fragment shaders generally run many more times than vertex shaders. Any calculation that can be done on the vertices and then just interpolated among fragments (via varyings) is a performance boon. (The interpolation of varyings is very cheap, and is done automatically for you through the fixed functionality rasterization phase of the graphics pipeline) For example, a simple animation of a textured surface can be achieved through a time-dependent transformation of texture coordinates. (The simp...
...texture in GPU memory until the first time the texture is drawn. Further, some drivers might unconditionally allocate the whole mip-chain (+30% memory!) even if you only want a single level. So, prefer texStorage+texSubImage for textures in WebGL 2 invalidateFramebuffer Storing data that you won't use again can have high cost, particularly on tiled-rendering GPUs common on mobile. When you're done with the contents of a framebuffer attachment, use invalidateFramebuffer to discard the data, instead of leaving the driver to waste time storing the data for later use. DEPTH/STENCIL and/or multisampled attachments in particular are great candidates for invalidateFramebuffer. Non-blocking async data download/readback The approach in WebGL 2 is analogous to the approach in OpenGL: https://jdash...
Signaling and video calling - Web APIs
ssages of unknown types to any specific user, letting them send signaling messages back and forth as desired. That's all we need to change on the server side of the equation. Now let's consider the signaling protocol we will implement. Designing the signaling protocol Now that we've built a mechanism for exchanging messages, we need a protocol defining how those messages will look. This can be done in a number of ways; what's demonstrated here is just one possible way to structure signaling messages. This example's server uses stringified JSON objects to communicate with its clients. This means our signaling messages will be in JSON format, with contents which specify what kind of messages they are as well as any additional information needed in order to handle the messages properly. Exch...
...ks like this: Each side sends candidates to the other as it receives them from their local ICE layer; there is no taking turns or batching of candidates. As soon as the two peers agree upon one candidate that they can both use to exchange the media, media begins to flow. Each peer continues to send candidates until it runs out of options, even after the media has already begun to flow. This is done in hopes of identifying even better options than the one initially selected. If conditions change--for example the network connection deteriorates--one or both peers might suggest switching to a lower-bandwidth media resolution, or to an alternative codec. This triggers a new exchange of candidates, after which a another media format and/or codec change may take place. You can learn more about t...
... media inputs to a specific device or set of devices by calling navigator.mediaDevices.enumerateDevices() to get a list of devices, filtering the resulting list based on our desired criteria, then using the selected devices' deviceId values in the deviceId field of the the mediaConstraints object passed into getUserMedia(). In practice, this is rarely if ever necessary, since most of that work is done for you by getUserMedia(). We attach the incoming stream to the local preview <video> element by setting the element's srcObject property. Since the element is configured to automatically play incoming video, the stream begins playing in our local preview box. We then iterate over the tracks in the stream, calling addTrack() to add each track to the RTCPeerConnection. Even though the connectio...
Lighting a WebXR setting - Web APIs
l as potentially affect the coloration of the light reflected off of it. Realism in augmented reality Augmented reality introduces an additional level of complexity to lighting your objects, since your virtual objects need to exist within a physical world that has its own light sources. As such, you should try to match your lighting to the real world's light sources as much as possible. This is done using a technique known as Lighting estimation. Conversely, you should try to avoid having virtual objects that are themselves light sources, unless you're prepared to create code that can cast that lighting onto the real world setting. Casting light onto real-world objects is essentially the opposite of casting shadows. It can be done, but is not as widely implemented. Lighting estimation Lig...
...rmine a spatial relationship between the devices; this could in theory indicate that the devices are in the same general area, for example. How browsers mitigate these issues In order to help mitigate these risks, browsers are required by the WebXR Lighting Estimation API specification to report lighting information that is fudged somewhat from the true value. There are many ways this could be done. Spherical harmonics precision Browsers can mitigate the risk of fingerprinting by reducing the precision of spherical harmonics. When performing real-time rendering--as is the case with any virtual or augmented reality application--spherical harmonic lighting is used to simplify and accelerate the process of generating highly realistic shadows and shading. By altering the accuracy of these fun...
...he location can no longer be accurately estimated using this technique. Temporal and spatial filtering Consider an attack that uses a building's automated lighting system to flash the lights on and off quickly in a known pattern. Without proper precautions, the lighting estimation data could be used to detect this pattern and thus determine that a user is in a particular location. This could be done remotely, or it could be performed by an attacker who's located in the same room but wants to determine if the other person is also in the same room. Another scenario in which lighting estimation can be used to obtain information about the user without permission: if the light sensor is close enough to the user's display to detect lighting changes caused by the contents of the display, an algori...
Movement, orientation, and motion: A WebXR example - Web APIs
on.disabled = false; }) .catch(() => { xrButton.disabled = true; }); } } The label of the button gets adjusted in the code that handles actuallys ttarting and stopping the WebXR session; we'll see that below. The WebXR session is toggled on and off by the handler for click events on the button, whose label is appropriately set to either "Enter WebXR" or "Exit WebXR". This is done by the onXRButtonClick() event handler. 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 already have a XRSession object representing an ongoing WebXR sessio...
...nimationFrameRequestID); animationFrameRequestID = 0; } xrSession = null; } We can also call sessionEnded() directly if we wish to programmatically end the WebXR session. In either case, the label of the button is updated to indicate that a click will start a session, and then, if there is a pending request for an animation frame, we cancel it by calling cancelAnimationFrame Once that's done, the value of xrSession is changed to NULL to indicate that we're done with the session. Implementing the controls Now let's take a look at the code that handles turning keyboard and mouse events into something usable for controlling an avatar in a WebXR scenario. Moving using the keyboard In order to allow the user to move through the 3D world even if they don't have a WebXR device with the ...
... ...
Starting up and shutting down a WebXR session - Web APIs
y requestAnimationFrame(). First, a handler for the end event is set up. Then the rendering canvas is obtained and a reference to its WebGL context is retrieved, specifying the xrCompatible option when calling getContext(). Next, any data and setup needed for the WebGL renderer is performed before then configuring WebGL to use the framebuffer of the WebGL context as its own framebuffer. This is done using the XRSession method updateRenderState() to set the render state's baseLayer to a newly-created XRWebGLLayer encapsulating the WebGL context. Preparing to render the scene At this point, the XRSession itself has been fully configured, so we can begin rendering. First, we need a reference space within which coordinates for the world will be stated. We can get the initial reference space fo...
...(such as if the user turns off their XR device), because the user has clicked a button to end the session, or some other situation as appropriate for your application. Here we discuss both how to request a shutdown of the WebXR session and how to detect when the session has ended, whether by your request or otherwise. ...
...That way, you handle the cleanup regardless of whether the shutdown was automatically or manually triggered. ...
Using Web Workers - Web APIs
be executed. Previously executed code (including code deferred using window.setTimeout()) will still be functional though. Function declarations after the importScripts() method are also kept, since these are always evaluated before the rest of the code. Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed. Shared workers A shared worker is accessible by multiple scripts -- even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our Basic shared worker example (run shared worker): This is very similar to the basic dedicated...
... The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start() method before any messages can be posted. Calling start() is only needed if the message event is wired up via the addEventListener() method. Note: When using the start() method to open the port connection, it needs to be ca...
...d assets reside on the server. They will also allow access to push notifications and background sync APIs. Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to js-ctypes in your worker. See ChromeWorker for more details. Audio Worklet provide the ability for direct scripted audio processing to be done in a worklet (a lightweight version of worker) context. Functions and interfaces available in workers You can use most standard JavaScript features inside a web worker, including: Navigator XMLHttpRequest Array, Date, Math, and String WindowTimers.setTimeout and WindowTimers.setInterval The main thing you can't do in a Worker is directly affect the parent page. This includes manipulati...
Window.pageYOffset - Web APIs
d at the top edge of the window's content area. Since this property is an alias for Window.scrollY, see that article for additional details on this value and its use. Example var contentHTML = ` <h2 id="introduction">Introduction</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean volutpat vitae felis non dictum. Ut auctor eros tortor, vel elementum arcu rhoncus nec. Donec non laoreet massa. Donec pretium nisi et condimentum convallis. Nullam dictum molestie finibus. Nullam vitae lorem non augue mattis cursus.</p> <p>Maecenas nec tortor tincidunt, sollicitudin mi eget, fermentum turpis. Vestibulum ac ante et libero efficitur faucibus id eget ex. Pellentesque tempor pharetra tincidunt. Suspendisse potenti. Nulla vulputate nunc sit amet hendrerit faucibus. Nullam ...
...tesque justo augue, placerat non leo sit amet, laoreet fringilla arcu.</p> <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin in gravida libero. Vivamus placerat, lacus eget condimentum sagittis, enim nunc bibendum nisi, quis varius erat felis sit amet risus.</p> <p>Sed non finibus ligula. Fusce a magna auctor, molestie nibh eget, sodales felis. Donec imperdiet facilisis mi ut aliquam. Etiam sodales suscipit urna, eget hendrerit neque elementum a. Vivamus fringilla sodales est ut ultricies. Nulla convallis congue maximus. Nullam consectetur felis vitae ultricies accumsan. Mauris at aliquam felis. Mauris efficitur tellus massa, id ullamcorper ipsum fermentum eu. Aenean mollis dignissim ultrices. Nunc gravida, sem sit amet lobortis iaculis, dol...
...ium, viverra neque nec, facilisis risus. Duis condimentum sapien non felis cursus blandit. Integer euismod lectus a ipsum pellentesque lacinia.</p> `; document.getElementById("frame").contentDocument .body.innerHTML = contentHTML; In this example, an <iframe> is created and filled with content, then a specific element within the document is scrolled into view in the frame. Once that's done, the vertical scroll position is checked by looking at the value of pageYOffset in the frame's contentWindow. HTML The HTML is extremely simple and has just two elements: an <iframe> that contains the document we're going to scroll, and a <div> into which we'll output the value of pageYOffset when we've finished the scroll. <iframe id="frame"> </iframe> <div id="info"> </div> JavaScript var...
HTML in XMLHttpRequest - Web APIs
to detect HTML support, a test HTML file is needed on the server. ...
...amp;&<</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.onreadystatechange = 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(); } catch (e) { window.setTimeout(function() { if (...
... { 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(); } catch (e) { window.setTimeout(function() { if (!done) { done = true; callback(false); } }, 0); } } The argument callback is a function that will be called asynchronously with true as the only argument if HTML parsing is supported and false as the only argument if HTML parsing is not supported. View on JSFiddle Character encoding If the character encoding is declared in the HTTP Content-Type header, that character en...
Using CSS animations - CSS: Cascading Style Sheets
animations running in tabs that aren't currently visible. Configuring the animation To create a CSS animation sequence, you style the element you want to animate with the animation property or its sub-properties. This lets you configure the timing, duration, and other details of how the animation sequence should progress. This does not configure the actual appearance of the animation, which is done using the @keyframes at-rule as described in Defining the animation sequence using keyframes below. The sub-properties of the animation property are: animation-name Specifies the name of the @keyframes at-rule describing the animation's keyframes. animation-duration Configures the length of time that an animation should take to complete one cycle. animation-timing-function Configures the...
... the sequence or reset to the start point and repeat itself. animation-fill-mode Configures what values are applied by the animation before and after it is executing. animation-play-state Lets you pause and resume the animation sequence. Defining the animation sequence using keyframes Once you've configured the animation's timing, you need to define the appearance of the animation. This is done by establishing two or more keyframes using the @keyframes at-rule. Each keyframe describes how the animated element should render at a given time during the animation sequence. Since the timing of the animation is defined in the CSS style that configures the animation, keyframes use a <percentage> to indicate the time during the animation sequence at which they take place. 0% indicates the firs...
...niteration": l.innerHTML = "New loop started at time " + event.elapsedTime; break; } document.getElementById("output").appendChild(l); } This code, too, is very simple. It simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we're using to log these events. The output, when all is said and done, looks something like this: Started: elapsed time is 0 New loop started at time 3.01200008392334 New loop started at time 6.00600004196167 Ended: elapsed time is 9.234000205993652 Note that the times are very close to, but not exactly, those expected given the timing established when the animation was configured. Note also that after the final iteration of the animation, the animationiter...
Variable fonts guide - CSS: Cascading Style Sheets
y reflect the typeface design and avoid differences between browsers and how they may or may not synthesize the different styles, it's more accurate to load the specific font files where needed when using a non-variable font. You may also find that some variable fonts come split into two files: one for uprights and all their variations, and one containing the italic variations. This is sometimes done to reduce the overall file size in cases where the italics aren't needed or used. In all cases, it is still possible to link them with a common font-family name so you can call them using the same font-family and appropriate font-style. Introducing the 'variation axis' The heart of the new variable fonts format is the concept of an axis of variation describing the allowable range of that partic...
...racters would have an overall thicker stroke, and perhaps other small modifications to ensure that it would reproduce and be readable at a physically smaller size. Conversely, when a much larger size was being used (like 48 or 60px), there might be much greater variation in thick and thin stroke weights, showing the typeface design more in line with the original intent. While this was originally done to compensate for the ink and paper printing process (very thin lines at small sizes often didn't print, giving the letterforms a broken appearance), it translates well to digital displays when compensating for screen quality and physical size rendering. Optical size values are generally intended to be automatically applied corresponding to font-size, but can also be manipulated using the lower-...
...ues. Custom axes Custom axes are just that: they can be any axis of design variation that the typeface designer imagines. There may be some that become fairly common -- or even become registered -- but only time will tell. Grade Grade may become one of the more common custom axes as it has a known history in typeface design. The practice of designing different grades of a typeface was often done in reaction to intended use and printing technique. The term 'grade' refers to the relative weight or density of the typeface design, but differs from traditional 'weight' in that the physical space the text occupies does not change, so changing the text grade doesn't change the overall layout of the text or elements around it. This makes grade a useful axis of variation as it can be varied or an...
Adding captions and subtitles to HTML5 video - Developer guides
racks[i].label)); } videoContainer.appendChild(subtitlesMenu); } This code creates a documentFragment, which is used to hold an unordered list containing our subtitles menu. First of all an option is added to allow the user to switch all subtitles off, and then buttons are added for each text track, reading the language and label from each one. ...
...tTracks[i].mode = 'hidden'; } } subtitlesMenu.style.display = 'none'; }); subtitleMenuButtons.push(button); return listItem; } This function builds the required <li> and <button> elements, and returns them so they can be added to the subtitles menu list. It also sets up the required event listeners on the button to toggle the relevant subtitle set on or off. This is done by simply setting the required subtlte's mode attribute to showing, and setting the others to hidden. Once the menu is built, it is then inserted into the DOM at the bottom of the videoContainer. Initially the menu is hidden by default, so an event listener needs to be added to our subtitles button to toggle it: subtitles.addEventListener('click', function(e) { if (subtitlesMenu) { ...
...ood, although some browsers differ slightly in their implementation. Internet Explorer Internet Explorer 10+ subtitles are enabled by default, and the default controls contain a button and a menu that offers the same functionality as the menu we just built. The default attribute is also supported. Note: IE will completely ignore WebVTT files unless you define the MIME type. This can easily be done by adding an .htaccess file to an appropriate directory that contains AddType text/vtt .vtt. Safari Safari 6.1+ has similar support to Internet Explorer 10+, displaying a menu with the different available options, with the addition of an "Auto" option, which allows the browser to choose. Chrome and Opera These browsers have similar implementations again: subtitles are enabled by default and ...
Introduction to HTML5 - Developer guides
ter into standards mode, which means that they'll interpret the long-established parts of HTML in an HTML5-compliant way while ignoring the new features of HTML5 they don't support. This is much simpler than the former doctypes, and shorter, making it easier to remember and reducing the amount of bytes that must be downloaded. Declaring the character set with the <meta charset> The first thing done on a page is usually indicating the character set that is used. In previous versions of HTML, it was done using a very complex <meta> element. Now, it is very simple: <meta charset="UTF-8"> Place this right after your <head>, as some browsers restart the parsing of an HTML document if the declared character set is different from what they had anticipated. Also, if you are not currently using UT...
...restart the parsing of an HTML document if the declared character set is different from what they had anticipated. Also, if you are not currently using UTF-8, it's recommended that you switch to it in your web pages, as it simplifies character handling in documents using different scripts. Note that HTML5 restricts character sets to those compatible with ASCII and using at least 8 bits. This was done to tighten security and prevent some types of attacks. Using the new HTML5 parser The parsing rules of HTML5, which analyze the meaning of mark-up, have been more precisely defined in HTML5. Until the introduction of HTML5, only the meaning of valid mark-up was defined, meaning that as soon as one small error was made in the mark-up (most websites have at least one), the behavior was undefined.
... ...
Content negotiation - HTTP
of negotiating a specific kind of resource. The 300 (Multiple Choices) or 406 (Not Acceptable) HTTP response codes by the server (agent-driven negotiation or reactive negotiation), that are used as fallback mechanisms. Over the years, other content negotiation proposals, like transparent content negotiation and the Alternates header, have been proposed. They failed to get traction and got abandoned. Server-driven content negotiation In server-driven content negotiation, or proactive content negotiation, the browser (or any other kind of user-agent) sends several HTTP headers along with the URL. These headers describe the preferred choice of the user. The server uses them as hints and an internal algorithm chooses the best content to serve to the client. The algorithm is server-specific a...
...et to a different value for each locale for the browser, like ISO-8859-1,utf-8;q=0.7,*;q=0.7 for a Western European locale. With UTF-8 now being well-supported, being the preferred way of encoding characters, and to guarantee better privacy through less configuration-based entropy, browsers omit the Accept-Charset header: Internet Explorer 8, Safari 5, Opera 11, Firefox 10 and Chrome 27 have abandoned this header. The Accept-CH-Lifetime header This is part of an experimental technology called Client Hints and is only available in Chrome 61 or later. The Accept-CH-Lifetime header is used with the Device-Memory value of the Accept-CH header and indicates the amount of time the device should opt-in to sharing the amount of device memory with the server. The value is given in miliseconds and...
...sly, the wildcard '*' prevents caching from occurring, as the cache cannot know what element is behind it. Agent-driven negotiation Server-driven negotiation suffers from a few downsides: it doesn't scale well. There is one header per feature used in the negotiation. If you want to use screen size, resolution or other dimensions, a new HTTP header must be created. Sending of the headers must be done on every request. This is not too problematic with few headers, but with the eventual multiplications of them, the message size would lead to a decrease in performance. The more precise headers are sent, the more entropy is sent, allowing for more HTTP fingerprinting and corresponding privacy concern. From the beginnings of HTTP, the protocol allowed another negotiation type: agent-driven negoti...
Intl.Collator.supportedLocalesOf() - JavaScript
the runtime's default locale. Description Returns an array with a subset of the language tags provided in locales. The language tags returned are those for which the runtime supports a locale in collation that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. ...
...anguage tags provided in locales. The language tags returned are those for which the runtime supports a locale in collation that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. ...
...supports a locale in collation that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. Examples Using supportedLocalesOf Assuming a runtime that supports Indonesian and German but not Balinese in collation, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is not used with Indonesian and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well. var locales = ['ban', 'id-u-co-pinyin', 'de-ID']; var options = { locale...
Intl.NumberFormat.supportedLocalesOf() - JavaScript
time's default locale. Description Returns an array with a subset of the language tags provided in locales. The language tags returned are those for which the runtime supports a locale in number formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. ...
...vided in locales. The language tags returned are those for which the runtime supports a locale in number formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. ...
... matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. Examples Using supportedLocalesOf Assuming a runtime that supports Indonesian and German but not Balinese in number formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to number formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well. var locales = ['ban', 'id-u-co-pinyin', 'de-ID']; var options = { local...
Intl.PluralRules.supportedLocalesOf() - JavaScript
me's default locale. Description Returns an array with a subset of the language tags provided in locales. The language tags returned are those for which the runtime supports a locale in plural formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. ...
...ded in locales. The language tags returned are those for which the runtime supports a locale in plural formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. ...
...atching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. Examples Using supportedLocalesOf() Assuming a runtime that supports Indonesian and German but not Balinese in plural formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to plural formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the lookup algorithm here -- a best fit matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well. var locales = ['ban', 'id-u-co-pinyin', 'de-ID']; var options = { localeMat...
yield - JavaScript
eld keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it. It cannot be called from nested functions or from callbacks. The yield keyword causes the call to the generator's next() method to return an IteratorResult object with two properties: value and done. The value property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed. Once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. Each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of ...
...mediately after the yield. throw is used to throw an exception from the generator. This halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an exception is thrown). The end of the generator function is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is undefined and done is true. A return statement is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is the value specified by the return statement and done is true. If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. Between the generator's code p...
...e following code is the declaration of an example generator function. function* countAppleSales () { let saleList = [3, 7, 5] for (let i = 0; i < saleList.length; i++) { yield saleList[i] } } Once a generator function is defined, it can be used by constructing an iterator as shown. let appleStore = countAppleSales() // Generator { } console.log(appleStore.next()) // { value: 3, done: false } console.log(appleStore.next()) // { value: 7, done: false } console.log(appleStore.next()) // { value: 5, done: false } console.log(appleStore.next()) // { value: undefined, done: true } You can also send a value with next(value) into the generator. 'step' evaluates as a return value in this syntax [rv] = yield [expression] function* counter(value) { let step; while (...
Populating the page: how browsers work - Web Performance
visited this site, a DNS lookup must happen. Your browser requests a DNS lookup, which is eventually fielded by a name server, which in turn responds with an IP address. After this initial request, the IP will likely be cached for a time, which speeds up subsequent requests by retrieving the IP address from the cache instead of contacting a name server again. DNS lookups usually only need to be done once per hostname for a page load. However, DNS lookups must be done for each unique hostname the requested page references. If your fonts, images, scripts, ads, and metrics all have different hostnames, a DNS lookup will have to be made for each one. This can be problematic for performance, particularly on mobile networks. When a user is on a mobile network, each DNS lookup has to go from the...
...er needs to do this super quickly. To ensure smooth scrolling and animation, everything occupying the main thread, including calculating styles, along with reflow and paint, must take the browser less than 16.67ms to accomplish. At 2048 X 1536, the iPad has over 3,145,000 pixels to be painted to the screen. That is a lot of pixels that have to be painted very quickly. To ensure repainting can be done even faster than the initial paint, the drawing to the screen is generally broken down into several layers. If this occurs, then compositing is necessary. Painting can break the elements in the layout tree into layers. Promoting content into layers on the GPU (instead of the main thread on the CPU) improves paint and repaint performance. There are specific properties and elements that instantiat...
...a repaint and a re-composite. Had we defined the size of our image, no reflow would have been necessary, and only the layer that needed to be repainted would be repainted, and composited if necessary. But we didn't include the image size! When the image is obtained from the server, the rendering process goes back to the layout steps and restarts from there. Interactivity Once the main thread is done painting the page, you would think we would be "all set." That isn't necessarily the case. If the load includes JavaScript, that was correctly deferred, and only executed after the onload event fires, the main thread might be busy, and not available for scrolling, touch, and other interactions. Time to Interactive (TTI) is the measurement of how long it took from that first request which led to ...
Optimizing startup performance - Web Performance
to look at a more important issue when building Web apps: starting up as asynchronously as possible. That means not running all your startup code in a single event handler on the app's main thread. Instead, you should write your code so that your app creates a Web worker that does as much as possible in a background thread (for example, fetching and processing data.) Then, anything that must be done on the main thread (such as user events and rendering UI) should be broken up into small pieces so that the app's event loop continues to cycle while it starts up. This will prevent the app, browser, and/or device from appearing to have locked up. Why is it important to be asynchronous? Other than the reasons suggested above, consider the impact of a non-responsive page or user interface. The us...
...ealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device rather than rolling your own or using one from the original codebase. The provided one is almost certainly significantly faster, and will reduce your app size to boot. In addition, the browser may automatically parallelize these decoders. Any data processing that can be done in parallel should be. Don't do one chunk of data after another; do them all at once when possible! Don't include scripts or stylesheets that don't participate in the critical path in your startup HTML file. Load them only when needed. Reduce the side of your JavaScript files. Try to send the minify version of the file to the browser and use compression like Gzip or Brotli. Utilize resource hi...
...y to send the minify version of the file to the browser and use compression like Gzip or Brotli. Utilize resource hints (like preconnect or preload) whenever possible to indicate to the browser which files are more critical for your application. The more stuff you can do asynchronously, the better advantage your app can take of multicore processors. Porting issues Once the initial loading is done and the app's main code starts to run, it's possible your app may necessarily be single-threaded,especially if it's a port. The most important thing to do to try to help with the main code's startup process is to refactor the code into small pieces that can be done in chunks interspersed across multiple calls to your app's main loop, so that the main thread gets to handle input and the like. Ems...
lang/functional - Archive of obsolete content
setTimeout with no wait (i.e. setTimeout(function () { ... }, 0)), except that the wrapped function may be reused and does not need to be repeated each time. This also enables you to use these functions as event listeners. let { defer } = require("sdk/lang/functional"); let fn = defer(function myEvent (event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // This will print 'done' before 'click : #home' since // we deferred the execution of the wrapped `myEvent` // function, making it non-blocking and executing on the // next event loop Parameters fn : function The function to be deferred. Returns function : The new, deferred function. remit() An alias for defer. invoke(callee, params, self) Invokes callee, passing params as an argume...
... Array Parameters to be passed into callee. self : mixed Object to be passed as the this context to callee. Returns mixed : Returns the return value of callee. partial(fn, arguments...) Takes a function and bind values to one or more arguments, returning a new function of smaller arity. let { partial } = require("sdk/lang/functional"); let add = function add (x, y) { return x + y; } let addOne = partial(add, 1); addOne(5); // 6 addOne(10); // 11 partial(add, addOne(20))(2); // 23 Parameters fn : function Function on which partial application is to be performed. arguments... : mixed Additional arguments Returns function : The partial function. compose(fn...) Returns the composition of a list of functions, where each function consumes the return value of the function that follo...
Getting started (cfx) - Archive of obsolete content
is tutorial walks through creating a simple add-on using the cfx command-line tool. cfx has been deprecated and you should use jpm instead. Use cfx only if you need to work with Firefox 38 or earlier. See: Getting started with jpm cfx to jpm Prerequisites To create add-ons for Firefox using the SDK, you'll first need to follow the instructions to install and activate the SDK. Once you've done that, you'll be looking at a command prompt. Initializing an empty add-on In the command prompt, create a new directory. The directory doesn't have to be under the SDK root: you can create it anywhere you like. Navigate to it, type cfx init, and hit enter: mkdir my-addon cd my-addon cfx init You'll see some output like this: * lib directory created * data directory created * test directory ...
...stens for new XPI files on a specified port and installs them automatically. That way you can test new changes without needing to restart the browser: make a change to your add-on run cfx xpi post the add-on to the port specified You could even automate this workflow with a simple script. For example: while true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done Note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run. This means that if you want to see output from console.log() messages, you'll have to tweak a setting. See the documentation on logging levels for the details on this. Another example using grunt and grunt-shell: module.exports = fu...
Extension Versioning, Update and Compatibility - Archive of obsolete content
F over regular http, Gecko 1.9 based applications will require that you digitally sign the update manifest to ensure that it's information isn't tampered with between you creating it and applications retrieving it. The McCoy tool should be used to sign the update RDF. ...
... signing mechanism are beyond the scope of this document however the basics are as follows: Step 1 - Done once, before you publish your add-on The target: Adding updateKey in install.rdf The add-on author creates a public/private RSA cryptographic key pair. The public part of the key is DER encoded and then base 64 encoded and added to the add-on's install.rdf as an updateKey entry. Step 2 - Done every time you change your "update.rdf" file The target: Setting value to signature in update.rdf When the author creates the update rdf file a tool is used to sign it using the private part of the key. Roughly speaking the update information is converted to a string, then hashed using a sha512 hashing algorithm and this hash is signed using the private key. The resultant data is DER encoded th...
How to convert an overlay extension to restartless - Archive of obsolete content
files go here) +- locale folder (your locale files go here) In versions of Firefox prior to 4.0 (Gecko 2.0), the XPI would be extracted into a folder in your profile's extensions folder. In current versions it stays unextracted as an XPI. If you were using input streams you already had to deal with this because they weren't an option without extraction. Opting-out to extractionlessness is done via the "unpack" flag in install.rdf. Why the internal JAR? Well, two reasons: Prior to extractionless add-ons, all of your files got extracted. Putting them in one single JAR file made all your stuff load in one file read, which was faster. Extractionless XPIs are bascially a standardization of this idea. XPI files are glorified ZIPs, and ZIP compression is horrible. Doing anuncompressed in...
...wn to work around this, but that doesn't seem to be enough with an internal JAR. So, time to switch to extractionless, too. See here for the list of stuff you can't have in addition to no resource:// URIs or file:// URIs to files inside your XPI. If you actually can't find a way to go fully extractionless, you could hack together some combination of internal JAR(s) and extracted files. It can be done. However, you really should go extractionless. Firefox profiles aren't the pristine environment they're supposed to be. Software that pretends to be designed to protect security or privacy that some users have installed will sometimes delete files. There have been plenty of reports of add-on franken-installs with files of two versions mixed together. This might be due to malware or a bug in Firef...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
e element inside the window element in your overlay, some weird errors will begin to happen. Always set the label and tooltiptext attributes of a toolbarbutton. In the case of a toolbaritem element (discussed later), use the title attribute instead of label. Tooltips are very important for users that want to know what a button does before clicking it. Setting the image for a toolbar button is done with CSS: #xulschoolhello-hello-world-button { list-style-image: url("chrome://xulschoolhello/skin/hello-world.png"); } It's not really that simple to set the image for a toolbar button, because we need to consider the appearance of the button on different systems, and also consider the different button states, but we'll get into that further ahead. The CSS file with your toolbar styles nee...
...ow have code that adds one or more buttons to the toolbar palette. The user can now use the Customize Dialog to add the buttons to the current Firefox toolbars. In most cases this is not what you want as default behavior, because it would be very hard for the user to discover your buttons. Keep in mind most users don't know how to customize toolbars in Firefox. Let's add our own toolbar. This is done in the overlay as well. <window id="main-window"> <toolbox id="navigator-toolbox"> <toolbar id="xulschoolhello-toolbar" toolbarname="&xulschoolhello.toolbarName.label;" accesskey="&xulschoolhello.toolbar.accesskey;" customizable="true" mode="icons" context="toolbar-context-menu" defaultset="xulschoolhello-hello-world-button" insertbefore="PersonalToolbar" /> </too...
Mozilla Documentation Roadmap - Archive of obsolete content
urces you should also keep in mind: Other extensions. There are thousands of extensions out there, and you may strike luck and find one that does exactly what you need. Be sure to look at the license the extension's code is released with before thinking about copying large sections of it. Also, remember to give credit when it's due. Mozilla's Bugzilla repository. Pretty much every code change done in Firefox and Mozilla projects is documented in this huge tracking database. But this also means that finding exactly what you need can be time-consuming, and often fruitless. The advanced search is very useful in filtering results, but it is our experience that it's often better to be too general than too specific. Better to scan a list of hundreds of bugs than getting no results at all, right?
... Good luck! << PreviousNext >> This tutorial was kindly donated to Mozilla by Appcoast. ...
Tabbed browser - Archive of obsolete content
var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel); //i used nsIHttpChannel but i guess you can use nsIChannel, im not sure why though var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Components.interfaces.nsIInterfaceRequestor); //var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below var loadContext; try { loadContext = interfaceRequestor.getInterface(Components.interfaces.nsILoadContext); } catch (ex) { try { loadContext = a...
... not an error } } return; } } }; Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false); //this function gets the contentWindow and other good stuff from loadContext of httpChannel function loadContextGoodies(httpChannel) { //httpChannel must be the subject of http-on-modify-request QI'ed to nsiHTTPChannel as is done on line 8 "httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);" //start loadContext stuff var loadContext; try { var interfaceRequestor = httpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor); //var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/d...
Firefox addons developer guide - Archive of obsolete content
FIXME: a message Notes: The original document is in Japanese and distributed via the xuldev.org website. So there may be still some reference to the xuldev website (we want to host source code on MDC, not on xuldev), and to Japanese things (like some specific locales, which have been translated to French since non-latin characters are not well supported). There are a few things that could be done to make this fit the site better, and for general cleaning up: Tables should use the "standard-table" CSS class so they're styled the same as those on the rest of MDC. 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 tho...
... These should use the Previous, Next, and PrevNext templates to add quick routes to get from chapter to chapter. See the XUL Reference, for example. Each chapter should be tagged appropriately, based on content, and every chapter should include the tag "Firefox addons developer guide". Instead of using footnotes, we should inline these notes into the body of the article. Apostrophes are being done using curly apostrophes instead of straight ones as is done everywhere else in MDC. The stuff about installing the DOM inspector (https://developer.mozilla.org/En/Firefox_addons_developer_guide/Let%27s_build_a_Firefox_extension#Install_the_DOM_Inspector) is not accurate for Firefox 3 or later, since it's no longer included in the Firefox installer and must be downloaded from AMO. Filenames shou...
Adding preferences to an extension - Archive of obsolete content
perCase(); this.refreshInformation(); window.setInterval(this.refreshInformation, 10*60*1000); } }, Our object has two member variables. prefs is configured by startup() to reference our extension's preferences, while tickerSymbol indicates the stock symbol to monitor. The first thing the startup() function does is to get a reference to the preferences for our extension. This is done in two steps: First, we get the Preferences service. This component handles preference management for Firefox and any extensions. Second, we call nsIPrefService.getBranch(). This lets us specify a specific branch of the preference tree to access. By default, we would have access to all preferences, but we only want access to those belonging to our own extension, so we specify that we want ...
...ence. You must set em:optionsType to 2 in your install.rdf. Your options.xul file would look like this: <?xml version="1.0" ?> <vbox xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <setting pref="extensions.stockwatcher2.symbol" type="string" title="Stock to watch" /> </vbox> Adding the context menu Adding the contextual menu is easy; all the work that needs doing is done in the stockwatcher2.xul file. The first step is to add the context attribute to the status bar panel: <statusbar id="status-bar"> <statusbarpanel id="stockwatcher2" label="Loading..." context="stockmenu" onclick="StockWatcher.refreshInformation()" /> </statusbar> Now when the user clicks on the status bar panel, the stock information refreshes, but when they right-click...
Getting Started - Archive of obsolete content
stall.rdf and place it in the My_Theme directory, then open it up in your text editor. This file is a small XML database that describes the skin. <Description about="urn:mozilla:install-manifest"> <em:id>{Themes_UUID}</em:id> <em:version>Themes_Version</em:version> The first section requires that you establish a UUID for your theme and that you give your theme a version number. Once you've done this, insert the information as above, and scroll down. You will also have to update the minimum and maximum compatible versions for the target application (SeaMonkey) in the following section: <em:targetApplication> <Description> <!-- SeaMonkey's UUID --> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minVersion>Min_SM_Version</em:minVersion> <em:maxVersi...
...hem, and so on. As an example, let's change the standard button. Go into the global directory and open button.css in your favorite text editor. Scroll down to button {. This section defines the normal button in its basic state (There is no mouse over it, it's not disabled, and it's not selected). Change the background-color: to DarkBlue and the color: to White, and save the file. ...
Download Manager preferences - Archive of obsolete content
her or not new downloads should be added to the recent documents list. Default value is true. browser.download.manager.alertOnEXEOpen A boolean value that indicates whether the UI Should alert the user about the dangers of opening (executing) an EXE. The user may check a "don't ask" box on the UI to toggle this. Default value is true. browser.download.manager.closeWhenDone A boolean value indicating whether or not the Downloads window should close automatically when downloads are completed. In Thunderbird the default value is true. In Other Applications the default value is false. browser.download.manager.flashCount Indicates the number of times the appropriate user interface element should be "flashed" to get the user's attention when a down...
... indicates that the download should be removed upon completion; 1 indicates that completed and canceled downloads should be removed on quit; 2 indicates that downloads should never be removed automatically. In Firefox and SeaMonkey the default value is 2. In Thunderbird the default value is 1; If the preference is missing, the value 0 is used. browser.download.manager.scanWhenDone A boolean value that indicates whether or not to perform virus scans after downloads are complete. On Windows XP SP2 and Windows Vista, this value also indicates whether downloaded files trigger a security warning upon launch. Default value is true. browser.download.manager.showAlertInterval The minimum number of milliseconds that must elapse between download complete alerts; i...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
attachment" set. If so, it skips trying to find an internal viewer and goes right over to looking for a stream converter. Otherwise, DispatchContent goes through a three-step process to try to find the correct listener. The basic idea is that DispatchContent calls nsDocumentOpenInfo::TryContentListener on various content listeners; if that returns true, we have found the right listener and we are done. TryContentListener makes use of the IsPreferred and CanHandleContent functions on nsIURIContentListener and calls DoContent() on the listener if it claims to handle the data, as well as hooking up a stream converter if the listener asks for one. If any of those steps fails, the function returns false so that another content listener will be looked for. The first content listener we check is the ...
...type" (another magic type), this is where nsUnknownDecoder would be instantiated. The conversion attempt is made by calling ConvertData. This creates a new nsDocumentOpenInfo object and sets it as the output streamlistener of the converter. This way, once we know what type we've managed to get we can attempt to redispatch it. If a converter is found, we hook that up as our stream listener and are done -- we just need to pump data into it and let the downstream nsDocumentOpenInfo handle the final dispatch. If we still do not have a stream listener, that means that we failed to find an nsIURIContentListener or nsIContentHandler for this type. Give the load to the helper app service; this will return an nsIStreamListener that we can use. Original Document Information Author(s): Boris Zbarsk...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
for images contained in hyperlinks: jetpack.menu.context.page.on("a > img").set("An Image Inside a Link"); Add a "Recent Tweets" submenu to the Jetpack menu. (Assume we've defined a getRecentTweets(), which invokes a callback with an array of strings.) When the menu is shown, it displays a "Loading..." item. If the menu remains open when getRecentTweets() receives data from the network and calls done(), the "Loading..." item is replaced with the tweets, one item per tweet: This example will not work on OS X due to a platform bug in Firefox. Replace jetpack.menu with jetpack.menu.context.page to see the effect on the content context menu. See bug 526382 for more information. jetpack.menu.add({ label: "Recent Tweets", menu: new jetpack.Menu({ beforeShow: function (menu) { men...
...s, one item per tweet: This example will not work on OS X due to a platform bug in Firefox. Replace jetpack.menu with jetpack.menu.context.page to see the effect on the content context menu. See bug 526382 for more information. jetpack.menu.add({ label: "Recent Tweets", menu: new jetpack.Menu({ beforeShow: function (menu) { menu.set("Loading..."); getRecentTweets(function done(tweets) menu.set(tweets)); } }) }); When the user selects some text on a page, the context menu normally displays a simple item that searches for it. Replace that item with a menu that lets the user search either Google or Wikipedia: jetpack.menu.context.page.replace("Search", function (context) { return { label: "Search for " + jetpack.selection.text, menu: new jetpack.Menu([ ...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
lmById("myID"); function getElmById(aID){ var element = null; if (isMozilla || isIE5) element = document.getElementById(aID); else if (isNetscape4) element = document.layers[aID]; else if (isIE4) element = document.all[aID]; return element; } The above code still has the issue of browser sniffing, or detecting which browser the user is using. Browser sniffing is usually done through the useragent, such as: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031016 While using the useragent to sniff the browser provides detailed information on the browser in use, code that handles useragents often can make mistakes when new browser versions arrive, thus requiring code changes. It is much better and more reliable to sniff by browser capability or object feature...
...he full year for any other year. (i.e. for 1999, getYear() returns 99, for 2000, it returns 2000). JavaScript execution differences Different browsers execute JavaScript differently. For example, the following code assumes that the div node already exists in the DOM by the time the script block executes: ... <div id="foo">Loading...</div> <script> document.getElementById("foo").innerHTML = "Done."; </script> However, this is not guaranteed. To be sure that all elements exist, you should use the onload event handler on the <body> tag: <body onload="doFinish();"> <div id="foo">Loading...</div> <script> function doFinish() { var element = document.getElementById("foo"); element.innerHTML = "Done."; } </script> ... Such timing-related issues are also hardware-related -- sl...
Monitoring downloads - Archive of obsolete content
where the user downloads the same file multiple times. Displaying the download log The download log window's code is encapsulated in an object called downloadlogger_dlwindow. Since this is a simple example, it's a one-shot log window; it doesn't monitor for further changes to the log. It simply displays the state of downloads at the moment the window was opened. ...
...ish to retrieve. Note that the start time is being divided by 1000 before we create a JavaScript Date object from it. That's to adjust the value from the granularity stored in the database to that expected by JavaScript. To right-justify the numeric columns, we set the appropriate cells' style attribute to text-align:right. Exercises for the reader There are some obvious things that could be done to improve this extension. If you're learning to use the Download Manager or Storage APIs, they're things you might look into doing for practice: Add code to update the download log window on the fly, instead of generating a static list when it's first opened. Add additional statistics. What's the average download speed across all downloads? What times of day do you get the best download p...
Hacking wiki - Archive of obsolete content
he folder itself) into the <tt>www</tt> directory on your server. The contents of the <tt>trunk</tt> directory you just checked out is a slightly modified MediaWiki install, so you can follow the MediaWiki install instructions. The <tt>css</tt> folder contains files that are supposed to be in the <tt>/css</tt> directory of the site.) To get a working install, you need to configure MediaWiki. It's done by navigating to <tt>/config/index.php</tt> in your web browser. Polvi claims that you'll have it, but in case you don't, you can copy one from the MediaWiki tarball. Once you're done with the configuration script, copy the <tt>config/LocalSettings.php</tt> file it created to the parent directory and navigate to the location you installed MediaWiki to. A main page should appear. You can log in an...
...an enable them by adding include("extensions/ExampleExt.php"); to the end of your <tt>LocalSettings.php</tt>. For example: [snip] include("extensions/Breadcrumbs.php"); include("extensions/TitleOverride.php"); include("extensions/Abbr.php"); include("extensions/Object.php"); include("extensions/Kbd.php"); ?> TBD installing/configuring RSS and Doxygen extensions - anything special needs to be done? The title-override / breadcrumbs extensions need an additional table created. To configure it, run <tt>update-devmo.php</tt> from the command line. The following worked for me (from the <tt>www</tt> directory): /path/to/php -f ./maintenance/update-devmo.php Done You should have a working install of the MDC wiki now. If you have problems with setting up the MDC wiki (and not the web server or...
New Skin Notes - Archive of obsolete content
e the default behaviour. --dria Headers which are also links that point to as-yet-unwritten wiki pages are colored as though they actually do exist. For an example of this, see Creating XPCOM Components. --Waldo 21:09, 25 Aug 2005 (PDT) Not Going to Change (Yet or possibly Ever) Adding pipes between buttons in horizontal nav-bar (ie: My talk | Preferences | My watchlist) (stricken part is done). Also, and this is a nit, it's a little "my" crazy up there -- do we need all the "My"s? --beltzner Any chance we can mobe the "main page" scrollbar to the actual "content area" of the page, so that the sidebar `stays` when in-use, and on dynamic pages (such as the preferences page) if you toggle between something that needs a verticle scrollbar and something that doesnt, you get screen-jitter...
...05 (PDT) For all that it is worth, I am against setting the 'base' font-size to anything other than 100%, let the User figure out which font-setting is best for him/her on his/her computer, rather than tweak it to what the designer feels is the right size for the designers eye(s). If the designer wants smaller text, tweak his UA's text size off of the base, for 100% page specified text. And when done, verify that the designer did not break the page with a "normal" font setting, by using a default profile. And no, break in that sense does not mean "font is too big" it means, still useable for the target audience. --Callek 12:02, 26 Aug 2005 (PDT) The font size isn't the problem, and we indeed shouldn't change it. The menu bar at the right, however, is too large in the new system, but is fine ...
Reading textual data - Archive of obsolete content
ar utf8Converter = Components.classes["@mozilla.org/intl/utf8converterservice;1"]. getService(Components.interfaces.nsIUTF8ConverterService); var data = utf8Converter.convertURISpecToUTF8 (str, "UTF-8"); Gecko 1.8 and newer Reading strings Starting with Gecko 1.8 (SeaMonkey 1.0, Firefox 1.5), you can use nsIConverterInputStream to read strings from a stream (nsIInputStream). This work was done in bug 295047. Usage: var charset = /* Need to find out what the character encoding is. Using UTF-8 for this example: */ "UTF-8"; const replacementChar = Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER; var is = Components.classes["@mozilla.org/intl/converter-input-stream;1"] .createInstance(Components.interfaces.nsIConverterInputStream); is.init(f...
...Not doing so can cause problems if you try to rename or delete the file at a later time on some platforms. Note that you may get less characters than you asked for, especially (but not only) at the end of the file (stream). Unsupported byte sequences You can specify what should happen with byte sequences that do not correspond to a valid character. The last (4th) argument...
Frequently Asked Questions - Archive of obsolete content
act us. Can I use a plugin for SVG instead of Mozilla's native support? Individuals can choose to use a plugin to view SVG in Mozilla on their own computers, but there is no way for SVG content authors to make Mozilla use a plugin when people view the SVG files on their website. The native SVG support must be turned off before Mozilla will look to see if there's an SVG plugin installed. This is done by toggling a hidden user configuration preference (pref). To access the pref type about:config into the URL bar, then type svg.enabled into the Filter field. When you double click on the pref you will see its value change to and from true/false, turning the native support on/off. How does Mozilla's SVG implementation compare to Adobe's? Mozilla's native implementation is less complete than Ado...
...ese things you should still feel free to ask us friendly questions and give us constructive feedback. Who's currently working on what? Other than reviewing patches and fixing the occassional bug, Alex is currently taking a break from active SVG development to concentrate on 'real work' and cool stuff like XTF and JSSh. Tim is working on implementing <filter> and working on items that need to be done before turning on SVG by default. After recently implementing gradients, Scooter is working on fixing some issues that remain outstanding and fixing <switch>. Jonathan is working on various bugs, especially those that need to be fixed before SVG can be enabled in the official builds. David continues to create SVG enabled nightlies and answer build related questions as he has done for some time. F...
Space Manager High Level Design - Archive of obsolete content
oyed. Thus, Space Managers are effectively 'nested' during reflow, with each new block introducing its own Space Manager. Use Case 2: Float is added to the Space Manager After a Space Manager is created for a block context's reflow chain, a floated block may be added to it. This happens in the method nsBlockReflowState::RecoverFloats and nsBlockReflowState::FlowAndPlaceFloat (formerly this was done in nsBlockFrame::UpdateSpaceManager). The general algorithm in nsBlockReflowState::RecoverFloats is: For each line in the block, see if it has floated blocks If floats are in the line, iterate over the floats and add each one to the Space Manager via the AddRectRegion method. The actual rect for the frame is cached in an nsFloatCache so it does not have to be recomputed. If the block has any ...
... If floats are in the line, iterate over the floats and add each one to the Space Manager via the AddRectRegion method. The actual rect for the frame is cached in an nsFloatCache so it does not have to be recomputed. If the block has any block children, then translate the Space Manager to the child block's origin and update the space manager in the context for the child block, recursively. When done with the child, restore the Space Managers coordinates by translating by the negative of the child block's origin. The general algorithm in nsBlockReflowState::FlowAndPlaceFloat is: The region that the float currently occupies is recorded. The band of available space is searched (with nsBlockReflowState::GetAvailableSpace); The float frame that is get from the passed nsFloatCache argument is...
Static Analysis for Windows Code under Linux - Archive of obsolete content
bz2 tar jxvf gcc-4.3.0.tar.bz2 # Get the patches which enable plugins cd gcc-4.3.0/ # Create an hg repository. This makes it easy to apply patches, they can be applied manually hg init . hg clone http://hg.mozilla.org/users/tglek_mo...-moz-plugin-mq .hg/patches # Apply gty.diff and plugin.diff # If you have mq setup, do hg qpush -a (for file in `cat .hg/patches/series`; do cat .hg/patches/$file; done) |patch -p1 cd .. Now, the Gcc source with plugin supports is ready, we should now build a cross compiler from this source. And the instructions are exactly the same with the one here. Follow that instructions strictly for making a cross compiler. Build Dehydra for Cross-compiler Build the Dehydra plugin Dehydra is a shared library which will be loaded by the above plugin-support gcc. Buil...
... Troubles You can post any question about static check to the mozilla.dev.static-analysis newsgroup and any question about cross compiling to the mozilla.dev.builds newsgroup. ...
The life of an HTML HTTP request - Archive of obsolete content
Interrupt() and nsHTMLContentSink::DidBuildModel(). WillInterrup is called by the parser between every 8kb block of data (unless the parser is temporarily blocked). (7) Since the presentation shell (nsPresShell) has registred as an DocumentObserver with the nsIDocument it also gets notified of changes in the Document/Content tree. This is used to create and update the nsIFrame hierarchy. This is done by the nsCSSFrameConstructor, which creates frames for each Content node according to the rules specified in the user agent stylesheet (ua.css) and the document specific style sheets. Each Content node corresponds to one or more nsIFrame, except content with displaytype "none". If there are several frames created from a content node, then the first of these are called the "primary" node, and the ...
...ified in the user agent stylesheet (ua.css) and the document specific style sheets. Each Content node corresponds to one or more nsIFrame, except content with displaytype "none". If there are several frames created from a content node, then the first of these are called the "primary" node, and the following frames can be found by using the GetNextInFlow() method of nsIFrame. The initial reflow is done by the nsHTMLContentSink::StartLayout(), StartLayout() calls PresShell::InitialReflow(). StartLayout is called quite early in the parsing process, for HTML it's called in nsHTMLContentSink::OpenBody() (among other places). TODO: How are nsIFrames reflowed after a change when they already exist? (8) Each nsIFrame knows how how to draw itself on the screen. When the PresShell [Note: not true, who...
URIs and URLs - Archive of obsolete content
wn set of characters that are reserved, so only the mechanism responsible for generating or interpreting that component can determine whether or not escaping a character will change its semantics. Likewise, a URI must be separated into its components before the escaped characters within those components can be safely decoded. This implies that the segments of urls are escaped differently. This is done by NS_EscapeURL which is now part of xpcom, but started as part of Necko. The information how to escape each segment is stored in a matrix. Also a string should not be escaped more than once. Necko will not escape an already escaped character unless forced by a special mask that can be used if it is known that a string is not escaped. Parsing URLs RFC 2396 defines an URL parser that can deal with...
...t is not known if an authority segment exists or not, less syntax correction can be applied in this case. Noteable Differences Necko does not support certain deprecated forms of relative URLs, based on the following part of RFC 2396: If the scheme component is defined, indicating that the reference starts with a scheme name, then the reference is interpreted as an absolute URI and we are done. Otherwise, the reference URI's scheme is inherited from the base URI's scheme component. Due to a loophole in prior specifications (RFC1630), some parsers allow the scheme name to be present in a relative URI if it is the same as the base URI scheme. Unfortunately, this can conflict with the correct parsing of non-hierarchical URI. For backwards compatibility, an implementation may work around s...
Using gdb on wimpy computers - Archive of obsolete content
ries to be loaded. Here's what it looks like in the 4.18 version of the debugger: ^C Program received signal SIGINT, Interrupt. 0x404ccdeb in __sigsuspend (set=0xbf5ffbc0) at ../sysdeps/unix/sysv/linux/sigsuspend.c:48 48 ../sysdeps/unix/sysv/linux/sigsuspend.c: No such file or directory. Current language: auto; currently c (gdb) shar glib Reading symbols from /usr/lib/libglib-1.2.so.0...done. (gdb) Here's what it looks like in a version 5.x of the debugger ( yet unreleased ): ^C Program received signal SIGINT, Interrupt. [Switching to Thread 2051 (runnable)] 0x404ccdeb in __sigsuspend (set=0xbf5ffbac) at ../sysdeps/unix/sysv/linux/sigsuspend.c:48 48 ../sysdeps/unix/sysv/linux/sigsuspend.c: No such file or directory. Current language: auto; currently c (gdb) shar gtk Readin...
...rsion 5.x of the debugger ( yet unreleased ): ^C Program received signal SIGINT, Interrupt. [Switching to Thread 2051 (runnable)] 0x404ccdeb in __sigsuspend (set=0xbf5ffbac) at ../sysdeps/unix/sysv/linux/sigsuspend.c:48 48 ../sysdeps/unix/sysv/linux/sigsuspend.c: No such file or directory. Current language: auto; currently c (gdb) shar gtk Reading symbols from /usr/lib/libgtk-1.2.so.0...done. Loaded symbols for /usr/lib/libgtk-1.2.so.0 Reading symbols from /usr/lib/gtk/themes/engines/libthinice.so...done. Loaded symbols for /usr/lib/gtk/themes/engines/libthinice.so (gdb) As you see above, it's possible to load more than one library with the same load command in GDB. How do I see what libraries I already have loaded? You can see what libraries you already have loaded with the info sh...
MenuItems - Archive of obsolete content
e the toolbar when the menuitem is checked and show the toolbar when the menuitem is not checked because the checked state hasn't been modified. The example assumes that the showToolbar() function might fail so if it returns false, the checked attribute is not modified. When clearing the checked state, the checked attribute should be removed rather than just set to false. In the example, this is done by using the removeAttribute method. Radio menu items A radio menu item os used when you wish to have a group of menuitems in which only one can be checked at a time. This works similarly to the checkbox type, except when selecting an item, all others in the same group are automatically unchecked. To create a menuitem that acts like a radio button, set the type attribute to "radio". In additio...
...and this will propagate to all elements attached to it. Modifying a menuitem Both the label and the access key may be changed dynamically in script by setting the label and accesskey properties. Note the mixed case of the accessKey property versus the lowercase usage of the accesskey attribute in XUL. For instance, you might want to change the label of an Undo menuitem based on what would be undone. The example below demonstrates this. if (gUndoBufferType == "typing") menuitem.label = "Undo Typing"; else if (gUndoBufferType == "paste") menuitem.label = "Undo Paste"; else menuitem.label = "Undo"; See Modifying a Menu for examples of how to add and remove items from a menu ...
Multiple Queries - Archive of obsolete content
ry. In fact, the order is the same as the examples that only use one query. Compare the multiple query example with an earlier example that used only a single query. The photos have appeared in the same order in both cases. This is because the builder notices that the photos are in an RDF Seq in the datasource and arranges them in the order they appear in the Seq. This and other automated sorting done by the template builder is a fairly complicated process that will be discussed in more detail later. Multiple Queries Using the RDF Simple Syntax You can also use multiple queries with RDF datasources using the simple query syntax. Here is the previous example rewritten using the simple syntax: <hbox id="photosList" datasources="template-guide-photos3.rdf" ref="http://www.xulplanet.com/...
...fficient when using multiple queries using the simple query syntax. This is because all simple queries will iterate over the same data, usually the children of an RDF container. So the builder only performs this step once and filters the data for each query. When using the extended query syntax, the manner in which the graph is navigated may be different for every query, so no optimization can be done. The builder needs to process every condition of every query. If, for example, you have six queries, each with a <member> condition, the builder will need to construct the children six times. You probably won't notice any difference for small amounts of data such as the photos example we've been using, but you might for large datasets. Thus, you will want to use the simple query syntax when possi...
RDF Modifications - Archive of obsolete content
r also has two methods onBeginUpdateBatch and onEndUpdateBatch. These are called when performing a lot of operations on a datasource. When changing the datasource, the changes are surrounded by begin and end batch calls. Then, rather than notify on every change, the datasource will send one notification when the changes are finished. The template builder then rebuilds the template completely when done. This is useful when making a large amount of changes to avoid having to keep recalculating parts of the template that might change again quickly. Adding RDF Triples Let's say we've just added the triple below to the datasource. subject: http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg predicate: http://purl.org/dc/elements/1.1/description object: One of the thirty or so Egyptian obelisk...
...cates that may optionally have values, the addition or removal or this RDF data would never be able to add or remove a new result. At the very most, the change would cause a label to be filled in with a value, or cleared when removing an RDF triple. As described earlier, the query part of a template is checked first to see if it would cause a change. After this, the bindings are examined. This is done whether the query produced a new result, removed one, or the content was not affected, since a binding could have affected any existing results. It's possible, for instance, for every existing row to be affected by a single triple being added to the datasource. Consider the following binding: <binding subject="?start" predicate="http://www.xulplanet.com/rdf/categoryName" ...
Using Recursive Templates - Archive of obsolete content
="?name"/> </vbox> </action> </template> </groupbox> In this simplified example, the XPath expression just gets the list of child elements of the reference node. For the outermost iteration, a vbox is created with a child label. Since the initial reference node is the root of the XML source document, the results are two elements, one for each group element. However, a further step is done to retrieve an additional level of nodes. As each group has children itself, each result (in this case, each group) becomes the reference point for a futher iteration. The same query is executed again but using the groups generated from the previous execution of the query. This time, the query generates a result for each person in the XML source. The content of the action body is again generated ...
...ent"> <label value="Female"/> <vbox id="row7" class="indent"><label value="Cleopatra"/></vbox> <vbox id="row8" class="indent"><label value="Laura Secord"/></vbox> </vbox> </groupbox> Note how similar content corresponding to the action body is created for both the groups as well as the people. The template builder has also added container and empty attributes to the groups. This is done with all nodes that have children to indicate that the node contains generated children as well as whether the node is empty. These hints are used for trees, but they can also be used in a stylesheet to provide a different appearance for containers with children, empty containers, as well as non-containers. In this example, both the parent groups and child people are displayed the same. You could...
Adding Properties to XBL-defined Elements - Archive of obsolete content
nt such as label or disabled, but they do not have to. The name attribute on the field element is used to indicate the name of the field. You can use the name from a script to get and set the value. The example below creates a button which generates and stores a random number. You can retrieve this same number multiple times by getting the number property from the button. Most of the work here is done in the oncommand handlers. Later, we'll find out how to move this to XBL. XUL: <box id="random-box" class="randomizer"/> <button label="Generate" oncommand="document.getElementById('random-box').number=Math.random();"/> <button label="Show" oncommand="alert(document.getElementById('random-box').number)"/> XBL: <binding id="randomizer"> <implementation> <field name=...
... name="number"> <getter> return this.getAttribute('number'); </getter> <setter> var v = parseInt(val,10); if (!isNaN(v)) { this.setAttribute('number', '' + v); } </setter> </property> The property in this example will only be able to hold integer values. If other characters are entered, they are stripped off. If there are no digits, the value is not changed. This is done in the code inside the setter element. The real value of the property is stored in the number attribute. You can use either syntax for creating get and set handlers. Readonly Attribute You can make a field or property read-only by adding a readonly attribute to the field tag or property tag and setting it to true. Attempting to set the value of a read-only property will fail. Note: The readonly...
Adding Style Sheets - Archive of obsolete content
already seen how to import style sheets for use. An example is shown below: <?xml-stylesheet href="chrome://bookmarks/skin/" type="text/css"?> This might be the first lines of a bookmarks window. It imports the bookmarks style sheet, which is bookmarks.css. Mozilla's skin system is smart enough to figure out which style sheet to use, because the specific filename was not indicated here. ...
...because the specific filename was not indicated here. We have done a similar thing with the global style sheet file (chrome://global/skin). A style sheet may import styles from another stylesheet using the import directive. Normally, you will only import one style sheet from each XUL file. The global style sheet can be imported from within the style sheet associated with the XUL file. This can be done with the code below, allowing you to remove the import from the XUL file: Style import from XUL: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> Style import from CSS: @import url(chrome://global/skin/); The second syntax is preferred because it reduces the number of dependencies within the XUL file itself. Remove the global style sheet import from findfile.xul and add the i...
More Wizards - Archive of obsolete content
ext handlers. Remember to return false in this case, because you have already changed the page yourself. Note that the goTo() method, because it causes a page change, will fire the events again, so you'll have to make sure you handle that case. For example, here are a set of wizard pages (the inner content has been omitted): <wizardpage pageid="type" next="font"> <wizardpage pageid="font" next="done"> <wizardpage pageid="color" next="done"> <wizardpage pageid="done"> The wizard always starts at the first page, which in this case has the page ID type. The next page is the one with the page ID font, so the wizard will navigate to that page next. On the page with the page ID font, we can see that the next page is done, so that page will be displayed afterwards. The page with the page ID...
... A script will adjust the next attributes as necessary to go to the page with the page ID color when needed. Wizard Functions The wizard works much like a tabbed panel, except that the tabs are not displayed and the user navigates between pages by using the buttons along the bottom. ...
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
y from scratch if necessary. If you do, you might store the data in an array or JavaScript data structure, or load the data from an XML file. Since the entire body of the tree is a single widget, you can't change the style of individual rows or cells in the normal way. This is because there are no elements that display the individual cells, like there is with the listbox. Instead, all drawing is done by the tree body using data supplied by the view. This is an important point and many XUL developers have trouble understanding this aspect. To modify the appearance of a tree cell, the view must instead associate a set of keywords for a row and cell. A special CSS syntax is used which styles components of the tree body with those keywords. In a sense, it is somewhat like using CSS classes. Tree ...
...uld be placed directly inside a treecols element. In this case we haven't specified a view to supply the tree's data, so we'll only see column headers and an empty tree body. You may have to resize the window to see anything since there isn't any data to display. Since the tree has been marked as flexible, the body will stretch to fit the available space. Making a tree flexible is quite commonly done, as it is often the case that the data in the tree is the most significant information displayed, so it makes sense to make the tree grow to fit. However, you may specify a specific number of rows to appear in a tree by setting the rows attribute on the tree element. This attribute specifies how many rows are displayed in the user interface, not how many rows of data there are. The total number o...
XML - Archive of obsolete content
to describe thestructure of a real, very simple memo. Note that our language doesn't suffice to describe the content of the memo, which is written in english. But that's not what markup languages are for, in general. An actual memo using the MemoML to represent itself might look like this: <memo> <from>Ian Oeschger</from> <to>Steve Rudman</to> <body>I think the first draft of the guide is done!</body> </memo> Note how the memo element -- the root element in our brief definition, ordeclaration, above -- surrounds the other three elements. In the MemoML definition, the memo element is defined as containing the from, to, and body elements in that order. So the example here is valid memo according to our DTD; it's a memo that's been writtten in MemoML. Bam! You're a markup language progr...
...iant and cross-platform, so rather than defining on its own how these widgets should be rendered, Gecko depends for all but the most basic behavioral and presentational aspects of the widgets upon Cascading Stylesheets. The combination of structure, as defined in the XUL, style as defined by the stylesheets, and the other standards are rendered by Gecko into the interface. The heavy lifting is done by the ingredients rather than the chef. This arrangement creates new possibilities for truly cross-platform web applications, application serving, web appliances and embedded systems, and all sort of other things. Like all really good technologies, XUL and its XP cousins are already being used in ways not imagined by their creators and growing propitiously out of control. Author: Ian T. Oeschge...
tabbrowser - Archive of obsolete content
aut...
... appended or replaced depending on the state of the preference browser.tabs.loadGroup. The argument should be an array of objects, one for each document to load. The objects may be defined in script and contain a URI property for the URL of the page to load. A referrerURI property may also be optionally used to set the referrer page. This function returns a reference to the first tab loaded. loadOneTab( URL, referrerURI, charset, postData, loadInBackground, allowThirdPartyFixup ) loadOneTab( URL, { referrerURI: ..., charset: ..., postData: ..., inBackground: ..., allowThirdPartyFixup: ..., relatedToCurrent: ... }) Return type: tab element Opens a new tab that loads a page with the specified URL. The rest of the parameters are optional. This method works the same as addTab except for the l...
2006-10-27 - Archive of obsolete content
Meetings Gecko 1.9/Gran Paradiso Status Meeting Gecko 1.9/Gran Paradiso Status Meeting: October 25th, 2006 - 11am PDT. ...
... Meetings Gecko 1.9/Gran Paradiso Status Meeting Gecko 1.9/Gran Paradiso Status Meeting: October 25th, 2006 - 11am PDT. ...
NPN_Write - Archive of obsolete content
lug-in can call this function multiple times after creating a stream with NPN_NewStream(). The browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired. See "Example of Sending a Stream" for an example that includes NPN_Write(). Example This example pushes a snippet of HTML over a newly created stream, then destroys the stream when it's done. Note: You should actually handle errors, which this example doesn't do. NPStream* stream; char* myData = "<HTML><B>This is a message from my plug-in!</B></HTML>"; int32 myLength = strlen(myData) + 1; /* Create the stream. */ err = NPN_NewStream(instance, "text/html", "_blank", &stream) /* Push data into the stream. */ err = NPN_Write(instance, stream, myLength, myData); /* Dele...
...'t do. ...
NPP_URLNotify - Archive of obsolete content
instance, const char* url, NPReason reason, void* notifyData); Parameters The function has the following parameters: instance Pointer to the current plug-in instance. url URL of the NPN_GetURLNotify() or NPN_PostURLNotify() request that has completed. reason Reason code for completion of request. Values: NPRES_DONE (most common): Completed normally. NPRES_USER_BREAK: User canceled stream directly by clicking the Stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. NPRES_NETWORK_ERR: Stream failed due to problems with network, disk I/O, lack of memory, or other problems. notifyData Plug-in-private value for associating a previou...
...Plug-in-private value for associating a previous NPN_GetURLNotify() or NPN_PostURLNotify() request with a subsequent NPP_URLNotify() call. Description The browser calls NPP_URLNotify() after the completion of a NPN_GetURLNotify() or NPN_PostURLNotify() request to inform the plug-in that the request was completed and supply a reason code for the completion. The most common reason code is NPRES_DONE, indicating simply that the request completed normally. Other possible reason codes are NPRES_USER_BREAK, indicating that the request was halted due to a user action (for example, clicking the Stop button), and NPRES_NETWORK_ERR, indicating that the request could not be completed, perhaps because the URL could not be found. The parameter notifyData is the plug-in-private value passed as an argum...
Tamarin Tracing Build Documentation - Archive of obsolete content
Use the following command to create a copy of the Tamarin repository: $ hg clone http://hg.mozilla.org/tamarin...
...Use the following command to create a copy of the Tamarin repository: $ hg clone http://hg.mozilla.org/tamarin-tracing tamarin-tracing Building Tamarin Building Tamarin will create all the ...
Browser Feature Detection - Archive of obsolete content
window.onerror = null; document.write('<p><b> Your browser ' + navigator.userAgent + '<\/b><\/p>'); generateReport(document, 'DOMCORE1', 'document'); generateReport(document, 'DOMCORE2', 'document'); generateReport(document, 'DOMHTML', 'document'); generateReport(document.body.style, 'DOMCSS1', 'document.body.style'); generateReport(docu...
... Note: This reprinted article was originally part of the DevEdge...
Using JavaScript Generators in Firefox - Archive of obsolete content
version 1.7 or later. You can opt in in HTML as follows: <script type="text/javascript;version=1.7" src="myScript.js"></script> Then your myScript.js file might look like this: // Need to stash the generator in a global variable. var generator; // Simple event listener function to pass the received event to the generator. function grabEvent(event) { generator.send(event); } // When we're all done we can close the generator, but that must happen outside // of the generator so we use a timeout. function closeGenerator() { setTimeout(function() { generator.close(); }, 0); } // Our main steps function databaseOperation() { mozIndexedDB.open("MyTestDatabase").onsuccess = grabEvent; var event = yield; var db = event.target.result; if (db.version != "1.0") { db.setVersion(...
... closeGenerator(); // Always have an extra yield at the end or you will see StopIteration // exceptions. yield; } generator = databaseOperation(); generator.next(); ...
Reference - Archive of obsolete content
t1.2" is mentioned in this reference: Special:Search?search=JavaScript1.2&go=Go. How should they be revised? --Maian 23:43, 21 September 2005 (PDT) I think we need a new section in the reference that specifies the differences between versions, collecting this information into a single location rather than leaving it scattered haphazardly throughout the reference as it currently is. ...
...BTW, https://bugzilla.mozilla.org/attachment.cgi?id=195375 is a screenshot of a table of differences. ...
Parsing microformats in JavaScript - Archive of obsolete content
, img and alt, area and alt, and value excerpting. propertyValue = Microformats.parser.defaultGetter(propnode, parentnode, datatype); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node. Otherwise this is the microformat node. datatype "HTML" if the search should be done using innerHTML(), or "text" to use innerText(). The default is "text". Return value A string containing the property's value. emailGetter() Specifically retrieves an email address from a microformat node. This removes the subject if one is specified, as well as the mailto: prefix. email = Microformats.parser.emailGetter(propnode, parentnode); Parameters propnode The DOM node to ...
...value excerpting. tel = Microformats.parser.telGetter(propnode, parentnode); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node. Otherwise this is the microformat node. Return value A string containing the telephone number. uriGetter() Specifically retrieves a URI from a microformat node. This is done by looking at an href, img, object, or area to get the fully-qualified URI. uri = Microformats.parser.uriGetter(propnode, parentnode); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node. Otherwise this is the microformat node. Return value A string containing the fully-qualifie...
RDF in Mozilla FAQ - Archive of obsolete content
rver interface that allows you to spy on a datasource's progress. The following code illustrates its usage: // This is the object that will observe the RDF/XML load's progress var Observer = { onBeginLoad: function(aSink) {}, onInterrupt: function(aSink) {}, onResume: function(aSink) {}, onEndLoad: function(aSink) { aSink.removeXMLSinkObserver(this); alert("done!"); }, onError: function(aSink, aStatus, aErrorMsg) { alert("error! " + aErrorMsg); } }; // Get the RDF service var RDF = Components .classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); // Get the datasource. var ds = RDF.GetDataSource("http://www.mozilla.org/some-rdf-file.rdf"); // Now see if it's loaded or not... var remote = ds.QueryIn...
...bring up Necko to be able to load and process URLs just like Mozilla does. Nothing happens after I call AddDataSource. Note that the template builder will not rebuild the contents of a template automatically after AddDataSource or RemoveDataSource have been called on the builder's database. To refresh the template's contents, you must manually call elt.builder.rebuild() yourself. Why? This was done to avoid multiple rebuilds when more than one datasource is added to the database. Examples Where can I find some (working) examples? A few examples are posted here. Some of these are included in signed scripts, and are runnable from HTTP directly. See also duplicates.rdf (for live RDF feed from Mozilla) alongside duplicates.xul. Note that for these to work, you have to relax Mozilla's securi...
Game monetization - Game development
g it you should consider earning some money out of it. If your work is a serious endeavour on the path to becoming an independent game developer able to make a living, read on and see what your options are. The technology is mature enough; now it's just about chosing the right approach. Paid games The first, most obvious choice that may come to your mind might be selling the games the way it is done for huge AAA titles -- with a fixed, up front price. Even though the digital market is key and you don't need to print covers and put your game in a physical store in boxes, to earn decent money on selling your games for a fixed price you have to invest your time and money in marketing. Only the best games will break even or earn more than they cost to make, and you still need a lot of luck for t...
...ey follow various strategies to earn money via your games, but you don't have to worry about all that as selling the license is usually a one-time deal. You get the money and they can get creative with using your game to make money. Finding publishers might be hard at first -- try to look for them at the HTML5 Gamedevs forums. If you're well known they may reach out to you. Most of the deals are done through emails when talking to a dedicated person on the publisher side. Some publisher websites have that information easily available, while some others are harder to find. When reaching a publisher try to be nice and straight to the point -- they are busy people. Exclusive licenses The exclusive license is a type of license for one publisher -- you've built a game and you're selling all the ...
Desktop mouse and keyboard controls - Game development
the list of supported platforms. We'll look at this below. It's also easier to test control-independent features like gameplay on desktop if you develop it there, so you don't have to push the files to a mobile device every time you make a change in the source code. Note: the Captain Rogers: Battle at Andromeda is built with Phaser and managing the controls is Phaser-based, but it could also be done in pure JavaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's totally up to you which approach you chose. Pure JavaScript approach Let's think about implementing pure JavaScript keyboard/mouse controls in the game first to see how it would work. First, we'd need an event listener to listen for the pressed keys:...
... if(this.stateStatus == 'intro') { this.hideIntro(); } }; This hides the intro and starts the actual game, without us having to set up another new key control just for this. Pause and game over screens To make the game fully playable with keyboard it should be possible to go back to the main menu, continue playing, or restart the game from the pause and game over screens. It can be done exactly the same as before -- by capturing key codes and performing actions. For example, by specifying Phaser.KeyCode.Backspace or Phaser.KeyCode.Delete you can hook up an action to fire when the Delete/Backspace button is pressed. Summary Ok, we've dealt with touch, keyboard and mouse controls. Now let's move on to look at how to set up the game to be controlled using a console gamepad, usin...
Tiles and tilemaps overview - Game development
or Final Fantasy's world view.) Side-view (like platformers such as Super Mario Bros.) Static tilemaps A tilemap can either fit into the visible screen area screen or be larger. In the first case, the tilemap is static -- it doesn't need to be scrolled to be fully shown. This case is very common in arcade games like Pacman, Arkanoid, or Sokoban. Rendering static tilemaps is easy, and can be done with a nested loop iterating over columns and rows. A high-level algorithm could be: for (var column = 0; column < map.columns; column++) { for (var row = 0; row < map.rows; row++) { var tile = map.getTile(column, row); var x = column * map.tileSize; var y = row * map.tileSize; drawTile(tile, x, y); } } You can read more about this and see an example implementation in Squar...
...y, some techniques need to be implemented so scrolling can be smooth. The first approach, as discussed above, is to only draw tiles that will be visible. But sometimes, this is not enough. One simple technique consists of pre-rendering the map in a canvas on its own (when using the Canvas API) or on a texture (when using WebGL), so tiles don't need to be re-drawn every frame and rendering can be done in just one blitting operation. Of course, if the map is large this doesn't really solve the problem -- and some systems don't have a very generous limit on how big a texture can be. One way consists of drawing the section that will be visible off-canvas (instead of the entire map.) That means that as long as there is no scrolling, the map doesn't need to be rendered. A caveat of that approach ...
Accessible multimedia - Learn web development
. This article shows how. Prerequisites: Basic computer literacy, a basic understanding of HTML, CSS, and JavaScript, an understanding of what accessibility is. Objective: To understand the accessibility issues behind multimedia, and how to overcome them. Multimedia and accessibility So far in this module we have looked at a variety of content and what needs to be done to ensure its accessibility, ranging from simple text content to data tables, images, native controls such as form elements and buttons, and even more complex markup structures (with WAI-ARIA attributes). This article on the other hand looks at another general class of content that arguably isn't as easy to ensure accessibility for -- multimedia. Images, videos, <canvas> elements, Flash movies, ...
... you can choose to generate automated captions/transcripts. Depending on how clear the spoken audio is, the resulting transcript quality will vary greatly. As with most things in life, you tend to get what you pay for; different services will vary in accuracy and time taken to produce the transcript. If you pay a reputable company or AI service to do the transcription, you will probably get it done rapidly and to a high quality. If you don't want to pay for it, you are likely to get it done at a lower quality, and/or slowly. It is not OK to publish an audio resource but promise to publish the transcript later on -- such promises often aren't kept, which will erode trust between you and your users. If the audio you are presenting is something like a face to face meeting or live spoken perfo...
WAI-ARIA basics - Learn web development
PIs. These are sometimes referred to as live regions. Let's look at a quick example -- see aria-no-live.html (also see it running live). In this example we have a simple random quote box: <section> <h1>Random quote</h1> <blockquote> <p></p> </blockquote> </section> Our JavaScript loads a JSON file via XMLHttpRequest containing a series of random quotes and their authors. Once that is done, we start up a setInterval() loop that loads a new random quote into the quote box every 10 seconds: let intervalID = window.setInterval(showQuote, 10000); This works OK, but it is not good for accessibility -- the content update is not detected by screenreaders, so their users would not know what is going on. This is a fairly trivial example, but just imagine if you were creating a complex UI ...
... <article class="active-panel" role="tabpanel" aria-hidden="false"> ... </article> <article role="tabpanel" aria-hidden="true"> ... </article> <article role="tabpanel" aria-hidden="true"> ... </article> </div> Note: The most striking change here is that we've removed the links that were originally present in the example, and just used the list items as the tabs -- this was done because it makes things less confusing for screenreader users (the links don't really take you anywhere; they just change the view), and it allows the setsize/position in set features to work better -- when these were put on the links, the browser kept reporting "1 of 1" all the time, not "1 of 3", "2 of 3", etc. The new features are as follows: New roles -- tablist, tab, tabpanel -- these i...
Positioning - Learn web development
ioned element will be displayed outside of the <html> element, and be positioned relative to the initial viewport. The positioned element is nested inside the <body> in the HTML source, but in the final layout, it is 30px away from the top and left of the edge of the page. We can change the positioning context -- which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors -- to one of the elements it is nested inside (you can't position it relative to an element it is not nested inside). To demonstrate this, add the following declaration to your body rule: position: relative; This should give the following result: <h1>Positioning context</h1> <p>I am a basic block level element. My adjacent block level ...
...icula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p> <div class="positioned">Sticky</div> <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis nato...
Styling links - Learn web development
ttons to accommodate that should all be the same size. To do this, we set the width to 19.5%, and the margin-right to 0.625%. You'll notice that all this width adds up to 100.625%, which would make the last button overflow the <ul> and fall down to the next line. However, we take it back down to 100% using the next rule, which selects only the last <a> in the list, and removes the margin from it. Done! The last three declarations are pretty simple and are mainly just for cosmetic purposes. We center the text inside each link, set the line-height to 3 to give the buttons some height (which also has the advantage of centering the text vertically), and set the text color to black. Note: You may have noticed that the list items in the HTML are all put on the same line as each other -- t...
...e last three declarations are pretty simple and are mainly just for cosmetic purposes. We center the text inside each link, set the line-height to 3 to give the buttons some height (which also has the advantage of centering the text vertically), and set the text color to black. Note: You may have noticed that the list items in the HTML are all put on the same line as each other -- this is done because spaces/line breaks in between inline block elements create spaces on the page, just like the spaces in between words, and such spaces would break our horizontal navigation menu layout. So we've removed the spaces. You can find more information about this problem (and solutions) at Fighting the space between inline block elements. Test your skills! You've reached the end of this article...
How do I start to design my website? - Learn web development
eally matters is what you want to accomplish. Yes, it seems obvious, but too many projects fail not from a lack of technical know-how, but from lack of goals and vision. So when you get an idea and want to turn it into a website, there are a few questions you should answer before anything else: What exactly do I want to accomplish? How will a website help me reach my goals? What needs to be done, and in what order, to reach my goals? All of this is called project ideation and is a necessary first step to reach your goal, whether you are a beginner or an experienced developer. Active Learning There is no active learning available yet. Deeper dive A project never starts with the technical side. Musicians will never make any music unless they first have an idea of what they want to pl...
...nd promote interaction between us and the public (good for goals 2 and 4). In short, since these goals all revolve around the same topic, having everything in one place will help us meet our goals and help our followers connect with us. How can a website help me reach my goals? By answering that, you'll find the best way to reach your goals and save yourself from wasted effort. What needs to be done, and in what order, to reach my goals? Now that you know what you want to accomplish, it's time to turn those goals into actionable steps. As a side note, your goals are not necessarily set in stone. They evolve over time even in the course of the project, especially if you run across unexpected obstacles or just change your mind. Rather than go through a long explanation, let's go back to our ...
Client-side form validation - Learn web development
ght format). "Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one symbol, and a number." (A very specific data format is required for your data). This is called form validation. When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side validation. In this chapter we are focusing on client-side validation. If the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't correctly formatted, it gives the user an error message...
...ormance than JavaScript, but it is not as customizable as JavaScript validation. JavaScript validation is coded using JavaScript. This validation is completely customizable, but you need to create it all (or use a library). Using built-in form validation One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap: required: Specifies whether a form field needs to be filled in before the form can be submitted. minlength and maxlength: Specifies the minimum and maximum length of textual data (strings) min and max: Specifies the minimum and maximum values of numerical input types type: Specifie...
Sending forms through JavaScript - Learn web development
wapped out for Fetch. If you control the front-end (the code that's executed in the browser) and the back-end (the code which is executed on the server), you can send JSON/XML and process them however you want. But if you want to use a third party service, you need to send the data in the format the services require. So how should we send such data? The different techniques you'll require are done below. Sending form data There are 3 ways to send form data: Building an XMLHttpRequest manually. Using a standalone FormData object. Using FormData bound to a <form> element. Let's look at them in detail. Building an XMLHttpRequest manually XMLHttpRequest is the safest and most reliable way to make HTTP requests. To send form data with XMLHttpRequest, prepare the data by URL-encoding ...
...Data sent and response loaded.' ); } ); // Define what happens in case of error XHR.addEventListener( 'error', function( event ) { alert( 'Oops! Something went wrong.' ); } ); ...
Creating hyperlinks - Learn web development
use is contacts.html: <p>Want to contact a specific staff member? Find details on our <a href="contacts.html">contacts page</a>.</p> Moving down into subdirectories: If you wanted to include a hyperlink inside index.html (the top level index.html) pointing to projects/index.html, you would need to go down into the projects directory before indicating the file you want to link to. This is done by specifying the directory's name, then a forward slash, then the name of the file. The URL you would use is projects/index.html: <p>Visit my <a href="projects/index.html">project homepage</a>.</p> Moving back up into parent directories: If you wanted to include a hyperlink inside projects/index.html pointing to pdfs/project-brief.pdf, you'd have to go up a directory level, then back do...
...you are currently on. The finished example should look similar to the following page: Note: If you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer. E-mail links It's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the <a> element and the mailto: URL scheme. In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example: <a href="mailto:nowhere@mozilla.org">Send email to nowhere</a> This results in a link that looks like this: Send email to nowhere. In fact, the email address is optional. If you omit it and your href is simply "m...
Document and website structure - Learn web development
navigate through a website. --> <form> <input type="search" name="q" placeholder="Search query"> <input type="submit" value="Go!"> </form> </nav> <!-- Here is our page's main content --> <main> <!-- It contains an article --> <article> <h2>Article heading</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p> <h3>Subsection</h3> <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, co...
...onec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p> <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p> <h3>Another subsection</h3> <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p> <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagit...
HTML text fundamentals - Learn web development
in a few seconds, they'll likely get frustrated and go somewhere else. Search engines indexing your page consider the contents of headings as important keywords for influencing the page's search rankings. Without headings, your page will perform poorly in terms of SEO (Search Engine Optimization). Severely visually impaired people often don't read web pages; they listen to them instead. This is done with software called a screen reader. This software provides ways to get fast access to given text content. Among the various techniques used, they provide an outline of the document by reading out the headings, allowing their users to find the information they need quickly. If headings are not available, they will be forced to listen to the whole document read out loud. To style content with CS...
...lly conveyed by underline: proper name, misspelling... A kind warning about underline: People strongly associate underlining with hyperlinks. Therefore, on the web, it's best to underline only links. Use the <u> element when it's semantically appropriate, but consider using CSS to change the default underline to something more appropriate on the web. The example below illustrates how it can be done. <!-- scientific names --> <p> The Ruby-throated Hummingbird (<i>Archilochus colubris</i>) is the most common hummingbird in Eastern North America. </p> <!-- foreign words --> <p> The menu was a sea of exotic words like <i lang="uk-latn">vatrushka</i>, <i lang="id">nasi goreng</i> and <i lang="fr">soupe a l'oignon</i>. </p> <!-- a known misspelling --> <p> Someday I'll learn how to ...
What’s in the head? Metadata in HTML - Learn web development
our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions. Open the HTML file in both your browser, and your text editor. By following the information given above, add <link> and <script> elements to your HTML, so that your CSS and JavaScript are applied to your HTML. If done correctly, when you save your HTML and refresh your browser you should be able to see that things have changed: The JavaScript has added an empty list to the page. Now when you click anywhere on the list, a dialog box will pop up asking you to enter some text for a new list item. When you press the OK button, a new list item will be added to the list containing the text. When you click on an...
...as added to the page (the red bar with the black border is the styling the CSS has added to the JS-generated list.) Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page. Setting the primary language of the document Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.) <html lang="en-US"> This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (...
Adding vector graphics to the Web - Learn web development
r the Web. Adding SVG to your pages In this section we'll go through the different ways in which you can add SVG vector graphics to your web pages. The quick way: <img> To embed an SVG via an <img> element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML. <img src="equilateral.svg" alt="triangle with all three sides equal" height="87" width="100" /> Pros Quick, familiar image syntax with built-in text equivalent available in the alt attribute. You can make the image into a hyperlink easily by nesting the <img> inside an <a> element. The SVG file can be cached by the browser, resulting in faste...
...the image is loaded. You may include fallback in a <foreignObject> element, but browsers that support SVG still download any fallback images. You need to weigh whether the extra overhead is really worthwhile, just to support obsolescent browsers. How to embed an SVG with an <iframe> You can open SVG images in your browser just like webpages. So embedding an SVG document with an <iframe> is done just like we studied in From <object> to <iframe> -- other embedding technologies. Here's a quick review: <iframe src="triangle.svg" width="500" height="500" sandbox> <img src="triangle.png" alt="Triangle with three unequal sides" /> </iframe> This is definitely not the best method to choose: Cons iframes do have a fallback mechanism, as you can see, but browsers only display the fallb...
Functions — reusable blocks of code - Learn web development
ndom()*number); } We needed this function because the browser's built-in Math.random() function only generates a random decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number. Invoking functions You are probably clear on this by now, but just in case ... to actually use a function after it has been defined, you've got to run -- or invoke -- it. This is done by including the name of the function in the code somewhere, followed by parentheses. function myFunction() { alert('hello'); } myFunction(); // calls the function once Anonymous functions You may see functions defined and invoked in slightly different ways. So far we have just created a function like so: function myFunction() { alert('hello'); } But you can also create a function that ...
...ript is set up like this for various reasons -- but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code -- external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be done maliciously, or just by accident. For example, say you have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a function defined that use the same name: <!-- Excerpt from my HTML --> <script src="first.js"></script> <script src="second.js"></script> <script> greeting(); </script> // first.js let name = 'Chris'; function greeting() { alert('...
Fetching data from the server - Learn web development
bute) -- so for example "Verse 1". The corresponding verse text file is "verse1.txt", and is in the same directory as the HTML file, therefore just the file name will do. However, web servers tend to be case sensitive, and the file name doesn't have a space in it. To convert "Verse 1" to "verse1.txt" we need to convert the V to lower case, remove the space, and add .txt on the end. This can be done with replace(), toLowerCase(), and simple string concatenation. Add the following lines inside your updateDisplay() function: verse = verse.replace(" ", ""); verse = verse.toLowerCase(); let url = verse + '.txt'; To begin creating an XHR request, you need to create a new request object using the XMLHttpRequest() constructor. You can call this object anything you like, but we'll call it r...
... Add the following below your last addition. You'll see that inside the onload event handler we are setting the textContent of the poemDisplay (the <pre> element) to the value of the request.response property. request.onload = function() { poemDisplay.textContent = request.response; }; The above is all set up for the XHR request -- it won't actually run until we tell it to, which is done using the send() method. Add the following below your previous addition to complete the function. This line should rest just above the closing curly brace of your updateDisplay() function. request.send(); One problem with the example as it stands is that it won't show any of the poem when it first loads. To fix this, add the following two lines at the bottom of your code (just above the ...
Introduction to web APIs - Learn web development
The gain node is then connected to the destination node so the sound can be played on your computer (the AudioContext.destination property represents whateve...
... to them are made in your code. As an example, the Notifications API asks for permission using a pop-up dialogue box: The Web Audio and HTMLMediaElement APIs are subject to a security mechanism called autoplay policy -- this basically means that you can't automatically play audio when a page loads -- you've got to allow your users to initiate audio play through a control like a button. This is done because autoplaying audio is usually really annoying and we really shouldn't be subjecting our users to it. Note: Depending on how strict the browser is, such security mechanisms might even stop the example from working locally, i.e. if you load the local example file in your browser instead of running it from a web server. At the time of writing, our Web Audio API example wouldn't work locally...
Third-party APIs - Learn web development
of the contents of a DOM element, in this case, the <section> element. We keep checking to see if the <section> has a first child, and if it does, we remove the first child. The loop ends when <section> no longer has any children. Next, we set the articles variable to equal json.response.docs -- this is the array holding all the objects that represent the articles returned by the search. This is done purely to make the following code a bit simpler. The first if() block checks to see if 10 articles are returned (the API returns up to 10 articles at a time.) If so, we display the <nav> that contains the Previous 10/Next 10 pagination buttons. If less than 10 articles are returned, they will all fit on one page, so we don't need to show the pagination buttons. We will wire up the pagination fun...
...objects contained the right data to show, we consulted the Article Search API reference (see NYTimes APIs). Most of these operations are fairly obvious, but a few are worth calling out: We used a for loop (for(var j = 0; j < current.keywords.length; j++) { ... } ) to loop through all the keywords associated with each article, and insert each one inside its own <span>, inside a <p>. This was done to make it easy to style each one. We used an if() block (if(current.multimedia.length > 0) { ... }) to check whether each article has any images associated with it (some stories don't.) We display the first image only if it exists (otherwise an error would be thrown). We gave our <div> element a class of "clearfix", so we can easily apply clearing to it. Wiring up the pagination but...
A first splash into JavaScript - Learn web development
checkGuess(); After pressing Return/Enter, you should see an alert come up that says "I am a placeholder"; we have defined a function in our code that creates an alert whenever we call it. Note: You'll learn a lot more about functions later in the course. Operators JavaScript operators allow us to perform tests, do math, join strings together, and other such things. If you haven't already done so, save your code, refresh the page in your browser, and open the developer tools JavaScript console. Then we can try typing in the examples shown below -- type in each one from the "Example" columns exactly as shown, pressing Return/Enter after each one, and see what results they return. First let's look at arithmetic operators, for example: Operator Name Example +...
...sses.style.padding = '10px'; guesses.style.boxShadow = '3px 3px 6px black'; Every element on a page has a style property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript. Finished for now... So that's it for building the example. You got to the end -- well done! Try your final code out, or play with our finished version here. If you can't get the example to work, check it against the source code. Previous Overview: First steps Next In this module What is JavaScript? A first splash into JavaScript What went wrong? Troubleshooting JavaScript Storing the information you need -- Variables Basic math in JavaScript -- numbers and operators H...
Useful string methods - Learn web development
ked at above: browserType[browserType.length-1]; The length of "mozilla" is 7, but because the count starts at 0, the character position is 6; using length-1 gets us the last character. Finding a substring inside a string and extracting it Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say if a substring is present inside a string). This can be done using the indexOf() method, which takes a single parameter -- the substring you want to search for. If the substring is found inside the main string, it returns a number representing the index position of the substring -- which character number of the main string the substring starts at. If the substring is not found inside the main string, it returns a value of -1. Try this: browserType.in...
...und inside the main string, it returns a value of -1. Try this: browserType.indexOf('zilla'); This gives us a result of 2, because the substring "zilla" starts at position 2 (0, 1, 2 -- so 3 characters in) inside "mozilla". Such code could be used to filter strings. For example, we may have a list of web addresses and only want to print out the ones that contain "mozilla". This can be done in another way, which is possibly even more effective. Try the following: browserType.indexOf('vanilla'); This should give you a result of -1 -- this is returned when the substring, in this case 'vanilla', is not found in the main string. You could use this to find all instances of strings that don't contain the substring 'mozilla', or do, if you use the negation operator, as shown below...
Object building practice - Learn web development
each ball's draw() and update() function to draw each one on the screen, then do the necessary updates to position and velocity in time for the next frame. Runs the function again using the requestAnimationFrame() method -- when this method is repeatedly run and passed the same function name, it runs that function a set number of times per second to create a smooth animation. This is generally done recursively -- which means that the function is calling itself every time it runs, so it runs over and over again. Last but not least, add the following line to the bottom of your code -- we need to call the function once to get the animation started. loop(); That's it for the basics -- try saving and refreshing to test your bouncing balls out! Adding collision detection Now for a b...
...hey are not the same. We then use a common algorithm to check the collision of two circles. We are basically checking whether any of the two circle's areas overlap. This is explained further in 2D collision detection. If a collision is detected, the code inside the inner if statement is run. In this case we only set the color property of both the circles to a new random color. We could have done something far more complex, like get the balls to bounce off each other realistically, but that would have been far more complex to implement. For such physics simulations, developers tend to use a games or physics library such as PhysicsJS, matter.js, Phaser, etc. You also need to call this method in each frame of the animation. Add the following below the balls[i].update(); line: balls[...
Test your skills: Object basics - Learn web development
ing the year the band split up, or false if they are still together. albums: An array representing the albums released by the band. Each array item should be an object containing the following members: name: A string representing the name of the album. released: A number representing the year the album was released. Include at least two albums in the albums array. Once you've done this, you should then write a string to the variable bandInfo, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Object basics 3 Fi...
...itor or in an online editor. Object basics 3 Finally for our object basics assessment, we want you to return to the cat object literal from Task #1. We want you to rewrite the greeting() method so that it logs "Hello, said Bertie the Cymric." to the browser DevTools' console, but in a way that will work across any cat object of the same structure, regardless of its name or breed. When you are done, write your own object called cat2, which has the same structure, exactly the same greeting() method, but a different name, breed, and color. Call both greeting() methods to check that they log appropriate greetings to the console. The code is not very DRY (each bit of code should only be defined once) -- you've got the same method defined twice, for example. Describe how you'd make it more DRY...
Aprender y obtener ayuda - Learn web development
olving the specific problems that it brings. You are focused on a narrow area. Diffuse learning is more to do with high-level thinking around a wider area. You let your mind wander more widely, and seemingly make random connections between different things. This is more the kind of thinking you do while you are in the shower, or during a coffee break. From the studies that neuroscientists have done on brain activity, we have found out that you can't really engage in both ways of learning -- or thinking -- at once. So which one should you choose? You might think that focused learning is better for studying, but in reality, both are very important. Focused thinking is great for concentrating hard on specific subjects, getting into deep problem solving, and improving your mastery of the techn...
...ch time you can spend on this of course depends on what your circumstances are. If you are at school, then you've got way more free time than if you have a job and children to provide for. It is still possible to achieve your goals, but you have to be realistic about how quickly you can do it. ...
Introduction to client-side frameworks - Learn web development
you to navigate back and forth, too. This is called server-side routing. Modern web applications typically do not fetch and render new HTML files -- they load a single HTML shell, and continually update the DOM inside it (referred to as single page apps, or SPAs) without navigating users to new addresses on the web. Each new pseudo-webpage is usually called a view, and by default, no routing is done. When an SPA is complex enough, and renders enough unique views, it's important to bring routing functionality into your application. People are used to being able to link to specific pages in an application, travel forward and backward in their navigation history, etc., and their experience suffers when these standard web features are broken. When routing is handled by a client application in t...
...ies will announce the title of the page. These things happen every time you navigate to a new page. With client-side routing, your browser is not loading new web pages, so it doesn't know that it should automatically adjust focus or announce a new page title. Framework authors have devoted immense time and labor to writing JavaScript that recreates these features, and even then, no framework has done so perfectly. The upshot is that you should consider accessibility from the very start of every web project, but bear in mind that abstracted codebases that use frameworks are more likely to suffer from major accessibility issues if you don't. How to choose a framework Each of the frameworks discussed in this module take different approaches to web application development. Each is regularly im...
React interactivity: Events and state - Learn web development
both in separate variables. Reading state You can see the name state in action right away. Add a value attribute to the form's input, and set its value to name. Your browser will render "Use hooks!" inside the input. <input type="text" id="new-todo-input" className="input input__lg" name="text" autoComplete="off" value={name} /> Change "Use hooks!" to an empty string once you're done; this is what we want for our initial state. const [name, setName] = useState(''); Reading user input Before we can change the value of name, we need to capture a user's input as they type. For this, we can listen to the onChange event. Let's write a handleChange() function, and listen for it on the <input /> tag. // near the top of the `Form` component function handleChange(e) { console.lo...
... function Form(props) { const [name, setName] = useState(""); function handleChange(e) { setName(e.target.value); } function handleSubmit(e) { e.preventDefault(); props.addTask(name); setName(""); } return ( <form onSubmit={handleSubmit}> <h2 className="label-wrapper"> <label htmlFor="new-todo-input" className="label__lg"> What needs to be done? </label> </h2> <input type="text" id="new-todo-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: Ad...
Beginning our React todo list - Learn web development
SS to style your app. ...
... We have a <form> element, with an <input type="text"> for writing out a new task, and a button to submit the form. We have an array of buttons that will be used to filter our tasks. We have a heading that tells us how many tasks remain. We have our 3 tasks, arranged in an un-ordered list. Each task is a list item (<li>), and has buttons to edit and delete it and a checkbox to check it off as done. The form will allow us to make tasks; the buttons will let us filter them; the heading and list are our way to read them. The UI for editing a task is conspicuously absent for now. That's okay - we'll write that later. Accessibility features You may notice some unusual attributes here. For example: <button type="button" className="btn toggle-btn" aria-pressed="true"> <span className="visu...
Starting our Svelte Todo list app - Learn web development
CSS, and JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: To learn how to create a Svelte component, render it inside another component, pass data into it using props, and save its state. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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,...
...r the moment we will start with a static markup representation of our app, so you can see what it will look like. ...
Working with Svelte stores - Learn web development
component. In this case, the Alert component is independent from the rest -- it is not a parent or child of any other -- so the messages don't fit into the component hierarchy. We will also see how to develop our own custom store to persist the todo information to web storage, allowing our todos to persist over page reloads. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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/...
... you don't implement stores from scratch; instead you'd use the writable store to create custom stores with domain-specific logic. In the following example we create a counter store, which will only allow us to add one to the counter or reset its value: import { writable } from 'svelte/store'; function myStore() { const { subscribe, set, update } = writable(0); return { subscribe, addOne: () => update(n => n + 1), reset: () => set(0) }; } If our To-do list app gets too complex, we could let our todos store handle every state modification. We could move all the methods that modify the todo array (like addTodo(), removeTodo(), etc) from our Todos component to the store. If you have a central place where all the state modification is applied, components could just call those ...
Getting started with Vue - Learn web development
locally so you can test it easily without needing to configure a server yourself. The CLI adds a serve command to the project's package.json file as an npm script, so you can easily run it. In your terminal, try running npm run serve (or yarn serve if you prefer yarn). Your terminal should output something like the following: INFO Starting development server... 98% after emitting CopyPlugin DONE Compiled successfully in 18121ms App running at: - Local: <http://localhost:8080/> - Network: <http://192.168.1.9:8080/> Note that the development build is not optimized. To create a production build, run npm run build. If you navigate to the "local" address in a new browser tab (this should be something like http://localhost:8080 as stated above, but may vary based on your setup)...
... you'd expect. Summary Let's leave this here for now. We've learnt about some of the ideas behind Vue, created some scaffolding for our example app to live inside, inspected it, and made a few preliminary changes. With a basic introduction out of the way, we'll now go further and build up our sample app, a basic Todo list application that allows us to store a list of items, check them off when done, and filter the list by all, complete, and incomplete todos. In the next article we'll build our first custom component, and look at some important concepts such as passing props into it and saving its data state. Previous Overview: Client-side JavaScript frameworks Next In this module Introduction to client-side frameworks Framework main features React Getting started with ...
Focus management with Vue refs - Learn web development
The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using Vue refs to handle this -- an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component. Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line. ...
...nts directly through native browser APIs (like Document.getElementById) when using frameworks, because it results in the VDOM and real DOM going out of sync. Instead, if you need to access the underlying DOM nodes (like when setting focus), you can use Vue refs. For custom Vue components, you can also use refs to directly access the internal structure of a child component, however this should be done with caution as it can make code harder to reason about and understand. To use a ref in a component, you add a ref attribute to the element that you want to access, with a string identifier for the value of the attribute. It's important to note that a ref needs to be unique within a component. No two elements rendered at the same time should have the same ref. Adding a ref to our app So, let's...
Implementing feature detection - Learn web development
ecent versions of Safari/iOS WebKit (9+/9.2+), whereas the JavaScript version should work in much older browsers (probably back to IE8 or 9, although older versions of IE will have additional problems, such as not supporting Document.querySelector, and having a messed up box model). JavaScript We already saw an example of a JavaScript feature detection test earlier on. Generally, such tests are done via one of the following common patterns: Summary of JavaScript feature detection techniques Feature detection type Explanation Example If member in object Check whether a certain method or property (typically an entry point into using the API or other feature you are detecting for) exists in its parent Object. if("geolocation" in navigator) { ... } ...
...odernizr.flexbox Modernizr.websqldatabase Modernizr.xhr2 Modernizr.fetch The console will return true/false values to indicate whether your browser supports those features or not. Let's look at an example to show how you'd use those properties. First of all, make a local copy of the modernizr-js.html example file. Attach the Modernizr library to the HTML using a <script> element, as we have done in previous demos. Put it above the existing <script> element, which is attaching the Google Maps API to the page. Next, fill in the YOUR-API-KEY placeholder text in the second <script> element (as it is now) with a valid Google Maps API key. To get a key, sign in to a Google account, go to the Get a Key/Authentication page, then click the blue Get a Key button and follow the instructions. Fina...
Package management basics - Learn web development
r will seamlessly handle installing and uninstalling packages. If you didn't use one, you'd have to manually handle: Finding all the correct package JavaScript files. Checking them to make sure they don't have any known vulnerabilities. Downloading them and putting them in the correct locations in your project. Writing the code to include the package(s) in your application (this tends to be done using JavaScript modules, another subject that is worth reading up on and understanding). Doing the same thing for all of the packages' sub-dependencies, of which there could be tens, or hundreds. Removing all the files again if you want to remove the packages. In addition, package managers handle duplicate dependencies (something that becomes important and common in front-end development). ...
...ple npm package to learn about using npm", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Chris Mills", "license": "ISC" } So this is the config file that defines your package. This is good for now, so let's move on. 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). First of all however, take another look at your package.json file. You'll see that npm has added a new field, dependencies: "dependencies": { "parcel-bundler": "^1.12.4" } This is part of the npm magic -- if in future you move your ...
Adding a new CSS property
by default or only properties that do not. (Which set the property is in is given in the specification, which says "Inherited: yes" or "Inherited: no" in the property's definition.) Also note that some of the style structs intentionally contain only properties set/reset by a particular common shorthand property; this improves the effectiveness of some of the performance and memory optimizations done with the rule tree, and thus we should avoid adding a property not reset by that shorthand to such a struct. Once you know which struct you're going to use (or that the property is a shorthand), you can add appropriate entry to nsCSSPropList.h. Again, see the documentation at the top of the file and the other entries for examples, and also see the next section for details about parsing. Parsin...
...new property is interpolated (as its specification should describe), then you'll need to implement a new behavior type in nsStyleAnimation and reference it from nsCSSPropList.h. This should probably be in a separate patch from the basic addition of the property. Finishing up Then you'll need to rebuild and run the mochitests in layout/style (./mach mochitest -f plain layout/style/). If you've done everything right, they should pass; if they don't, you need to fix something. Then you should get review on the work you've done so far and move on to implementing whatever the property does (which should be in a separate patch or patches). ...
Debugging a hang on OS X (Archived)
ll the latest Computer Hardware Understanding Development (CHUD) Tools from Apple). By default, sampling of any hanging application will begin automatically. After about 3-4 seconds, select the hanging application in the "Detected Hangs" window and click the "Interrupt Sampling" button. Note that sampling will quickly hog up a lot of memory if you leave it on for too long! When it's done parsing the data, click the "Show text report" button; a new window will open with a couple of rows with stacktraces for all the threads in the sampled application. If you need to upload the sample to Bugzilla, select all the sample text, copy it into your favorite text editor, and save as a plain-text file. For a more detailed view of the sample data, make sure the sample you just recorded is ...
...rmance Tools/</tt> folder; if it is missing, install the latest Computer Hardware Understanding Development (CHUD) Tools from Apple.). Choose File > Attach... Select "firefox-bin" or the hung application you want a sample from. Now, click "Start recording". Note that only 3-4 seconds usually suffice, note that this will quickly hog up a lot of memory if you leave it on for too long! When it's done parsing the data, you should now have a couple of rows with stacktraces for all the threads in the sampled application. When you have the raw Sample data, you can't just save that and attach it to a bug, because the format is not very usable (unless the developer is a Mac hacker). Export it using Tools > Generate Report, and attach this as a text file to the bug report. The final data will sho...
Makefiles - Best practices and suggestions
Do not use directories as a dependency for generated targets, ever. Any activity within a directory will alter inodes forcing targets to always be stale. For ex, individual unit tests would invalidate all prior test activity whenever a test touched a timestamp file in the directory to signal success. ...
...success. Parallel make: add an explicit timestamp dependency (.done) that make can synchronize threaded calls on to avoid a race condition. # Transient directory for storing timestamps TS=.ts ##################################################### ## Extra dep needed to synchronize parallel execution ##################################################### $(TS): $(TS)/.done $(TS)/.done: $(MKDIR) -p $(dir $@) touch $@ # "clean" target GARBAGE_DIRS += $(TS) Maintain clean targets - makefiles should be able to remove all content that is generated so "make clean" will return the sandbox/directory back to a clean state. targets = foo bar tans timestampDIR = .ts all: $(timestampDIR) $(targets) %: %.c $(CC) -o $@ $< $(timestampDIR): $(MKDIR) $@ # "cl...
How Mozilla's build system works
e spent roughly 25% of the time waiting on I/O. Phase 3: Invocation of the Build Backend When most people think of the build system, they think of Phase 3. This is where we take all the code in the tree and produce the Firefox binary program file or the application you are creating. Phase 3 effectively takes whatever was generated by Phase 2 and runs it. Since the dawn of Mozilla, this has been done with the make tool, consuming makefiles. However, with the transition to moz.build files, you may eventually see non-make build backends, such as Tup or Visual Studio. When building the tree, most of the time is spent in Phase 3. This is when header files are installed, C++ files are compiled, files are preprocessed, and so on. Recursive Make Backend The recursive make backend is the tried-and...
... installed, C++ files are compiled, files are preprocessed, and so on. Recursive Make Backend The recursive make backend is the tried-and-true backend used to build the tree. It's what's been used since the dawn of Mozilla. Essentially, there are makefiles in each directory. make starts processing the makefile in the root directory and then recursively descends into child directories until it's done. But there's more to the process than that. The recursive make backend divides the source tree into tiers. A tier is a grouping of related directories containing makefiles of their own. For example, there is a tier for the Netscape Portable Runtime (nspr), one for the JavaScript engine, one for the core Gecko platform, one for the XUL app being built, and so on. The main moz.build file defines ...
Eclipse CDT
Mac is really horrible. If you use Mac, you may want to build the latest FSF version of GDB and set Eclipse to use that GDB for debugging. One suggested configuration for building GDB is '--prefix="$HOME" --disable-debug --with-python=/usr' (create an optimized build with support for Python (so that you can use python to much better control when you break etc.), and install it in $HOME/bin). That done, open the workspace preferences, select "C/C++ > Debug > GDB", and set "GDB Debugger" to the full path of your new gdb executable. GDB unexpectedly detaching If GDB starts ignoring your breakpoints, or unexpectedly terminates or detaches from the Firefox process, this may be caused by out of date breakpoints (breakpoints that you set during a previous debug session, after which you've since reb...
...ings you can try: Select your project in the Project Explorer, then from the context menu select "Index > Search for Unresolved Includes". For problematic source files, select the file in the Project Explorer and from the context menu select "Index > Create Parser Log File". Select your project in the Project Explorer, then from the context menu select "Index > Rebuild". When the indexing is done, open the log using "Window > Show View > Other > General > Error Log" and check the summary and look for exceptions. Searching Free text search is not backed by a database, so it is extremely slow. Furthermore, the results are not saved so if you immediately search for the exact same text again without any changes to the source files having occurred, Eclipse will do a slow search all over aga...
Eclipse CDT Manual Setup
e. For now it's stored here until that integration happens in order that the Eclipse CDT page isn't hugely cluttered with mostly redundant information, make setting up Eclipse look much more complicated than it is nowadays. Setup time Some points in the rest of this document below are old and taken care of by the mach commands described above (although some of the project configuration is not done automatically yet). Some of it like the section on building the index and usage tips are still relevant, and other parts still may provide useful background information to understand it in more detail on how Eclipse works. You can expect it to take an hour or so to work through these instructions if you're doing so for the first time. (This assumes that you already have a copy of the Mozilla s...
...t-mozilla-build.py'). If you don't put just-print-mozilla-build.py somewhere in your PATH, then go back to the Initial project properties section where you set just-print-mozilla-build.py and specify its absolute path instead of just its name. Now invoke the script by clicking the Build button (the button with the hammer symbol) or by selecting "Project > Build Project" from the main menu. That done, select the "Console" tab at the bottom of the main Eclipse window and you should see the build console output flying by as Eclipse processes it. It should take about 5-10 minutes for Eclipse to finish processing the output. Additional discovery for C++11 mode As of Mozilla 25, Mozilla is built in C++11 mode. When GCC is invoked in C++11 mode, it defines pre-processor symbols that enable condit...
Multiple Firefox profiles
ion is not lost. "Don't Delete Files" is the preferred option, because it saves the old profile's folder, allowing you to recover the files to a new profile. Delete Files removes the profile and its files, including the profile bookmarks, settings, passwords, etc. Warning: If you use the "Delete Files" option, the profile folder, and files will be deleted. This action cannot be undone. Cancel interrupts the profile deletion. Renaming a profile In the Profile Manager, select the profile you want to rename, and then click "Rename Profile". Enter a new name for the profile and click on OK. Note: The folder containing the files for the profile is not renamed. Options Work offline Choosing this option loads the selected profile, and starts Firefox offline. You...
... "Target" text field that you can edit, and it should show the current file path. To permanently set a specific profile, add -p PROFILE_NAME to the target path, but outside of the quotes, replacing "PROFILE_NAME" with the actual profile name you chose. If you would also like to allow multiple instances of Firefox to run at the same time, add -no-remote after the profile name. Once you are all done, click Ok. Do this for each icon you'd like to have a specific profile for. Once done, each one should automatically start with the specified profile. Linux There is no extremely straightforward way to create custom application launchers in Gnome 3 like there was in Gnome 2. The following tutorial will help get you going overall: Gnome 3 Custom application launcher. Once you get to the point of...
Performance best practices for Firefox front-end engineers
lso important to note that most of our JavaScript runs on the main thread, so it's easy for script to cause delays in event processing or painting. That means that the more code we can get off of the main thread, the more that thread can respond to user events, paint, and generally be responsive to the user. You might want to consider using a Worker if you need to do some computation that can be done off of the main thread. If you need more elevated privileges than a standard worker allows, consider using a ChromeWorker, which is a Firefox-only API which lets you create workers with more elevated privileges. Use requestIdleCallback() If you simply cannot avoid doing some kind of long job on the main thread, try to break it up into smaller pieces that you can run when the browser has a free ...
...move all DOM writes into requestAnimationFrame(), then we can be sure that all size and position queries are cheap. It's also possible (though less infallible than promiseDocumentFlushed) to queue JavaScript to run very soon after the frame has been painted, where the likelihood is highest that the DOM has not been written to, and layout and style information queries are still cheap. This can be done by using a setTimeout or dispatching a runnable inside a requestAnimationFrame callback, for example: requestAnimationFrame(() => { setTimeout(() => { // This code will be run ASAP after Style and Layout information have // been calculated and the paint has occurred. Unless something else // has dirtied the DOM very early, querying for style and layout information // here shoul...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
nd next buttons, set searchActive to true, and blur() the search bar to make the keyboard disappear and stop taking up our screen once the search is submitted. ...
...rs do: prev.addEventListener('touchend',function() { browser.findNext("backward"); }); next.addEventListener('touchend',function() { browser.findNext("forward"); }); The last event listener in this section controls what happens when the search toggle button is pressed. We switch the class values on the element to toggle the show/hide. If searchActive is true, meaning that a search has been done, we want to disable the search as we hide the search options -- we disable the buttons, make searchActive false, clear the entered search value, and run HTMLIFrameElement.clearMatch(), which gets rid of any stored/highlighted search results from the browser. searchToggle.addEventListener('touchend',function() { if(search.getAttribute('class') === 'search') { search.setAttribute('class', 's...
Overview of Mozilla embedding APIs
s: nsIServiceManager Related Interfaces: nsIShutdownListener nsMemory The nsMemory service provides the global memory manager implementation for XPCOM. In addition to memory allocation and release, this service provides low memory notifications, called a memory pressure observers, which are notified when memory is low - thus allowing cached resources to be freed. All heap access should be done via the nsMemory service. To facilitate this, a set of global functions are available to access the nsMemory methods without requiring an instance of the nsMemory service (see nsMemory.h). Contract-id: NS_MEMORY_CONTRACTID Implemented Interfaces: nsIMemory Related Interfaces: nsIObserver nsComponentManager The nsComponentManager service is responsible for creating new instances of XPCOM c...
...Browser The nsWebBrowser is the main embedding component which Gecko exposes. Conceptually, each nsWebBrowser instance represents a HTML content area. Conceptually, for each document being rendered, Gecko creates a container called a DOMWindow. Each WebBrowser exposes a tree of DOMWindows - representing the frame hierarchy for the current document. As such, access to individual document frames is done via the DOMWindow interfaces. Manipulation of the entire document structure is done via the various WebBrowser interfaces. Contract-id: NS_WEBBROWSER_CONTRACTID Implemented Interfaces: nsIWebBrowser nsIWebNavigation nsIWebBrowserSetup nsIWebBrowserPersist nsIWebBrowserFind nsIWebBrowserPrint nsIWebBrowserFocus nsIBaseWindow Requestor Interfaces: nsIDOMWindow nsIDOMDocument ...
Embedding the editor
or and the UI needs to go through one or more interfaces that insulate the editor from its host application. (The current nsEditorShell makes assumptions about the hosting XUL document, which need to be broken.) Composer embedded in a web page (<htmlarea>) IE 5 supports the <HTMLArea> element; if Mozilla is to support something similar, editor needs to be embeddable to the extent that this can be done. It is likely that we'd use XBL to implement this type of widget, as is the plan for other form controls. As is the case for composer embedded in a native application, there is a requirement here that the composer UI be configurable, such that it can be displayed either as a toolbar at the top of the <htmlarea>, a floating palette, or a top-level toolbar. Current problems The current composer arc...
...'d have an implementation in JS that talks to the existing commands, and updates the XUL nodes. Fix existing JS and C++ code which explicitly addresses elements in the XUL document to go through nsIEditorUserInterface. Steps to embedding This section attempts to lay out an implementation plan, with the aim of keeping everything working as the various steps are taken. Some of these tasks can be done concurrently. Decide on how to implement editing session multiple-editor support Eliminate specific interdependencies between Composer and the XUL document, via nsIEditorUserInterface Create bottleneck for getting to the focussed editor; ensure that focus changes update state Move editor ownership to docShell, creating nsIEditorFrame Created the editing session API which copes with col...
Roll your own browser: An embedding how-to
Warning: This document is out of date. You should instead build XULRunner and use it for all new embedding. You should not need to, and should not, use embedding/config. What bits do I need? One of the requirements of building a SDK is the ability to identify and package up required files. Like that isn't totally obvious, nonetheless it has to be done. Here is that effort. I have created a directory under embedding called config. Contained within this directory are a couple of makefiles: basebrowser-unix basebrowser-win The XPInstall packager follows the same format. However in our case, we only have one named XPI package. After the build is done, you can change directory into mozilla/embedding/config, and do a make. This will produce a directory in DIST named Embed. It should...
...is will produce a directory in DIST named Embed. It should include all of the base support that you need to get a web browser started up. Included is the sample test application (gtkEmbed or winEmbed). What initializations do I have to do? Somewhere during the start of your application, you must initialize XPCOM. You will also want to shut this down when you quit. Other initialization must be done to start up event queues and load some string bundles. All of this is somewhat generic and has been isolated into a static library that you can simply call on. If you build mozilla/embedding/base/, a static library (on windows) called baseembed_s.lib is built. Just link this library to your application. There are two functions that are needed: nsresult NS_InitEmbedding(const char *aPath); nsres...
Gecko SDK
image not found Trace/BPT trap Unfortunately, this is caused by a problem with the SDK build process which cannot currently be resolved (see Bugzilla bug #430274). To get around it, you'll need to first install MacPorts as outlined in the Mac OS X Build Prerequisites and install libidl with it. On 64-bit versions of Mac OS X, you'll need to install libidl with the +universal flag. Once that's done, you should perform the following command: ln -s /opt/local/lib/libintl.8.dylib /opt/local/lib/libintl.3.dylib This should fix the problem. Building the SDK To build the SDK, you should build XULRunner (the Gecko SDK is built as part of the XULRunner build process, which is why it's sometimes called the XULRunner SDK). See the Build Documentation for complete details. After the XULRunner buil...
..., XPCOM functions, and NSPR functions (under include/) Import libraries or shared libraries (under lib/) Static utility libraries (under lib/) Various tools (under bin/) For more information about safely linking XPCOM components using the XPCOM "glue" library, see XPCOM Glue. Using the Mozilla Build System with the SDK It's possible to use the Mozilla Build System with the SDK. This can be done by downloading the source code for Firefox and using the --with-libxul-sdk option to configure. Resources static xpidl.exe (non-official) If you are looking for a static linked xpidl.exe, you can download here. Mac Intel Gecko 1.8 SDK The official Mac 1.8 SDK is a ppc version. This is an unofficial intel build. ...
How Mozilla determines MIME Types
ted at netwerk/streamconv/converters/nsUnknownDecoder.cpp, the interesting part starts at line 287, the sSnifferEntries array together with the DetermineContentType function. It does the following: Checks the start of the file for "magic numbers"; this can currently detect PDF and Postscript. If the file starts with <?xml, asks the ExternalHelperAppService for a MIME type for the URI. This is done because the generic text/xml MIME type does not work for XUL files, and XHTML files get a different DOM when interpreted as text/xml. The Image Library will be asked for the MIME type given the content. This should allow reliable detection of all image types Mozilla supports. Checks whether the data is HTML by looking for some common HTML tags. The URI is handed to the ExternalHelperAppService...
...Firstly, the Operating System is asked for a MIME type. (On Unix, this means checking mime.types.) If that fails, a user-supplied helper app is searched for by extension, and the specified MIME type will be used. (i.e. the list i...
Implementing Download Resuming
s feature. Not only is the ability to specify a start position important, but it's also important to have some assurance that the file did not change since the initial download attempt. That would lead to a situation where the first part of the file corresponds to the initial version, while the latter part belongs to a different version, leading to an unusable result. The interface Resuming is done using the nsIResumableChannel interface. The expected way to use it is this: For all downloads that happen, get the entityID from the channel, and store it for later use. The entity ID is what ensures that the file remains unchanged. This can also be used to check whether the download is resumable: if it is not (e.g. the server is not using HTTP 1.1), then accessing this attribute will throw a...
...open the channel as usual (using nsIChannel.asyncOpen() in the common case) and write to the file in the onDataAvailable notifications. You may want to use nsISimpleStreamListener to simplify this task; to get progress notifications, you can implement nsIProgressEventSink and set an interface requester as the notificationCallbacks of the channel that gives out such an event sink (this needs to be done before calling asyncOpen). Note: In versions of Firefox prior to 3.0 alpha 7, nsIWebBrowserPersist cannot append to existing files (as opposed to overwriting them), and is therefore not usable for this task (see bug 129921). Detecting when a file changed If the file changed (that is, the entity ID does not match), then Necko will notify the stream listener with an NS_ERROR_ENTITY_CHANGED error...
Examples
console.log(exists ? "You have .mozconfig in " + currentDir : "You don't have .mozconfig in " + currentDir); }); }).then(null, Components.utils.reportError); Parallel promise (THIS EXAMPLE NEEDS MORE WORK) So when chaining promises, consequent promises run after the previous promise completes. Now what if we want to run multiple promises and then return when all are done? This is accomplished by using Promise.all, this feature requires Promise.jsm. const {Cu} = require("chrome"); const {TextDecoder, TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {}); /* files: An array of file paths */ function readTextFiles(files) { let promises = [], decoder = new TextDecoder(); for (let i = 0; i < files.length; i++) { let promise = OS.File.re...
..."read.me"), Os.Path.join(folder, "home.html") ]); promise.then( function onSuccess(filesContent) { // filesContent is an array of strings; each string is the content of one file. console.log(filesContent); }, function onFail() { console.error("Failed to load all files"); } ); See also the ask.m.o topic: Doing multiple promises in function in pareallel, how return when last done? Simple Example User Defined Promise Function 2 Whenever you want to make a function a promise. Always wrap that function in a try catch and make that catch return Promise.reject(ex) otherwise it will not trigger the rejection function of the promise.then. This way if any error happens it will reject the promise. In the example below we try alerting an undefined variable. Components.utils.impo...
Bootstrapping a new locale
sion. For instance, for Firefox 3.6, we use mozilla-1.9.2. Refer to L10n:Branches for the list of all branches. If you are interested in localizing Thunderbird 3, SeaMonkey 2 or other Mozilla projects based on Gecko 1.9.1 you'll need to follow the instructions on getting the source-code of the comm-central repository. Create a bare-bones localization Next, create a base localization. This is done by cloning the en-US (United States English) files into your localization. First, you should specify your locale's language identifier in ab-CD format, where "ab" is the ISO 639 language code, and CD is the ISO 3166 country code. The "-CD" part is only necessary to differentiate between versions of a language that are subtly different from country to country, such as in "en-US" and "en-GB" for ...
...uide on where to start and in what order to proceed through translation. The localization phase lists (Firefox 3.5: ff35.phaselist, Firefox 3.6: ff36.phaselist). Description of phases. Land your translated files one by one, making sure it follows the *mozilla-1.9.2* structure. This will familiarize you with our "Hg" commands and will get us something that we can import easily when you are done. Working with Bit Bucket Before a team becomes official, we like to get the localizers comfortable with the Hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository. We use a web service called Bit Bucket to start the learning process. To begin, contact the l10n-drivers to let them know that you are interested in starting a localization. The l10...
Localizing with Mercurial
o manage patches. Mercurial account priviledges Eventually, you or your team leader will need Hg account priviledges. Let's face it, it's just more convenient to commit and push your work to the remote repo yourself, rather than creating patches and asking someone else to push them for you. To get write access to the l10n hg repositories on the Mozilla server, there's a bit of paper work to be done. The localization team owner needs to file a bug requesting an hg account. This bug will request level 1 L10n priviledges. You need to follow the instructions regarding the contributor form. Write access to the hg repositories requires a ''voucher'', which, for the owner, will be done based on the review by Mozilla. For peers of a localization, the owner can vouch (once she or he is registered). ...
...Take a break and grab a snack, you deserve it ...
Localizing without a specialized tool
age pack or a binary file that is ready for installation. Repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version. If you choose to localize Mozilla with nothing more than a text editing application and not a specialized tool, this document (along with Create a New Localization) will enable you to learn just what needs to be done. Before we start, did you make sure to install Mercurial and confirm that you have set up the proper build environment on your local machine? You cannot begin localizing Mozilla file by file without a specialized tool without going through the Create a New Localization page. What we will translate We will translate a small piece of the UI found in the search bar. The search bar is next to the ri...
... ...
Localization sign-off reviews
every user who downloads your localized Mozilla application receives all of your hard work in a functional product. Each QA review helps us in these ways: Ensures that your L10n work is visible and functional within the Mozilla application. Allows us to understand how each L10n team is performing their localization work. Allows us to discover potential bugs within L10n tools. Overview You've done some localization work and are ready for it to be released. The merge date for migrating from one product release channel to the next is rapidly approaching. You need to make sure that your work can effectively be compiled into a build for the next release channel. Here is a detailed overview of what a sign-off review is and who it's meant for: A sign-off review: is performed as a QA measure fo...
...m one product release channel to the next is rapidly approaching. You need to make sure that your work can effectively be compiled into a build for the next release channel. Here is a detailed overview of what a sign-off review is and who it's meant for: A sign-off review: is performed as a QA measure for maintaining a localization from release-to-release. only evaluates new L10n work. This is done by generating a diff between the new release revision being considered and the previously approved release revision. focuses on technical accuracy and completion of L10n work, not translation quality. evaluates new release revisions, not entire L10n repos. does not need to be approved before revision merge between release channels, although it is recommended. Sign-off review criteria Since th...
What every Mozilla translator should know
zilla.com), Pike on IRC Another interesting way of getting help is the IRC channel #l10n at irc.mozilla.org Useful Tools The L10n Dashboard Pontoon Narro Translate Toolkit Koala 0.1 MozillaTranslator Mercurial The hg is organized into several repositories, sometimes called branches. We have the main repository called mozilla-central (or trunk) where the day to day developing work is done. When a development is started for an specific version, a new repository is created under hg.mozilla.org/releases/. All the content of the trunk is copied to this new branch so that the developing work is done in two (or more) parallel places: the generic trunk and the version oriented branch(es). For every branch and every locale, there is a separate repository for localization files committed b...
... committed, put the bug in FIXED state and write fixed1.8.xxx in the keyword field You have to verify in the next build that the changes have been successful. If so, change the state of the bug to VERIFIED and write verified1.8.xxx in the keyword field Tinderbox In Tinderbox you can see the result of the build process. Once you have made some changes in Mercurial, as soon as the next build is done you can check the Tinderbox and see if something was wrong. l10n Tinderbox When the color is green, it means that the build process has finished with no errors. In this case the resultant installable file will be available in the Mozilla FTP servers: Firefox Nightly Builds Thunderbird Nightly Builds QA (Quality Assurance) In order to assure the quality of a build we should make some t...
Investigating leaks using DMD heap scan mode
using the DMD heap scan logs is to do some pre-processing for the DMD log. Stacks need to be symbolicated, and we need to clamp the values contained in the heap. Clamping is the same kind of analysis that a conservative GC does: if a word-aligned value in a heap block points to somewhere within another heap block, replace that value with the address of the block. ...
...a word-aligned value in a heap block points to somewhere within another heap block, replace that value with the address of the block. Both kinds of preprocessing are done by the dmd.py script, which can be invoked like this: $objdir/dist/bin/dmd.py --clamp-contents dmd-$pid.log.gz This can take a few minutes due to symbolification, but you only need to run it once on a log file. After that is done, we can finally find out which objects (possibly) point to other objects, using the block_analyzer script: python $srcdir/memory/replace/dmd/block_analyzer.py dmd-$pid.log.gz $leakaddr This will look through every block of memory in the log, and give some basic information about any block of memory that (possibly) contains a pointer to that object. You can pass some additional options to affect...
Leak-hunting strategies and tips
ts. Seeing a leaked GlobalWindowImpl, nsXULPDGlobalObject, nsXBLDocGlobalObject, or nsXPCWrappedJS is a sign that there could be significant numbers of JS objects leaked.) For example, start with bringing up the mail window and closing the window without doing anything. Then go on to selecting a folder, then selecting a message, and then other activities one does while reading mail. Once you've done this, and it doesn't leak much, then try the action under trace-malloc or LSAN or Valgrind to find the leaks of smaller graphs of objects. (When I refer to the size of a graph of objects, I'm referring to the number of objects, not the size in bytes. Leaking many copies of a string could be a very large leak, but the object graphs are small and easy to identify using GC-based leak detection.) Wh...
...lancer or diffbloatdump.pl --use-address for trace-malloc) andthen run the balance trees (which are much smaller) through the post-processing. Getting symbol information for system libraries Windows Setting the environment variable _NT_SYMBOL_PATH to something like symsrv*symsrv.dll*f:\localsymbols*http://msdl.microsoft.com/download/symbols as described in Microsoft's article. This needs to be done when running, since we do the address to symbol mapping at runtime. Linux Many Linux distros provide packages containing external debugging symbols for system libraries. fix_stacks.py uses this debugging information (although it does not verify that they match the library versions on the system). For example, on Fedora, these are in *-debuginfo RPMs (which are available in yum repositories tha...
Measuring performance using the PerfMeasurement.jsm code module
code section we want to measure. Since we enable monitoring immediately before calling code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured. The monitor object automatically accumulates counts over start/stop cycles (that is, it doesn't automatically zero the counters each time you start recording). ...
...u're done benchmarking, you can read out each of the counters you asked for as properties: let report = "CPU cycles: " + monitor.cpu_cycles + "\n" + "Cache refs: " + monitor.cache_references + "\n" + "Cache misses: " + monitor.cache_misses + "\n"; monitor.reset(); alert(report); The reset() method clears all of the enabled counters, as you might expect. When you're done with your measurements, just let the monitor object go out of scope. ...
AsyncTestUtils extended framework
This is likely to happen when I/O is involved or a potentially expensive process wants to break itself up into smaller chunks (like a search operation) so that the UI stays responsive. In the Mozilla platform, the "top level" of a program is the event loop. It is a never-ending loop that dequeues pending events an...
...continue executing without stopping. A function that does not return anything (or returns undefined) and is not a generator is treated like a function that returned true. Most of the things you will want to do already have helper functions that take care of all of this, so all you need to do is pass their return values through. For example, you would do "yield async_move_messages(...);" and be done with it. Helpers for the Asynchronous Function Contract It can be annoying to have to write interface boilerplate just to call async_driver. If you have the following types of listeners you can use the following pre-defined helpers: nsIUrlListener: asyncUrlListener (predefined). If you need to wrap an existing url listener or need a callback or fancy promise, create an instance of AsyncUrlLi...
Introduction to NSPR
is the sum of the other two. Expressed mathematically, the invariant is sum = v1 + v2. Any modification of v1 or v2 requires modification of sum. Since that is a complex operation, it must be monitored. Furthermore, any type of access to sum must also be monitored to ensure that neither v1 nor v2 are in flux. Note: Evaluation of the invariant expression is a conceptual requirement and is rarely done in practice. It is valuable to formally define the expression during design, write it down, and adhere to it. It is also useful to implement the expression during development and test it where appropriate. The thread makes an absolute assertion of the expression's evaluation both on entering and on exiting the monitor. Acquiring a lock is a synchronous operation. Once the lock primitive is calle...
...anism for indicating that something has changed. It is the programmer's responsibility to associate a condition with the state of the data. A thread may be designed to wait for a particular situation to exist in some monitored data. Since the nature of the situation is not an attribute of the condition, the program must test that itself. Since this testing involves the monitored data, it must be done from within the monitor. The wait operation atomically exits the monitor and blocks the calling thread in a waiting condition state. When the thread is resumed after the wait, it will have reentered the monitor, making operations on the data safe. There is a subtle interaction between the thread(s) waiting on a condition and those notifying it. The notification must take place within a monitor--...
FIPS Mode - an explanation
l want to use it in a way that is fully conformant with all the relevant FIPS regulations. Some other governments have also adopted many of the FIPS regulations, so their applicability is somewhat wider than just the US government's personnel. What is "FIPS Mode"? One of the FIPS regulations, FIPS 140, governs the use of encryption and cryptographic services. It requires that ALL cryptography done by US government personnel MUST be done in "devices" that have been independently tested, and certified by NIST, to meet the extensive requirements of that document. These devices may be hardware or software, but either way, they must function and behave as prescribed. So, in order for Mozilla Firefox and Thunderbird to be usable by people who are subject to the FIPS regulations, Mozilla's cryp...
...ed to enter the master password to visit ordinary https servers, nor to view certificates he has previously stored. In non-FIPS mode, NSS is willing and able to use popular non-FIPS approved cryptographic algorithms, such as RC4 and MD5, to communicate with older https servers. NSS divides its operations up into two "devices" rather than just one. One device does all the operations that may be done without needing to authenticate, and the other device stores the user's certificates and private keys and performs operations that use those private keys. How do I put Firefox into FIPS Mode? Instructions for how to configure Firefox into FIPS mode may be found on support.mozilla.com. Some third-parties distribute Firefox ready for FIPS mode, a partial list can be found at the NSS wiki. ...
NSS Sample Code sample2
err %d)\n", PR_GetError()); goto out; } /* NSS passes blobs around as SECItems. These contain a pointer to * data and a length. Turn the raw key into a SECItem. */ keyItem.type = siBuffer; keyItem.data = gKey; keyItem.len = sizeof(gKey); /* Turn the raw key into a key object. We use PK11_OriginUnwrap * to indicate the key was unwrapped - which is what should be done * normally anyway - using raw keys isn't a good idea */ SymKey = PK11_ImportSymKey(slot, cipherMech, PK11_OriginUnwrap, CKA_ENCRYPT, &keyItem, NULL); if (SymKey == NULL) { fprintf(stderr, "Failure to import key into NSS (err %d)\n", PR_GetError()); goto out; } /* set up the PKCS11 encryption paramters. * when not using CBC mode, iv...
...buf1 len must be atleast (data len + 8) */ tmp1_outlen = tmp2_outlen = 0; /* Create cipher context */ EncContext = PK11_CreateContextBySymKey(cipherMech, CKA_ENCRYPT, SymKey, SecParam); rv1 = PK11_CipherOp(EncContext, buf1, &tmp1_outlen, sizeof(buf1), data, strlen(data)+...
nss tech note4
Also, this document does not attempt to be an exhaustive survey of all possible ways to do a certain task; it merely tries to show a certain way. ...
...rver, this will get you the client's cert handle IF client auth is enabled CERTCertificate* cert = SSL_LocalCertificate(PRFileDesc *fd); If SSL client, this will get you the client cert's handle, IF client auth happened If SSL server, this will get you the server's cert handle Don't forget to clean up the cert handle when you're done with it void CERT_DestroyCertificate(CERTCertificate *cert); Some info is readily available cert->subjectName (char*) cert->issuerName (char*) cert->emailAddr (char*) OR char *CERT_GetCertificateEmailAddress(CERTCertificate *cert); cert->keyUsage (unsigned int) To break the issuer and subject names into component...
nss tech note5
http://www.mozilla.org/projects/security/pki/nss/ You can browse the NSS source online at http://lxr.mozilla.org/mozilla/source/security/nss/ and http://lxr.mozilla.org/security/ Be sure to look for sample code first for things you need to do. Note: This document contains code snippets that focus on essential aspects of the task and often do not illustrate all the cleanup that needs to be done. Also, this document does not attempt to be an exhaustive survey of all possible ways to do a certain task; it merely tries to show a certain way. Encrypt/Decrypt Include headers #include "nss.h" #include "pk11pub.h" Make sure NSS is initialized.The simplest Init function, in case you don't need a NSS database is NSS_NoDB_Init(".") Choose a cipher mechanism. Note that some me...
... inbuflen); s = PK11_DigestFinal(EncContext, outbuf+tmp1_outlen, &tmp2_outlen, sizeof outbuf - tmp1_outlen); result_len = tmp1_outlen + tmp2_outlen; <big>Destroy the Context PK11_DestroyContext(EncContext, PR_TRUE);</big> <big>Repeat Step 6 any number of times. When all done with encrypt/decrypt ops, clean up</big> <big>PK11_FreeSymKey(SymKey); SECITEM_FreeItem(SecParam, PR_TRUE); PK11_FreeSlot(slot);</big> Note: AES encryption, a fixed blocksize of 16 bytes is used. The Rijndael algorithm permits 3 blocksizes (16, 24, 32 bytes), but the AES standard requires the blocksize to be 16 bytes. The keysize can vary and these keysizes are permitted: 16, 24, 32 ...
NSS tools : ssltab
13 0f 52 a3 c8 f6 | VoRbth=3e+-...RGBPE. } cipher_suite = (0x0003) SSL3/RSA/RC4-40/MD5 } 0: 0b 00 02 c5 |...A type = 11 (certificate) length = 709 (0x0002c5) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } 0: 0c 00 00 ca |.... type = 12 (server_key_exchange) length = 202 (0x0000ca) 0: 0e 00 00 00 |.... type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { 0: 16 03 00 00 44 |....D type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { 0: 10 00 00 40 |...@ type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { 0: 14 03 00 00 01 |..... type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |. } SSLRecord { 0: 1...
...000046) ServerHello { server_version = {3, 0} random = {...} session ID = { length = 32 contents = {..} } cipher_suite = (0x0003) SSL3/RSA/RC4-40/MD5 } type = 11 (certificate) length = 709 (0x0002c5) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) > encrypted > } ] >-- [ S...
NSS tools : ssltap
13 0f 52 a3 c8 f6 | VoRbth=3e+-...RGBPE. } cipher_suite = (0x0003) SSL3/RSA/RC4-40/MD5 } 0: 0b 00 02 c5 |...A type = 11 (certificate) length = 709 (0x0002c5) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } 0: 0c 00 00 ca |.... type = 12 (server_key_exchange) length = 202 (0x0000ca) 0: 0e 00 00 00 |.... type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { 0: 16 03 00 00 44 |....D type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { 0: 10 00 00 40 |...@ type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { 0: 14 03 00 00 01 |..... type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |. } SSLRecord { 0: 1...
...000046) ServerHello { server_version = {3, 0} random = {...} session ID = { length = 32 contents = {..} } cipher_suite = (0x0003) SSL3/RSA/RC4-40/MD5 } type = 11 (certificate) length = 709 (0x0002c5) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) > encrypted > } ] >-- [ S...
sslerr.html
SSL_ERROR_RX_MALFORMED_CERTIFICATE -12258 "SSL received a malformed Certificate handshake message." SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH -12257 "SSL received a malformed Server Key Exchange handshake message." SSL_ERROR_RX_MALFORMED_CERT_REQUEST -12256 "SSL received a malformed Certificate Request handshake message." SSL_ERROR_RX_MALFORMED_HELLO_DONE -12255 "SSL received a malformed Server Hello Done handshake message." SSL_ERROR_RX_MALFORMED_CERT_VERIFY -12254 "SSL received a malformed Certificate Verify handshake message." SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH -12253 "SSL received a malformed Client Key Exchange handshake message." SSL_ERROR_RX_MALFORMED_FINISHED -12252 "SSL received a ma...
...ROR_RX_UNEXPECTED_CERTIFICATE -12244 "SSL received an unexpected Certificate handshake message." SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH -12243 "SSL received an unexpected Server Key Exchange handshake message." SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST -12242 "SSL received an unexpected Certificate Request handshake message." SSL_ERROR_RX_UNEXPECTED_HELLO_DONE -12241 "SSL received an unexpected Server Hello Done handshake message." SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY -12240 "SSL received an unexpected Certificate Verify handshake message." SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH -12239 "SSL received an unexpected Client Key Exchange handshake message." SSL_ERROR_RX_UNEXPECTED_FINISHED -12238 "SSL rece...
sslfnc.html
ing the other processes. An application uses multiple processesonly if it uses the Unix function fork, or the Win32 function CreateProcess. This is not the same as using multiple threads or multiple processors. Note that an SSL server that uses Fortezza hardware devices is limited to a single process. It can use multiple threads, and thereby make use of multiple processors, but this must all be done from a single process. This function creates two caches: theserver session ID cache (also called the server session cache, or server cache), and theclient-auth certificate cache (also called the client cert cache, or client auth cache). Both caches are used only for sessions where the program handshakes as a server. The client-auth certificate cache is used to remember the certificates previous...
...for a particular socket generates the same error. However, there is no good reason for these to be mutually exclusive. This restirction will be removed in future releases. If a socket that is already connected gets imported into SSL after it has been connected (that is, after PR_Accept or PR_Connect has returned), then no implicit SSL handshake configuration as a client or server will have been done by PR_Connect or PR_Accept on that socket. In this case, a call to SSL_ResetHandshake is required to explicitly configure the socket to handshake as a client or as a server. If SSL_ResetHandshake is not called to explicitly configure the socket handshake, a crash is likely to occur when the first I/O operation is done on the socket after it is imported into SSL. SSL_OptionGet SSL_OptionGe...
NSS Tools ssltap
ain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } 0: 0c 00 00 ca |.... type = 12 (server_key_exchange) length = 202 (0x0000ca) 0: 0e 00 00 00 |.... ...
... } type = 11 (certificate) length = 709 (0x0002c5) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) }}]--> [SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } }}]--> [SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1)}SSLRecord { type ...
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
inlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } 0: 0c 00 00 ca |.... type = 12 (server_key_exchange) length = 202 (0x0000ca) 0: 0e 00 00 00 |.... ...
...type = 11 (certificate) length = 709 (0x0002c5) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,...
Tutorial: Embedding Rhino
With more effort on the part of the embedder, the objects exposed to scripts can be customized further. This tutorial leads you through the steps from a simple embedding to more customized, complex embeddings. Fully compilable examples are provided along the way. The examples live in the rhino/examples directory in the distribution and in mozilla/js/rhino/examples in cvs. This document will link to them using lxr. In this document, JavaScript code will be in green, Java code will be in green, and shell logs will be in purple. ...
... in the classpath. Let's step through the body of main one line at time. Entering a Context The code Context cx = Context.enter(); Creates and enters a Context. A Context stores information about the execution environment of a script. Initializing standard objects The code Scriptable scope = cx.initStandardObjects(); Initializes the standard objects (Object, Function, etc.) This must be done before scripts can be executed. The null parameter tells initStandardObjects to create and return a scope object that we use in later calls. Collecting the arguments This code is standard Java and not specific to Rhino. It just collects all the arguments and concatenates them together. String s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } Evaluating a script The code Obj...
Rhino scopes and contexts
xibility from the techniques described below. Contexts The Rhino Context object is used to store thread-specific information about the execution environment. There should be one and only one Context associated with each thread that will be executing JavaScript. To associate the current thread with a Context, simply call the enter method of Context: Context cx = Context.enter(); Once you are done with execution, simply exit the Context: Context.exit(); These calls will work properly even if there is already a Context associated with the current thread. That context will be returned and an internal counter incremented. Only when the counter reaches zero will it be disassociated from the thread. Remember to put the exit() call in a finally block if you're executing code that could throw...
...hen calling Context.initStandardObjects(ScriptableObject, boolean): ScriptableObject sealedSharedScope = cx.initStandardObjects(null, true); This seals only all standard library objects, it does not seal the shared scope itself thus after callinginitStandardObjects, sealedSharedScope can be farther populated with application-specific objects and functions. ...
Running Parsemark
t. The test files are not checked into the source tree because they're non-Mozilla JS code. Download the suite of parse tests from Bug 548621 and decompress them. Within js/src/tests, run python parsemark.py -h to see help documentation. ...
...pare them to the results for the "current" version of your shell. ...
Mozinfo
Mozinfo proposes to solve this problem. MozInfo is a bridge interface, making the underlying (complex) plethora of OS and architecture combinations conform to a subset of values of relevance to Mozilla software. The current implementation exposes relevant key, values: os, version, bits, and processor. ...
... Mozinfo proposes to solve this problem. MozInfo is a bridge interface, making the underlying (complex) plethora of OS and architecture combinations conform to a subset of values of relevance to Mozilla software. The current implementation exposes relevant key, values: os, version, bits, and processor. ...
Setting up an update server
a few additional steps to be taken here. First, the maintenance service needs to be "installed". Most likely, a different maintenance service is already installed, probably at C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe. Backup that file to another location and replace it with <obj dir>/dist/bin/maintenanceservice.exe. Don't forget to restore the backup when you are done. Also, the Mozilla Maintenance Service is only used if the install directory is within C:\Program Files or C:\Program Files (x86), so make sure your install directory is in one of those locations. Now that you have a build of Firefox capable of using a locally-built MAR, it's time to build the MAR. First, build Firefox the way you want it to be after updating. If you want it to be the same befor...
...efox's browser console to determine the update directory: const {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); FileUtils.getDir("UpdRootD", [], false).path Once you have determined the update directory, close Firefox, browse to the directory and remove the subdirectory called updates. Next, you need to change the update URL to point to the local XML file. This can be done most reliably with an enterprise policy. The policy file location depends on the operating system you are using. Windows/Linux: <install dir>/distribution/policies.json macOS: <install dir>/Contents/Resources/distribution/policies.json Create the distribution directory, if necessary, and put this in policies.json: { "policies": { "AppUpdateURL": "http://127.0.0.1:8000/update.xml" } } ...
Animated PNG graphics
Mozilla › Tech › APNG
offset unsigned int X position at which to render the following frame. 16 y_offset unsigned int Y position at which to render the following frame. 20 delay_num unsigned short Frame delay fraction numerator. 22 delay_den unsigned short Frame delay fraction denominator. 24 dispose_op byte Type of frame area disposal to be done after rendering this frame. 25 blend_op byte Type of frame area rendering for this frame. The frame must be rendered within the region defined by x_offset, y_offset, width, and height. The offsets must be non-negative, the dimensions must be positive, and the region may not fall outside of the default image. Constraints on frame regions: x_offset >= 0 y_offset >= 0 ...
...ed for decoding and display of each frame, so that animations will run at the same rate regardless of the performance of the decoder implementation. dispose_op specifies how the output buffer should be changed at the end of the delay (before rendering the next frame). Valid values for dispose_op are: Value Constant Description 0 APNG_DISPOSE_OP_NONE No disposal is done on this frame before rendering the next; the contents of the output buffer are left as is. 1 APNG_DISPOSE_OP_BACKGROUND The frame's region of the output buffer is to be cleared to fully transparent black before rendering the next frame. 2 APNG_DISPOSE_OP_PREVIOUS The frame's region of the output buffer is to be reverted to the previous contents before rendering the n...
Querying Places
container's contents, you must first open the container. Most container types populate themselves lazily, so opening a container actually corresponds to executing the given query. While a container is open, it will listen to the history and bookmarks systems' notifications and modify their contents to keep themselves up-to-date. For this reason, it is best to close a container as soon as you are done with it, since it will give better performance. If you close a container and re-open it before any history or bookmark change notifications come, the results will generally still be there and this operation will be fast. This example uses the Places history service to display all the titles of the history pages. // queries parameters (e.g. domain name matching, text terms matching, time range..
...eveloper.mozilla.org/en/nsINavHistoryContainerResultNode var cont = result.root; cont.containerOpen = true; for (var i = 0; i < cont.childCount; i ++) { var node = cont.getChild(i); // "node" attributes contains the information (e.g. uri, title, time, icon...) // see : https://developer.mozilla.org/en/nsINavHistoryResultNode dump(node.title+ "\n"); } // Close container when done // see : https://developer.mozilla.org/en/nsINavHistoryContainerResultNode cont.containerOpen = false; See also Places query URIs Displaying Places information using views ...
Retrieving part of the bookmarks tree
This document provides a quick start for those wishing to quickly retrieve a portion of the bookmarks tree. Bookmarks are retrieved using the Places query system. For more basic bookmarks examples, see Manipulating bookmarks using Places. Get the query and options objects All querying is done through the history service. First, you need to get an empty query and options objects from the history service: var historyService = Components.classes["@mozilla.org/browser/nav-history-service;1"] .getService(Components.interfaces.nsINavHistoryService); var options = historyService.getNewQueryOptions(); var query = historyService.getNewQuery(); Find the folder you want to get Known folder IDs are retrieved from the bookmarks service. Attributes defined in /toolkit/compon...
...ill be an nsINavHistoryContainerResultNode corresponding to your folder. If you have a complex query the root will be a nsINavHistoryQueryResultNode. Before accessing the children of any result container, you must first open it, and then you can iterate the children. As long as the container is open, it will listen for notifications from the bookmarks system to keep itself up-to-date. When you're done, be sure to close the container to free up the resources. Otherwise, it will continue to get observer notifications and update itself, slowing down the whole browser. var rootNode = result.root; rootNode.containerOpen = true; // iterate over the immediate children of this folder and dump to console for (var i = 0; i < rootNode.childCount; i ++) { var node = rootNode.getChild(i); dump("Child:...
How to build an XPCOM component in JavaScript
x-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsIHelloWorld : nsISupports { string hello(); }; Note that you must generate a new UUID for each XPCOM component that you create. See Generating GUIDs for more information. Compiling the Typelib Your interface definition must be compiled into a binary format (XPT) in order to be registered and used within Mozilla applications. The compilation can be done using the Gecko SDK. You can learn how to get Mac, Linux, and Windows versions of the Gecko SDK by reading the article Gecko SDK. For code outside the tree Note: On Windows if you download the Gecko SDK without the whole build tree, you will be missing some required DLLs for xpidl.exe and it will run with no errors but not do anything. To fix this download the Mozilla build tools for Windows an...
...jsm using Components.utils.import to simplify the process of writing your component slightly. The imported library contains functions for generating the module, factory, and the NSGetModule and QueryInterface functions for you. Note: it doesn't do the work of creating your interface definition file or the type library for you, so you still have to go through those steps above if they haven't been done. The library provides a simple example of its use in the source code (js/xpconnect/loader/XPCOMUtils.jsm), but here's another using this example. To begin, include a line at the top of your interface to import the XPCOMUtils library: Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); then implement your interface the same way you did above, except with a few modifications so tha...
Mozilla internal string guide
ring nsPromiseFlatString - created through PromiseFlatString() nsLiteral[C]String - created through the ""_ns and u""_ns user-defined literals Of course, there are times when it is necessary to reference these string classes in your code, but as a general rule they should be avoided. Iterators Because Mozilla strings are always a single buffer, iteration over the characters in the string is done using raw pointers: /** * Find whether there is a tab character in `data` */ bool HasTab(const nsAString& data) { const char16_t* cur = data.BeginReading(); const char16_t* end = data.EndReading(); for (; cur < end; ++cur) { if (char16_t('\t') == *cur) return true; } return false; } Note that `end` points to the character after the end of the string buffer. It should neve...
... it. If there's a need to request a different capacity before you are ready to call Finish(), you can call RestartBulkWrite() on the handle. It takes three arguments that match the first three arguments of BulkWrite(). It returns mozilla::Result<mozilla::Ok, nsresult> to indicate success or OOM. Calling RestartBulkWrite() invalidates previously-obtained span, raw pointer or length. Once you are done writing, call Finish(). It takes two arguments: the new logical length of the string (which must not exceed the capacity retuned by the Length() method of the handle) and a boolean indicating whether it's OK to attempt to reallocate a smaller buffer in case a smaller mozjemalloc bucket could accommodate the new logical length. Helper Classes and Functions Converting Cocoa strings Use mozilla::...
Receiving startup notifications
ervices at appropriate times, for example. Receiving startup notifications in Gecko 2.0 (Firefox 4) and later In order to improve startup times, changes were made to the XPCOM startup process. See The startup process for details on how this now works, if you're interested in specifics. The important thing to note is that now instead of registering with the Category Manager programmatically as was done in the past, you add lines to your chrome.manifest to let the application handle it for you. For example: category profile-after-change MyComponent @foobar/mycomponent;1 Important: In the past, the contract ID of the category entry started with "service," if the component was implemented as a service. This is no longer the case, so be sure to remove that when migrating existing code. Additionally...
...ensions. Once that process is completed, extensions can then be loaded by simply reading their manifests, loading their components, and continuing with application startup, all without having to restart the browser. Receiving startup notifications prior to Gecko 2.0 (Firefox 4) To receive startup notifications, one needs to register with the "app-startup" category using nsICategoryManager; having done so, the component will receive these startup notifications, including: xpcom-startup Sent when XPCOM finishes starting up. Most application features are not yet available at this point, but XPCOM itself is. app-startup Sent when the application has finished starting up. final-ui-startup Sent just before the first application window is displayed. Registering with the Category Manager To register...
HOWTO
Async network requests Problem You want to make network requests or do other asynchronous work in xpcshell. However, when you start your script, it exits immediately, before the network request returns. Solution 1. ...
...ediately, before the network request returns. Solution 1. Put the following at the end of your script: // Do async processing // From <https://developer.mozilla.org/en/XPConnect/xpcshell/HOWTO> print("Doing async work"); gScriptDone = false; var gThreadManager = Cc["@mozilla.org/thread-manager;1"] .getService(Ci.nsIThreadManager); var mainThread = gThreadManager.currentThread; while (!gScriptDone) mainThread.processNextEvent(true); while (mainThread.hasPendingEvents()) mainThread.processNextEvent(true); 2. In all callbacks where your script is finished, i.e. both success and error callbacks, put: gScriptDone = true; If you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait). This is of course a massive, ugly hack pro...
imgIContainer
Obsolete since Gecko 2.0 void setDiscardable(in string aMimeType); Native code only! Obsolete since Gecko 2.0 void setFrameBlendMethod(in unsigned long framenumber, in PRInt32 aBlendMethod); Obsolete since Gecko 2.0 void setFrameDisposalMethod(in unsigned long framenumber, in PRInt32 aDisposalMethod); Obsolete since Gecko 2.0 void setFr...
... this should only be called from within nsImageFrame or objects of similar type. void requestRefresh( [const] in TimeStamp aTime ); Parameters aTime Missing Description Exceptions thrown Missing Exception Missing Description resetAnimation() void resetAnimation(); Parameters None. Exceptions thrown Missing Exception Missing Description Native code only!restoreDataDone Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. void restoreDataDone(); Parameters None. Exceptions thrown Missing Exception Missing Description Native code only!setDiscardable Obsolete since Gecko 2.0 (F...
mozIThirdPartyUtil
3.3 / SeaMonkey 2.1) Method overview boolean isThirdPartyChannel(in nsIChannel aChannel, [optional] in nsIURI aURI); boolean isThirdPartyURI(in nsIURI aFirstURI, in nsIURI aSecondURI); boolean isThirdPartyWindow(in nsIDOMWindow aWindow, [optional] in nsIURI aURI); Methods isThirdPartyChannel() Determine whether the given channel and its content window hierarchy is third party. This is done as follows: If aChannel is an nsIHttpChannel and has the 'forceAllowThirdPartyCookie' property set, then: If aURI is null, return false. Otherwise, find the URI of the channel, determine whether it is foreign with respect to aURI, and return. Find the URI of the channel and determine whether it is third party with respect to the URI of the channel. If so, return. Obtain the bottommost nsIDOMW...
...tp://images.google.com/", but "http://mail.yahoo.com/" and "http://192.168.1.1/" are. boolean isThirdPartyURI( in nsIURI aFirstURI, in nsIURI aSecondURI ); Parameters aFirstURI Missing Description aSecondURI Missing Description Return value true if aFirstURI is third party with respect to aSecondURI. isThirdPartyWindow() Determine whether the given window hierarchy is third party. This is done as follows: Obtain the URI of the principal associated with aWindow. Call this the 'bottom URI'. If aURI is provided, determine if it is third party with respect to the bottom URI. If so, return. Find the same-type parent window, if there is one, and its URI. Determine whether it is third party with respect to the bottom URI. If so, return. Therefore, each level in the window hierarchy is teste...
nsIDragService
43 (Firefox 43 / Thunderbird 43 / SeaMonkey 2.40) Note: Using this interface directly from add-on code is deprecated. Add-ons should use the standard dataTransfer drag and drop API instead. The only exception is getCurrentSession(), since there's currently no way to check for a drag in progress using standard DOM methods or properties. ...
...ot used on GTK, which handles the drag popup itself. [noscript] void dragMoved( in long aX, in long aY ); Parameters aX The X coordinate to which to move the popup being dragged. aY The Y coordinate to which to move the popup being dragged. endDragSession() Tells the Drag Service to end a drag session. This is called when an external drag occurs. void endDragSession( in PRBool aDoneDrag ); Parameters aDoneDrag If aDoneDrag is true, the drag has finished, otherwise the drag has just left the window. fireDragEventAtSource() Obsolete since Gecko 43 (Firefox 43 / Thunderbird 43 / SeaMonkey 2.40)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Fire a drag event...
nsIHTMLEditor
defaults. aAttribute The attribute of the property, if applicable. May be null. Example: aProperty="font", aAttribute="color" aValue If aAttribute is not null, the value of the attribute. Example: aProperty="font", aAttribute="color", aValue="0x00FFFF" removeInlineProperty() Deletes the properties from all text in the current selection. If aProperty is not set on the selection, nothing is done. void removeInlineProperty( in nsIAtom aProperty, in AString aAttribute ); Parameters aProperty The property to remove from the selection All atoms are for normal HTML tags (for example nsIEditorProperty.font()) except when you want to remove just links and not named anchors. For that, use nsIEditorProperty.href(). aAttribute The attribute of the property, if applicable. May be null.
...ameters aProperty aAttribute aValue setParagraphFormat() Insert a block paragraph tag around selection. void setParagraphFormat( in AString aParagraphFormat ); Parameters aParagraphFormat "p", "h1" to "h6", "address", "pre", or "blockquote" updateBaseURL() Set the BaseURL for the document to the current URL but only if the page doesn't have a <base> tag This should be done after the document URL has changed, such as after saving a file This is used as base for relativizing link and image urls. void updateBaseURL(); Parameters None. ...
nsINavHistoryResult
register themselves through the registerViewer() method. The viewer then tells the actual view object what to do. You can use nsINavHistoryResultTreeViewer as the viewer; this provides a prepackaged interaction with a nsiTreeBoxObject. If you need a different view, you'll need to create your own viewer interface. The viewer provides notifications to the controller when view events occur; this is done using the nsINavHistoryResultViewObserver interface. Method overview void addObserver(in nsINavHistoryResultObserver aObserver, in boolean aOwnsWeak); void removeObserver(in nsINavHistoryResultObserver aObserver); Attributes Attribute Type Description root nsINavHistoryContainerResultNode The root of ...
... their results to be valid. When a result goes out of scope it will continue to observe changes till it is cycle collected. While the result waits to be collected it will stay in memory, and continue to update itself, potentially causing unwanted additional work. When you close the root node the result will stop observing changes, so it is good practice to close the root node when you are done with a result, since that will avoid unwanted performance hits. Read only. sortingAnnotation AUTF8String The annotation to use in SORT_BY_ANNOTATION_* sorting modes; you must set this value before setting the sortingMode attribute. sortingMode unsigned short Specifies the sorting mode for the result. This value must be one of nsINavHistoryQ...
nsITransaction
transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undoTransaction() and redoTransaction() methods can be called. If the transient state is true, the transaction manager returns immediately after the transaction's doTransaction() method is called, no references to the transaction are maintained. Transient transactions cannot be undone or redone by the transaction manager. Read only. Methods doTransaction() Executes the transaction. void doTransaction(); Parameters None. merge() Attempts to merge a transaction into "this" transaction. Both transactions must be in their undo state, doTransaction() methods already called. The transaction manager calls this method to coalesce a new transaction with the transaction on the top o...
...s not possible or failed. If true, the transaction manager will Release() the new transaction instead of pushing it on the undo stack. boolean merge( in nsITransaction aTransaction ); Parameters aTransaction The previously executed transaction to merge. Return value Missing Description redoTransaction() Executes the transaction again. Can only be called on a transaction that was previously undone. In most cases, the redoTransaction method will actually call the doTransaction() method to execute the transaction again. void redoTransaction(); Parameters None. undoTransaction() Restores the state to what it was before the transaction was executed. void undoTransaction(); Parameters None. See also nsITransactionList nsITransactionListener nsITransactionManager ...
nsITransactionList
aIndex); Attributes Attribute Type Description numItems long The number of transactions contained in this list. Read only. Methods getChildListForItem() Returns the list of children associated with the item at aIndex. Implementations may return null if there are no children, or an empty list. The list returned is AddRef'd so it is up to the caller to Release the transaction when it is done. nsITransactionList getChildListForItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value The nsITransactionList of children associated with the item at aIndex. getItem() Returns the transaction at the given index in the list. Note that a null can be returned here if the item is a batch. The transaction returned is AddRef'd so it is up to the caller to Rele...
...stForItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value The nsITransactionList of children associated with the item at aIndex. getItem() Returns the transaction at the given index in the list. Note that a null can be returned here if the item is a batch. The transaction returned is AddRef'd so it is up to the caller to Release the transaction when it is done. nsITransaction getItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value Missing Description getNumChildrenForItem() Returns the number of child (auto-aggreated) transactions the item at aIndex has. long getNumChildrenForItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value The number of child (auto-aggreated) trans...
nsITransactionManager
edo stacks if the value specified is less than the number of items that exist on both the undo and redo stacks. numberOfRedoItems long The number of items on the redo stack. Read only. numberOfUndoItems long The number of items on the undo stack. Read only. Methods AddListener() Adds a listener to the transaction manager's notification list. Listeners are notified whenever a transaction is done, undone, or redone. The listener's nsITransactionListener.AddRef() method is called. void AddListener( in nsITransactionListener aListener ); Parameters aListener The nsITransactionListener to add. beginBatch() Turns on the transaction manager's batch mode, forcing all transactions executed by the transaction manager's doTransaction() method to be aggregated together until EndBatch() is call...
...sactionListener aListener ); Parameters aListener The nsITransactionListener to add. beginBatch() Turns on the transaction manager's batch mode, forcing all transactions executed by the transaction manager's doTransaction() method to be aggregated together until EndBatch() is called. This mode allows an application to execute and group together several independent transactions so they can be undone with a single call to undoTransaction(). void beginBatch(); Parameters None. clear() Clears the undo and redo stacks. void clear(); Parameters None. doTransaction() Calls a transaction's nsITransaction.doTransaction() method, then pushes it on the undo stack. This method calls the transaction's nsITransaction.AddRef() method. The transaction's nsITransaction.Release() method will be called when...
NS_CStringContainerInit
s This function is equivalent to NS_CStringContainerInit2(container, nsnull, 0, 0). The nsCStringContainer structure has private members that should not be accessed directly. After a nsCStringContainer object has been initialized via NS_CStringContainerInit, it may be used as an ordinary nsACString object. With NS_CStringContainerInit, the coder is required to call NS_CStringContainerFinish when done with the nsCStringContainer object. Therefore, it is generally better to use nsEmbedCString, to instantiate a nsACString object, since it automatically releases allocated memory when the object goes out of scope. Example nsCStringContainer str; if (NS_SUCCEEDED(NS_CStringContainerInit(str))) { // Now, |str| can be used with any function taking a nsACString parameter. // Call this function...
...ore, it is generally better to use nsEmbedCString, to instantiate a nsACString object, since it automatically releases allocated memory when the object goes out of scope. Example nsCStringContainer str; if (NS_SUCCEEDED(NS_CStringContainerInit(str))) { // Now, |str| can be used with any function taking a nsACString parameter. // Call this function to release any memory owned by |str| when done. NS_CStringContainerFinish(str); } History This function was finalized for Mozilla 1.7. See bug 239123 for details. See Also NS_CStringContainerFinish, nsACString, nsEmbedCString ...
NS_StringContainerInit
error code. Remarks The nsStringContainer structure has unspecified size and layout. Its members may not be accessed directly. After a nsStringContainer object has been initialized, it may be used as an ordinary nsAString object. The internal buffer allocated by a nsStringContainer is always null-terminated. With NS_StringContainerInit, the coder is required to call NS_StringContainerFinish when done with the nsStringContainer object. Therefore, it is generally better to use nsEmbedString, to instantiate a nsAString object, since it automatically releases allocated memory when the object goes out of scope. Example Code nsStringContainer str; if (NS_SUCCEEDED(NS_StringContainerInit(str))) { // Now, |str| can be used with any function taking a nsAString parameter. // Be sure to c...
...ly better to use nsEmbedString, to instantiate a nsAString object, since it automatically releases allocated memory when the object goes out of scope. Example Code nsStringContainer str; if (NS_SUCCEEDED(NS_StringContainerInit(str))) { // Now, |str| can be used with any function taking a nsAString parameter. // Be sure to call this function to release any memory owned by |str| when done. NS_StringContainerFinish(str); } History This function was frozen for Mozilla 1.7. See bug 239123 for details. See Also NS_StringContainerFinish, nsAString, nsEmbedString ...
Reference Manual
to be a complete replacement for raw XPCOM interface pointers where they are used as owning references. Almost any place you could use a raw XPCOM interface pointer, you should be able to use an nsCOMPtr. An nsCOMPtr is the exact same size and shape as a raw XPCOM interface pointer. It can be used as a member variable without introducing bloat. Most of the work of being an owning reference can be done in the constructor, destructor, and assignment operators of nsCOMPtr. Whenever you `point' the nsCOMPtr at a different XPCOM object (by assignment or initialization), it must Release its old value, if any, and AddRef the new. At its own destructor time it must Release as well. nsCOMPtr only does exactly the work you would have done, if you always remembered to do the right thing. Safety Features ...
..., though the recommendations from that document are re-iterated here. Time [[More time-performance measurements are needed.]] In places where two or more subroutines calls are required, i.e., of AddRef, Release, and QueryInterface, some nsCOMPtr routines are factored, and hence, require additional time corresponding to invoking a subroutine. This time is negligable, especially in the face of work done by QueryInterface, and the work that may be done by Release. In all other cases, nsCOMPtr does only the work you would have done by hand. The bulk of the work for which an nsCOMPtr is used is dereferencing with operator->, just as it is with a primitive pointer. On every platform, this operation generates the exact same code, and takes the same time, as performing this operation on a raw XPCOM in...
Using nsIDirectoryService
The interfaces for this can be found here. Known Locations The nsIProperties strings for currently defined locations can be found in: nsDirectoryServiceDefs.h nsAppDirectoryServiceDefs.h nsXULAppAPI.h Content formerly at http://www.mozilla.org/projects/xpco...locations.html Background The way in which Mozilla components locate special files and directories has changed. In the past, this was done using nsIFileLocator. This component was a problem for embedding applications. Since it was a component and was loaded implicitly by many other components, it was difficult to customize. Customizing the locations is important if, for example, your application already has a profile directory or other resource directories. You may wish that you could have Mozilla use these locations rather than req...
...roviders, only the service. Defined Locations The nsIProperties keywords that you will use to get locations are defined in two places. OS and XPCOM Level nsDirectoryServiceDefs.h These locations are provided by XPCOM, are constant with the system, and and should not need customization. Although you will not customize these locations, you may need to tell XPCOM where its /bin directory is. This is done by passing a directory to NS_InitXPCOM or, for embedding, as the first parameter to NS_InitEmbedding. The location of the Components folder and the Components registry, among other things, are relative to the /bin directory. If Mozilla's Components directory is not in the same directory as your process, you will need to set the /bin directory as described above. In this case you will also need to...
xptcall FAQ
bitrary XPCOM interfaces into JavaScript and to make calls from JavaScript to XPCOM using XPTC_InvokeByIndex. The information in the typelibs allows XPConnect to convert function parameters and build the nsXPTCVariant array required to make this call. The stubs (or impersonation) facility of xptcall allows for implementing a class which can, at runtime, pretend to be any XPCOM interface. This is done by providing a vtbl full of generic function stubs in xptcall. These stubs forward calls to a shared function whose job it is to use the typelib information to extract the parameters from the platform specific calling convention to build an array of variants to hold the parameters and then call an inherited method which can then do whatever it wants with the call. This code also does the platform...
...cific calling convention to build an array of variants to hold the parameters and then call an inherited method which can then do whatever it wants with the call. This code also does the platform specific cleanup as the call returns. This all works and is being used in Mozilla today on numerous platforms. Why can't xptcall just be implemented in C or C++? Neither of these two facilities can be done in a fully cross platform way. Nor can they generally be done fully in C or C++. Let's take them one at a time to see why. The invoke facility requires code that can build and invoke an arbitrary call frame. The C++ compiler builds such call frames all the time. But the compiler builds frames customized at compile time for the specific signature of the callee. xptcall needs to be able to call an...
Filelink Providers
LD_TYPE is "int", "bool", or "char". For example, the Hightail implementation provides the following function: function extraArgs() { var usernameValue = document.getElementById("username").value; return { "username": {type: "char", value: usernameValue}, }; } In this example, the username value is read from the input, and then the specially-crafted object is returned. Once this is done, the field is accessible from within the implementation via the Preferences API using the key mail.cloud_files.accounts.ACCOUNT_KEY.username where ACCOUNT_KEY is the value passed into the implementations init function. The Hightail settings.xhtml and settings.js file have examples of this. Management interface Once an account has been created, it is manageable from within the Preferences dialo...
...s manageable from within the Preferences dialog, in the Attachment pane, in the Outgoing tab. The content to the right of the menulist is an IFrame, pointed at a URL read from the providers managementURL attribute, which should point to an XHTML page. The XHTML page should have a function in the global scope called onLoadProvider. This function is called automatically once the DOM content is done loading, and is passed a single parameter - the provider instance whose data is being displayed. ...
MailNews Filters
For new incoming messages, the protocol specific object that handles new messages calls nsIMsgFilterList::ApplyFiltersToHdr and passes itself in as nsIMsgFilterHitNotify interface to handle filter hits. E.g., IMAP, POP3. ApplyFiltersToHdr will in turn call the applyFilterHit method of the passed in nsIMsgFilterHitNotify interface ptr. The protocol specific code will then apply all of the actions of the filter to the current msg header. ...
...r local folder, and advance to the next header. For IMAP, we tend to initiate the urls synchronously, but because we don't run two urls simultaneously on the same folder, the urls don't run until we've finished downloading headers. We also coalesce moves to the same destination folder, so that we can do them in one url/command to the server, and we playback those moves when the header download is done. After the Fact Filters These are one or more filters run on one or more folders *after* the headers have been downloaded. These filters are initiated in the filter editor, and implemented in nsMsgFilterService.cpp. This is implemented by doing a search using the filter criteria and applying the actions en masse on the resulting hits. The search is executed locally, not on the server, so that...
Mail composition back end
by Richard H. Pizzarro <rhp@netscape.com> Contents Overview Sending Messages nsIMsgSend Sending Listener Interfaces nsIMsgSendListener nsIMsgCopyServiceListener Copy Operations Copy to Sent Folder Drafts Templates "Send Later" Sending Unsent Messages Sending Unsent Messages Listener Quoting Sample Programs Overview I've done considerable work in the past few weeks reorganizing the Mail Composition back end, so I thought it would be helpful to put together a small doc on the new interfaces and how one can use them. The Mail Composition back end is responsible for the assembly and creation of RFC822 messages to be delivered either via SMTP or NNTP services. You also have the ability to save RFC822 files to disk, should...
...interface. The SetFcc() and GetFcc() methods are used by the caller to control if a message should be copied to the defined "Sent" folder if the sending operation was successful. Currently, this pref is a "char *" which is the specific name of the folder, but this will more than likely change to a PRBool (boolean) preference. The determiniation of which folder is the "Sent" folder for the user is done by a call to GetFoldersWithFlag() and the message store will control this user defined preference. If the setting for GetFcc() is set to true, the copy operation is automatically performed after a successful send operation. Drafts Saving a message as a draft is controlled by the "nsMsgDeliverMode mode" argument of the CreateAndSendMessage and SendMessageFile methods. If the c...
Using Objective-C from js-ctypes
d OS Libraries page. Converting Objective-C code to C code To convert Objective-C code to js-ctypes, we need to convert it to C code first. We can then convert it straight to js-ctypes code. Speech Synthesis Example Let's start with the following Objective-C code, which invokes the Speech Synthesis API to say "Hello, Firefox!". It uses the default system voice and waits until the speaking is done. #import <AppKit/AppKit.h> int main(void) { NSSpeechSynthesizer* synth = [[NSSpeechSynthesizer alloc] initWithVoice: nil]; [synth startSpeakingString: @"Hello, Firefox!"]; // Wait until start speaking. while (![synth isSpeaking]) {} // Wait while speaking. while ([synth isSpeaking]) {} [synth release]; return 0; } Save this file as test.m, and run with the following command...
...let text = objc_msgSend(tmp2, initWithCString_encoding, ctypes.char.array()("Hello, Firefox!"), ctypes.unsigned_long(NSUTF8StringEncoding)); Converted js-ctypes code Finally, we have our converted code. This can run with a copy-and-paste into a JavaScript shell. This example uses a busy loop, and thus, Firefox won't respond until the speaking is done. If this code were to be used in a production add-on, then to avoid Firefox locking up, run this code from a ChromeWorker. let { ctypes } = Components.utils.import("resource://gre/modules/ctypes.jsm", {}); let id = ctypes.StructType("objc_object").ptr; let SEL = ctypes.StructType("objc_selector").ptr; let BOOL = ctypes.signed_char; let lib = ctypes.open(ctypes.libraryName("objc")); let objc_g...
Library
close(); Parameters None. ...
...y.cpp?offset=0#271 This shows that we can also supply only two arguments to the declare function. ...
Animation.reverse() - Web APIs
Web › API › Animation › reverse
an unplayed animation, the whole animation is played backwards. If called on a paused animation, the animation will continue in reverse. Syntax animation.reverse(); Parameters None. Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to play backwards, causing her to get smaller. ...
... or tapping the bottle causes Alice's growing animation (aliceChange) to play backwards, causing her to get smaller. It is done by setting aliceChange's Animation.playbackRate to -1 like so: var shrinkAlice = function() { // play Alice's animation in reverse aliceChange.playbackRate = -1; aliceChange.play(); // play the bottle's animation drinking.play() } But it could also have been done by calling reverse() on aliceChange like so: var shrinkAlice = function() { // play Alice's animation in reverse aliceChange.reverse(); // play the bottle's animation drinking.play() } Specifications Specification Status Comment Web AnimationsThe definition of 'reverse()' in that specification. Working Draft ...
AudioNode - Web APIs
Web › API › AudioNode
n only belong to one audio context. A source node has zero inputs but one or multiple outputs, and can be used to generate sound. On the other hand, a destination node has no outputs; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). In addition, there are processing nodes which have inputs and outputs. The exact processing done varies from one AudioNode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the AnalyserNode, where the result of the processing is accessed separately). The more nodes in a graph, the higher the latency will be. For example, if your graph has a latency of 500ms,...
...2048; analyserNode.maxDecibels = -25; analyserNode.minDecibels = -60; analyserNode.smoothingTimeConstant = 0.5; You are free to use either constructors or factory methods, or mix both, however there are advantages to using the constructors: All parameters can be set during construction time and don't need to be set individually. You can sub-class an audio node. While the actual processing is done internally by the browser and cannot be altered, you could write a wrapper around an audio node to provide custom properties and methods. Slightly better performance: In both Chrome and Firefox, the factory methods call the constructors internally. Keep in mind that Microsoft Edge does not yet appear to support the constructors; it will throw a "Function expected" error when you use the constr...
Background Tasks API - Web APIs
logFragment = null; } if (scrolledToEnd) { logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight; } statusRefreshScheduled = false; } First, scrolledToEnd is set to true if the text in the log is scrolled to the bottom; otherwise it's set to false. We'll use that to determine if we should update the scroll position to ensure that the log stays at the end when we're done adding content to it. Next, we update the progress and status information if any tasks have been enqueued. If the current maximum value of the progress bar is different from the current total number of enqueued tasks (totalTaskCount), then we update the contents of the displayed total number of tasks (totalTaskCountElem) and the maximum value of the progress bar, so that it scales properly. ...
...ediately changing the main DOM itself. We then create a new <div> element and set its contents to match the input text. Then we append the new element to the end of the pseudo-DOM in logFragment. logFragment will accumulate log entries until the next time updateDisplay() is called because the DOM for the changes. Running tasks Now that we've got the task management and display maintenance code done, we can actually start setting up code to run tasks that get work done. The task handler The function we'll be using as our task handler--that is, the function that will be used as the value of the task object's handler property--is logTaskHandler(). It's a simple function that outputs a bunch of stuff to the log for each task. In your own application, you'd replace this code with whatever task...
Body.body - Web APIs
Web › API › Body › body
ing an identical copy of the image. ...
...inal image fetch('./tortoise.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(body => { const reader = body.getReader(); return new ReadableStream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // When no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // Enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); }); } } }) }) .then(stream => new Response(stream)) .then(response => response.blob()) .then(blob => URL.createObjectURL(blob)) .then(url => console.log(image.src = url)) .catch(err => ...
Manipulating video using canvas - Web APIs
is check to see if the video is even playing; if it's not, the callback returns immediately without doing anything. Then it calls the computeFrame() method, which performs the chroma-keying effect on the current video frame. The last thing the callback does is call setTimeout() to schedule itself to be called again as soon as possible. In the real world, you would probably schedule this to be done based on knowledge of the video's frame rate. Manipulating the video frame data The computeFrame() method, shown below, is responsible for actually fetching a frame of data and performing the chroma-keying effect. processor.computeFrame = function computeFrame() { this.ctx1.drawImage(this.video, 0, 0, this.width, this.height); let frame = this.ctx1.getImageData(0, 0, this.width, this...
...arameters that are considered to be part of the green screen has its alpha value replaced with a zero, indicating that the pixel is entirely transparent. As a result, the final image has the entire green screen area 100% transparent, so that when it's drawn into the destination context in line 13, the result is an overlay onto the static backdrop. The resulting image looks like this: This is done repeatedly as the video plays, so that frame after frame is processed and displayed with the chroma-key effect. View the full source for this example. ...
Basic usage of canvas - Web APIs
but is one of the global HTML attributes which can be applied to any HTML element (like class for instance). It is always a good idea to supply an id because this makes it much easier to identify it in a script. The <canvas> element can be styled just like any normal image (margin, border, background...). These rules, however, don't affect the actual drawing on the canvas. We'll see how this is done in a dedicated chapter of this tutorial. When no styling rules are applied to the canvas it will initially be fully transparent. Fallback content The <canvas> element differs from an <img> tag in that, like for <video>, <audio>, or <picture> elements, it is easy to define some fallback content, to be displayed in older browsers not supporting it, like versions of Internet Explorer earlier than...
...This function, or one like it, could also be called using window.setTimeout(), window.setInterval(), or any other event handler, as long as the page has been loaded first. Here is how a template would look in action. As shown here, it is initially blank. A simple example To begin, let's take a look at a simple example that draws two intersecti...
Using images - Web APIs
nt of the drawImage() method adds two new parameters and lets us place scaled images on the canvas. drawImage(image, x, y, width, height) This adds the width and height parameters, which indicate the size to which to scale the image when drawing it onto the canvas. Example: Tiling an image In this example, we'll use an image as a wallpaper and repeat it several times on the canvas. ...
...anvas. This is done simply by looping and placing the scaled images at different positions. In the code below, the first for loop iterates over the rows. The second for loop iterates over the columns. The image is scaled to one third of its original size, which is 50x38 pixels. Note: Images can become blurry when scaling up or grainy if they're scaled down too much. Scaling is probably best not done if you've got some text in it which needs to remain legible. <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var ctx = document.getElementById('canvas').getContext('2d'); var img = new Image(); img.onload = function() { for (var i = 0; i < 4; i++) { for (var j = 0; j < 3; j++) { ctx.drawImag...
ConstantSourceNode.offset - Web APIs
lider control's value is set to match the gain on the two nodes. Then we create a new ConstantSourceNode and make it the source for the two gain nodes' GainNode.gain values. Each of those values is also an AudioParam. Let's say we have an event handler (for click events, in this case) which needs to respond by altering the value of the two gain nodes. ...
...The two gain nodes quickly adopt the new volume level. ...
Constraint validation API - Web APIs
rols, before submitting the values to the server. Concepts and usage Certain HTML form controls, such as <input>, <select> and <textarea>, can restrict the format of allowable values, using attributes like required and pattern to set basic constraints. However, you may want to impose more complex constraints, or to provide clearer reporting of validation failures than the defaults. This can be done using the Constraint Validation API. Note: Client-side constraint validation doesn't remove the need for validation on the server side. Even though client-side validation can prevent many common kinds of invalid values, invalid ones can still be sent by older browsers or by attackers trying to trick your web application. Therefore, you need to also validate input values on the server side, in a...
... Note: Client-side constraint validation doesn't remove the need for validation on the server side. Even though client-side validation can prevent many common kinds of invalid values, invalid ones can still be sent by older browsers or by attackers trying to trick your web application. Therefore, you need to also validate input values on the server side, in a way that is consistent with what is done on the client side. Client side validation is a tool for giving quick feedback to the user. You should not rely on it to completely sanitize data received by the server. Validation of constraints through the constraint validation API is done either on a single form element or at the form level, on the <form> element itself. Constraint validation interfaces ValidityState The ValidityState i...
DataTransferItem.webkitGetAsEntry() - Web APIs
it as its text content, and then appends it to the container. The container is always a list element in this example, as you'll see shortly. Once the current item is in the list, the item's isDirectory property is checked. If the item is a directory, we need to recurse into that directory. The first step is to create a FileSystemDirectoryReader to handle fetching the directory's contents. That's done by calling the item's createReader() method. Then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy. After that, directoryReader.readEntries() is called to read in all the entries in the directory. These are each, in turn, passed into a recursive call to scanFiles() to process them. Any of them which a...
...fault(); listing.innerHTML = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitGetAsEntry(); if (item) { scanFiles(item, listing); } } }, false); This fetches the list of DataTransferItem objects representing the items dropped from event.dataTransfer.items. Then we call Event.preventDefault() to prevent the event from being handled further after we're done. Now it's time to start building the list. First, the list is emptied by setting listing.innerHTML to be empty. That leaves us with an empty ul to begin inserting directory entries into. Then we iterate over the items in the list of dropped items. For each one, we call its webkitGetAsEntry() method to obtain a FileSystemEntry representing the file. If that's successful, we call scanFiles() to p...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
What is whitespace? Whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, CRLF sequences, carriage returns or line feeds). ...
...ks taking up space in the page. People viewing the web page see the words "Hello" and "World!" on 2 separate lines as you'd expect 2 <div>s to be laid out. The browser engine has essentially ignored all of the whitespace that was added in the source code. Spaces in between inline and inline-block elements Let's move on to look at a few issues that can arise due to whitespace, and what can be done about them. First of all, we'll look at what happens with spaces in between inline and inline-block elements. In fact, we saw this already in our very first example, when we described how whitespace is processed inside inline formatting contexts. We said that there were rules to ignore most characters but that word-separating characters remain. When you're only dealing with block-level elements ...
FileReader.readyState - Web APIs
The FileReader readyState property provides the current state of the reading operation a FileReader is in. A FileReader exists in one of the following states: Value State Description 0 EMPTY Reader has been created. None of the read methods called yet. 1 LOADING A read method has been called. 2 DONE The operation is complete. EMPTY The FileReader has been created, but no readAs method was called yet. LOADING A readAs method was invoked. A File or Blob is being read, and no error has occurred yet. DONE The read operation is complete. This could mean that: the entire File or Blob has been read into memory, a file read error occurred, or abort() was called and the read was cancelled. Example var reader = new FileReader...
...This could mean that: the entire File or Blob has been read into memory, a file read error occurred, or abort() was called and the read was cancelled. Example var reader = new FileReader(); console.log('EMPTY', reader.readyState); // readyState will be 0 reader.readAsText(blob); console.log('LOADING', reader.readyState); // readyState will be 1 reader.onloadend = function () { console.log('DONE', reader.readyState); // readyState will be 2 }; Value A number which is one of the three possible state constants define for the FileReader API. Specifications Specification Status Comment File APIThe definition of 'readyState' in that specification. Working Draft Initial definition ...
FileReader - Web APIs
cations for details and examples. Properties FileReader.error Read only A DOMException representing the error that occurred while reading the file. FileReader.readyState Read only A number indicating the state of the FileReader. This is one of the following: EMPTY 0 No data has been loaded yet. LOADING 1 Data is currently being loaded. DONE 2 The entire read request has been completed. FileReader.result Read only The file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation. Event handlers FileReader.onabort A handler for the abort event. This event is triggered each time the reading...
... the reading operation is completed (either in success or failure). FileReader.onprogress A handler for the progress event. This event is triggered while reading a Blob content. As FileReader inherits from EventTarget, all those events can also be listened for by using the addEventListener method. Methods FileReader.abort() Aborts the read operation. Upon return, the readyState will be DONE. FileReader.readAsArrayBuffer() Starts reading the contents of the specified Blob, once finished, the result attribute contains an ArrayBuffer representing the file's data. FileReader.readAsBinaryString() Starts reading the contents of the specified Blob, once finished, the result attribute contains the raw binary data from the file as a string. FileReader.readAsDataURL() Starts reading th...
FileSystemDirectoryReader.readEntries() - Web APIs
it as its text content, and then appends it to the container. The container is always a list element in this example, as you'll see shortly. Once the current item is in the list, the item's isDirectory property is checked. If the item is a directory, we need to recurse into that directory. The first step is to create a FileSystemDirectoryReader to handle fetching the directory's contents. That's done by calling the item's createReader() method. Then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy. After that, directoryReader.readEntries() is called to read in all the entries in the directory. These are each, in turn, passed into a recursive call to scanFiles() to process them. Any of them which a...
...fault(); listing.innerHTML = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitGetAsEntry(); if (item) { scanFiles(item, listing); } } }, false); This fetches the list of DataTransferItem objects representing the items dropped from event.dataTransfer.items. Then we call Event.preventDefault() to prevent the event from being handled further after we're done. Now it's time to start building the list. First, the list is emptied by setting listing.innerHTML to be empty. That leaves us with an empty ul to begin inserting directory entries into. Then we iterate over the items in the list of dropped items. For each one, we call its webkitGetAsEntry() method to obtain a FileSystemEntry representing the file. If that's successful, we call scanFiles() to p...
FileHandle API - Web APIs
pshot = this.result; } Managing progress All the methods from the LockedFile interface return a FileRequest object. Such an object is basically a DOMRequest with an extra power: it allows to monitor the progress of an operation. Sometimes writing and reading operations can be very long, therefore it is a good idea to monitor the operation to provide feedback to the user. Such monitoring can be done using the FileRequest.onprogress event handler. var progress = document.querySelector('progress'); var myFile = myFileHandle.open('readonly'); // Let's read a 1GB file var action = myFile.readAsArrayBuffer(1000000000); action.onprogress = function (event) { if (progress) { progress.value = event.loaded; progress.max = event.total; } } action.onsuccess = function () { conso...
...ause to access the file, a LockedFile object is required and operations on such object are performed in isolation, meaning that once a LockedFile is active, all operations of this LockedFile are guaranteed to happen sequentially on the underlying file without being interleaved with operations from other LockedFile. Secured write operation For performance reasons, write (and read) operations are done in memory. Periodically, the results of those operation are asynchronously flushed to the device storage area. If for some reason a problem occurs before that, you can lose the results of some operations. To avoid that problem, you can force the data to be flushed by using the LockedFile.flush() method. Once this method has been successfully called, you can be sure your change on the file will be...
Using the Gamepad API - Web APIs
mepaddisconnected", function(e) { gamepadInfo.innerHTML = "Waiting for gamepad."; cancelRequestAnimationFrame(start); }); Chrome does things differently here. Instead of constantly storing the gamepad's latest state in a variable it only stores a snapshot, so to do the same thing in Chrome you have to keep polling it and then only use the Gamepad object in code when it is available. We have done this below using Window.setInterval(); once the object is available the gamepad info is outputted, the game loop is started, and the interval is cleared using Window.clearInterval(). Note that in older versions of Chrome Navigator.getGamepads() is implemented with a webkit prefix. We attempt to detect and handle both the prefixed version and the standard version of the function for backwards comp...
...es appropriately, then update the left and top properties, changing their values to the current values of a and b respectively. This has the effect of moving the ball around the screen. In current versions of Chrome (version 34 as of this writing) the button values are stored as an array of double values, instead of GamepadButton objects. This is fixed in development versions. After all this is done, we use our requestAnimationFrame() to request the next animation frame, running gameLoop() again. function buttonPressed(b) { if (typeof(b) == "object") { return b.pressed; } return b == 1.0; } function gameLoop() { var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []); if (!gamepads) { return; } ...
Drag Operations - Web APIs
election. An OS-specific rendering of the selection will appear and follow the mouse pointer as the drag occurs. However, this behavior is only the default drag behavior, if no listeners adjust the data to be dragged. In HTML, apart from the default behavior for images, links, and selections, no other elements are draggable by default. To make other HTML elements draggable, three things must be done: Set the draggable="true" on the element that you wish to make draggable. Add a listener for the dragstart event. Set the drag data in the above listener. Here is an example which allows a section of content to be dragged. <p draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')"> This text <strong>may</strong> be dragged. </p> The draggabl...
...the drag leaves the element. This is the time when you should remove any insertion markers or highlighting. You do not need to cancel this event. Any highlighting or other visual effects specified using the :-moz-drag-over pseudoclass will be removed automatically. The dragleave event will always fire, even if the drag is cancelled, so you can always ensure that any insertion point cleanup can be done during this event. Performing a Drop When the user releases the mouse, the drag and drop operation ends. If the mouse is released over an element that is a valid drop target, that is, one that cancelled the last dragenter or dragover event, then the drop will be successful, and a drop event will fire at the target. Otherwise, the drag operation is cancelled, and no drop event is fired. During...
Intersection Observer API - Web APIs
ist of entries received by the callback includes one entry for each target which reporting a change in its intersection status. Check the value of the isIntersecting property to see if the entry represents an element that currently intersects with the root. Be aware that your callback is executed on the main thread. It should operate as quickly as possible; if anything time-consuming needs to be done, use Window.requestIdleCallback(). Also, note that if you specified the root option, the target must be a descendant of the root element. How intersection is calculated All areas considered by the Intersection Observer API are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle which encloses all of the element's parts. Similarly, if the visible...
... The target element's bounding rectangle (that is, the smallest rectangle that fully encloses the bounding boxes of every component that makes up the element) is obtained by calling getBoundingClientRect() on the target. This is the largest the intersection rectangle may be. ...
Notifications API - Web APIs
be displayed even when the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems, across different platforms. Concepts and usage On supported platforms, showing a system notification generally involves two things. ...
... compatible with existing notification systems, across different platforms. Concepts and usage On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the Notification.requestPermission() method. ...
PerformanceNavigation - Web APIs
This interface is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceNavigation interface represents information about how the navigation to the current document was done. An object of this type can be obtained by calling the Performance.navigation read-only attribute. Properties The PerformanceNavigation interface doesn't inherit any properties. PerformanceNavigation.type Read only An unsigned short which indicates how the navigation to this page was done. Possible values are: TYPE_NAVIGATE (0) The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar. TYPE_RELOAD (1) The page was accessed by clicking the Reloa...
...ission, or a script, or by typing the URL in the address bar. TYPE_RELOAD (1) The page was accessed by clicking the Reload button or via the Location.reload() method. TYPE_BACK_FORWARD (2) The page was accessed by navigating into the history. TYPE_RESERVED (255) Any other way. PerformanceNavigation.redirectCount Read only An unsigned short representing the number of REDIRECTs done before reaching the page. Methods The Performance interface doesn't inherit any methods. PerformanceNavigation.toJSON() Is a jsonizer returning a json object representing the PerformanceNavigation object. Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceNavigation' in that specification. Recommendation Initial def...
Using the Performance API - Web APIs
Web performance interfaces are defined in a suite of standards. ...
...eStamp) that is a discrete point in time. By calling this method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var startTime; var endTime; startTime = performance.now(); do_task(); endTime = performance.now(); return (endTime - startTime); } Serializing the Performance object JSON serialization of the Performance object is done via the toJSON() method. In the following example, JSON serialization for the Performance, Performance.timing and Performance.navigation objects is printed in the object element. function print_json() { var json; var o = document.getElementsByTagName("output")[0]; if (window.performance.toJSON === undefined) { json = "window.performance.toJSON() is NOT supported"; o.innerHTML += j...
RTCPeerConnection.setConfiguration() - Web APIs
t configuration of the RTCPeerConnection based on the values included in the specified RTCConfiguration object. This lets you change the ICE servers used by the connection and which transport policies to use. The most common use case for this method (and even then, probably not a very common use case) is to replace the set of ICE servers to be used. Two potential scenarios in which this might be done: The RTCPeerConnection was instantiated without specifying any ICE servers. If, for example, the RTCPeerConnection() constructor was called with no parameters, you would have to then call setConfiguration() to add ICE servers before ICE negotiation could begin. Renegotiation of the connection is needed, and a different set of ICE servers needs to be used for some reason. Perhaps the user has ...
...happens if configuration.peerIdentity or configuration.certificates is set and their values differ from the current configuration. InvalidStateError The RTCPeerConnection is closed. SyntaxError One or more of the URLs provided in the configuration.iceServers list is invalid. Example In this example, it has already been determined that ICE restart is needed, and that negotiation needs to be done using a different ICE server. var restartConfig = { iceServers: [{ urls: "turn:asia.myturnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; myPeerConnection.setConfiguration(restartConfig); myPeerConnection.createOffer({"iceRestart": true}).then(function(offer) { ...
RTCPeerConnection.setLocalDescription() - Web APIs
et. At that time, the offer can be sent to a remote peer via the signaling server. errorCallback A function matching the signature RTCPeerConnectionErrorCallback which gets called if the description can't be set. It is passed a single DOMException object explaining why the request failed. This deprecated form of the method returns instantaneously without waiting for the actual setting to be done: in case of success, the successCallback will be called; in case of failure, the errorCallback will be called. Deprecated exceptions When using the deprecated callback-based version of setLocalDescription(), the following exceptions may occur: InvalidStateError The connection's signalingState is "closed", indicating that the connection is not currently open, so negotiation cannot take pla...
...try { await offer = pc.createOffer(); pc.setLocalDescription(offer); signalRemotePeer({ description: pc.localDescription }); } catch(err) { reportError(err); } } This begins by creating an offer by calling createOffer(); when that succeeds, we call setLocalDescription(). We can then send the newly-created offer along to the other peer using the signaling server, which here is done by calling a function called signalRemotePeer(). Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.setLocalDescription()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.setRemoteDescription() - Web APIs
et. At that time, the offer can be sent to a remote peer via the signaling server. errorCallback A function matching the signautre RTCPeerConnectionErrorCallback which gets called if the description can't be set. It is passed a single DOMException object explaining why the request failed. This deprecated form of the method returns instantaneously without waiting for the actual setting to be done: in case of success, the successCallback will be called; in case of failure, the errorCallback will be called. Exceptions When using the deprecated callback-based version of setRemoteDescription(), the following exceptions may occur: InvalidStateError The connection's signalingState is "closed", indicating that the connection is not currently open, so negotiation cannot take place. Inval...
...aling server }) .catch(handleGetUserMediaError); } After creating our RTCPeerConnection and saving it as myPeerConnection, we pass the description included in the received offer message, msg, directly into setRemoteDescription() to tell the user agent's WebRTC layer what configuration the caller has proposed using. When our promise fulfillment handler is called, indicating that this has been done, we create a stream, add it to the connection, then create an SDP answer and call setLocalDescription() to set that as the configuration at our end of the call before forwarding that answer to the caller. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.setRemoteDescription()' in that...
RTCPeerConnection - Web APIs
This lets you change the ICE servers used by the connection and which transport policies to use.setIdentityProvider() The RTCPeerConnection.setIdentityProvider() method set...
...CIceGatheringState enum The RTCIceGatheringState enum defines string constants which reflect the current status of ICE gathering, as returned using the RTCPeerConnection.iceGatheringState property. You can detect when this value changes by watching for an event of type icegatheringstatechange. Constant Description "new" The peer connection was just created and hasn't done any networking yet. "gathering" The ICE agent is in the process of gathering candidates for the connection. "complete" The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to "gathering" to gather those candidates. ...
WebGLRenderingContext - Web APIs
hether the browser supports WebGL. To that end we will try to obtain the WebGL rendering context from a canvas element. The WebGL rendering context is an interface, through which you can set and query the state of the graphics machine, send data to the WebGL, and execute draw commands. Saving the state of the graphics machine within a single context interface is not unique to WebGL. This is also done in other graphics {{Glossary("API")}}, such as the canvas 2D rendering context. However, the properties and variables you can tweak are different for each API. Effect of canvas size on rendering with WebGL With scissor() and clear() we can demonstrate how the WebGL drawing buffer is affected by the size of the canvas. The size of the first canvas is set to the styled Element size, determined b...
...ics {{Glossary("API")}}, such as the canvas 2D rendering context. However, the properties and variables you can tweak are different for each API. Effect of canvas size on rendering with WebGL With scissor() and clear() we can demonstrate how the WebGL drawing buffer is affected by the size of the canvas. The size of the first canvas is set to the styled Element size, determined by CSS. This is done by assigning the width and height properties of the canvas to the values of the clientWidth and clientHeight properties, respectively. In contrast, no such assignment is done for the second canvas. The internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas Element in the browser window. The effect is clearly visible wh...
Color masking - Web APIs
des of yellow (including shades of orange, brown, olive and yellow-green), the complementary of blue. Similarly, masking only green would give us shades of magenta (also purples, crimsons, and so on), and masking only red would give shades of cyan (also sea greens, blues, and so on). Note that the calls to colorMask() only occur when the user clicks on one of the toggle buttons. But rendering is done every second, using the timer. The color mask state of WebGL is preserved, so we do not need to call colorMask() every frame to set up the color mask. This is an important aspect of the WebGL state machine. It allows us to setup WebGL in a single initialization phase, and then just execute drawing commands for each frame. Color masking gives you fine control of updating pixel values on the scree...
...at are written by each drawing command, you can use each channel, for example, to store a different grayscale image. Alternatively, you may use the RGB components for color, but the alpha component for some custom pixel data of your invention. Finally, color masking teaches us that WebGL is not only a state machine, it is also a graphics pipeline. This means that graphics operations in WebGL are done in a certain order, where the output of each operation serves as the input of the next. So, for example, clearing operation sets the value of each pixel to the chosen clear color. Masking occurs later in the pipeline, and modifies the pixel color value, so the final result on the screen is that of the clear color, tinted by the color mask. <p>Tinting the displayed colors with color masking.</p...
Lifetime of a WebRTC session - Web APIs
. This page is currently under construction, and some of the content will move to other pages as the WebRTC guide material is built out. Pardon our dust! Establishing the connection The Internet is big. Really big. It's so big that years ago, smart people saw how big it was, how fast it was growing, and the limitations of the 32-bit IP addressing system, and realized that something had to be done before we ran out of addresses to use, so they started working on designing a new 64-bit addressing system. But they realized that it would take longer to complete the transition than 32-bit addresses would last, so other smart people came up with a way to let multiple computers share the same 32-bit IP address. Network Address Translation (NAT) is a standard which supports this address sharing b...
...at the channel for performing signaling doesn't even need to be over the network. One peer can output a data object that can be printed out, physically carried (on foot or by carrier pigeon) to another device, entered into that device, and a response then output by that device to be returned on foot, and so forth, until the WebRTC peer connection is open. It'd be very high latency but it could be done. Information exchanged during signaling There are three basic types of information that need to be exchanged during signaling: Control messages used to set up, open, and close the communication channel, and to handle errors. Information needed in order to set up the connection: the IP addressing and port information needed for the peers to be able to talk to one another. Media capability n...
A simple RTCDataChannel sample - Web APIs
ther the connection should support audio, video, or both. In our simple example, we don't have any constraints. If the offer is created successfully, we pass the blob along to the local connection's RTCPeerConnection.setLocalDescription() method. This configures the local end of the connection. The next step is to connect the local peer to the remote by telling the remote peer about it. This is done by calling remoteConnection.RTCPeerConnection.setRemoteDescription(). Now the remoteConnection knows about the connection that's being built. In a real application, this would require a signaling server to exchange the description object. That means it's time for the remote peer to reply. It does so by calling its createAnswer() method. This generates a blob of SDP which describes the connection...
...andleReceiveMessage; receiveChannel.onopen = handleReceiveChannelStatusChange; receiveChannel.onclose = handleReceiveChannelStatusChange; } The datachannel event includes, in its channel property, a reference to a RTCDataChannel representing the remote peer's end of the channel. This is saved, and we set up, on the channel, event listeners for the events we want to handle. Once this is done, our handleReceiveMessage() method will be called each time data is received by the remote peer, and the handleReceiveChannelStatusChange() method will be called any time the channel's connection state changes, so we can react when the channel is fully opened and when it's closed. Handling channel status changes Both our local and remote peers use a single method to handle events indicating a c...
Using DTMF with WebRTC - Web APIs
onnection between them, then waits for the user to click a "Dial" button. When the button is clicked, a DTMF string is sent over the connection using RTCDTMFSender.insertDTMF(). Once the tones finish transmitting, the connection is closed. Note: This example is obviously somewhat contrived, since normally the two RTCPeerConnection objects would exist on different devices, and signaling would be done over the network instead of it all being simply linked up inline as it is here. HTML The HTML for this example is very basic; there are only three elements of importance: An <audio> element to play the audio received by the RTCPeerConnection being "called." A <button> element to trigger creating and connecting the two RTCPeerConnection objects, then sending the DTMF tones. A <div> to rece...
...hed playing, tone is an empty string; when that's the case, RTCDTMFSender.toneBuffer is empty. In this example, we log to the screen which tone just finished playing. In a more advanced application, you might update the user interface, for example, to indicate which note is currently playing. On the other hand, if the tone buffer is empty, our example is designed to disconnect the call. This is done by stopping each stream on both the caller and the receiver by iterating over each RTCPeerConnection's track list (as returned by its getTracks() method) and calling each track's stop() method. Once both the caller's and the receiver's media tracks are all stopped, we pause the <audio> element and set its srcObject to null. This detaches the audio stream from the <audio> element. Then, finally,...
Fundamentals of WebXR - Web APIs
nal movement detection, but to capture more substantial movement through the space, external sensors are usually required, such as cameras (either using visible light or infrared). WebXR session modes WebXR offers support for both augmented reality (AR) and virtual reality (VR) sessions, using the same API. Which type of session you want to create is specified when creating the session. This is done by specifying the appropriate session mode string for the kind of session you want to create. Virtual reality In a VR environment, the entire image is digitally created by your app or site, from foreground objects all the way to the background or skybox. Your frame drawing code will have to redraw every pixel of each view during each frame in order to avoid the potential of artifacts being left...
...reedom the user has. Goggles and glasses XR goggles are similar to headsets in that they involve the placing of graphics display surfaces in front of the eyes in order to render the views of a scene needed to simulate the depth of the simulated scene. The difference is that the goggles pass through the real world, overlaying the rendered image on top of the user's physical environment. This is done without digitally reproducing the world, as would be necessary with a full headset. Instead, the display surface is transparent, and if not displaying anything is essentially identical to wearing regular eyeglasses. When objects are drawn, they are drawn onto the goggles' lenses, either partially or completely blocking the physical environment from being seen through the obscured portion of the l...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
pace to an offset (or vice-versa, since the result is the same) to determine the transform matrix that represents the resulting location in the space's coordinate system. Poses Once your reference space or spaces are established for the various key objects in the scene, you will have times when you need to describe another position relative to the origin of a particular reference space. This is done using poses. A pose, simply put, describes a position and orientation relative to the origin of the reference space from which it was created. In WebXR, a pose is represented by an XRPose object, whose transform property is an XRRigidTransform defining the transform matrix that, applied to any coordinate, vector, or matrix in the original space, converts it to the target space. Thus a pose can b...
...wer pose, viewerPose, can in turn be used to compute positions and orientations to properly render the objects in the scene given the user's point of view. Offsetting or moving reference spaces While you can't change a reference space since both XRReferenceSpace and XRBoundedReferenceSpace are read-only, you can easily create new reference spaces by applying an offset transform to them. This is done by calling the reference space's getOffsetReferenceSpace() method. Offsetting positions within a reference space The simplest case for using getOffsetReferenceSpace() is to transform a point or matrix within the context of the same space. For example, to create a new reference space that moves the reference space aRefSpace a half meter in each direction, you can do something like this: let hal...
Background audio processing using AudioWorklet - Web APIs
resume(); await audioContext.audioWorklet.addModule("module-url/module.js"); } catch(e) { return null; } } return new AudioWorkletNode(audioContext, "processor-name"); } This createMyAudioProcessor() function creates and returns a new instance of AudioWorkletNode configured to use your audio processor. It also handles creating the audio context if it hasn't already been done. In order to ensure the context is usable, this starts by creating the context if it's not already available, then adds the module containing the processor to the worklet. Once that's done, it instantiates and returns a new AudioWorkletNode. Once you have that in hand, you connect it to other nodes and otherwise use it just like any other node. You can then create a new audio processor node by ...
...ode in place and ready to use. Supporting audio parameters Just like any other Web Audio node, AudioWorkletNode supports parameters, which are shared with the AudioWorkletProcessor that does the actual work. Adding parameter support to the processor To add parameters to an AudioWorkletNode, you need to define them within your AudioWorkletProcessor-based processor class in your module. This is done by adding the static getter parameterDescriptors to your class. This function should return an array of AudioParam objects, one for each parameter supported by the processor. In the following implementation of parameterDescriptors(), the returned array has two AudioParam objects. The first defines gain as a value between 0 and 1, with a default value of 0.5. The second parameter is named frequen...
Web audio spatialization basics - Web APIs
The boombox sits inside a room (defined by the edges of the browser viewport), and in this demo, we can move and rotate it with the provided controls. When we move the boombox, the sound it produces changes accordingly, panning as it moves to the left or right of the room, or becoming quieter as it is moved away from the user or is rotated so the speakers are facing away from them, etc. This is done by setting the different properties of the PannerNode object instance in relation to that movement, to emulate spacialization. Note: The experience is much better if you use headphones, or have some kind of surround sound system to plug your computer into. Creating an audio listener So let's begin! The BaseAudioContext (the interface the AudioContext is extended from) has a listener property...
... ...
Window.open() - Web APIs
Web › API › Window › open
tring, then a new blank, empty window (URL about:blank) is created with the default toolbars of the main window. Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously. Examples var windowObjectReference; var windowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; function openRequestedPopup() { windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", windowFeatures); } var windowObjectReference; function openRequestedPopup() { windowObjectReference = window.open( "http://www.domainnam...
...secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window, which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop that cannot be recycled, reused. In any case, if your code is well done, it should not interfere with the user's final choice but rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser). Glossary Opener window, parent window, main window, first window Terms often used to describe or to identify the same window. It is the window from which a new window will be created. It is the window on which the user clic...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
t tincidunt. </div> <h1>JavaScript Typewriter</h1> <div id="article"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit v...
...ype="submit" value="Send" /> </form> <p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum condimentum feugiat.</p> <p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vita...
WritableStream.WritableStream() - Web APIs
nderlyingSink An object containing methods and properties that define how the constructed stream instance will behave. underlyingSink can contain the following: start(controller) Optional This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The controller parameter passed to this method is a WritableStreamDefaultController. This can be used by the developer to control the stream during set up. 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 w...
... set when creating the counting strategy (line 35), sets the maximum amount of data that the WritableStream instance will handle in a single write() operation. In this example, it's the maximum amount of data that can be sent to defaultWriter.write() (line 11). The defaultWriter.ready property returns a promise that resolves when the sink (the first property of the WritableStream constructor) is done writing data. The data source can wither write more data (line 11) or call close() (line 24). Calling close() too early can prevent data from being written. This is why the example calls defaultWriter.ready twice (lines 9 and 22). The Promise returned by the sink's write() method (line 40) tells the WritableStream and its writer when to resolve defaultWriter.ready. Specifications Sp...
XMLHttpRequest.responseText - Web APIs
quest or null if the request failed or "" if the request has not yet been sent by calling send(). While handling an asynchronous request, the value of responseText always has the current content received from the server, even if it's incomplete because the data has not been completely received yet. You know the entire content has been received when the value of readyState becomes XMLHttpRequest.DONE (4), and status becomes 200 ("OK"). Exceptions InvalidStateError The XMLHttpRequest.responseType is not set to either the empty string or "text". Since the responseText property is only valid for text content, any other value is an error condition. Example var xhr = new XMLHttpRequest(); xhr.open('GET', '/server', true); // If specified, responseType must be empty string or "text" xhr.re...
...tpRequest.responseType is not set to either the empty string or "text". Since the responseText property is only valid for text content, any other value is an error condition. ...
XMLHttpRequest.status - Web APIs
response. Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors. ...
...HttpRequest errors. ...
XMLHttpRequest.statusText - Web APIs
ng. If the server response doesn't explicitly specify a status text, statusText will assume the default value "OK". ...
...le var xhr = new XMLHttpRequest(); console.log('0 UNSENT', xhr.statusText); xhr.open('GET', '/server', true); console.log('1 OPENED', xhr.statusText); xhr.onprogress = function () { console.log('3 LOADING', xhr.statusText); }; xhr.onload = function () { console.log('4 DONE', xhr.statusText); }; xhr.send(null); /** * Outputs the following: * * 0 UNSENT * 1 OPENED * 3 LOADING OK * 4 DONE OK */ Specifications Specification Status Comment XMLHttpRequest Living Standard WHATWG living standard ...
XRInputSource - Web APIs
pointer, or screen. targetRaySpaceRead only An XRSpace object defining the origin of the target ray and the direciton in which it extends. This space is established using the method defined by targetRayMode. Methods The XRInputSource interface defines no methods. Usage notes Actions and the target ray If the device provides an indication of the direction in which it is pointed, this is done using a target ray. This is a ray extending from the position of the device outward in the direction in which it is pointed. A target ray emitted by a hand controller. If the device includes a trigger or other squeezable input, such as a hand gesture device that recognizes when the user squeezes their fist, that action is called a primary squeeze action. A primary squeeze action should corr...
... action. A primary action may occur when the user presses a button, clicks on a touchpad or the top button of a thumb stick, or uses a hand gesture or spoken command that invokes the button-like action. When a primary action begins, a selectstart event is sent to the XRSession. When the action has completed (such as when the user releases the button), a select event is sent. Finally, once that is done--or if the user aborts the action--a selectend event is sent to the session object. An action may be aborted either by the user in some device-specific fashion or if the input device is disconnected before the action is completed. Local coordinate system Each input source has its own local coordinate system, which is described by the gripSpace property, which is an XRSpace used to map the inpu...
XRReferenceSpace - Web APIs
ration of the XRSession. To do that, call the XRSession method requestReferenceSpace(), specifying the reference space type you wish to obtain. xrSession.requestReferenceSpace("local").then((refSpace) => { xrReferenceSpace = refSpace; /* ... */ }); The other situation in which you may need to acquire a new reference space is if you need to move the origin to a new position; this is commonly done, for example, when your project allows the user to move through the environment using input devices such as the keyboard, mouse, touchpad, or game controls that are not connected through the XR device. Since the origin will typically be the user's location in the space, you need to change the origin to reflect their movement and any orientation changes they make. To move or rotate the user's vie...
...y be the user's location in the space, you need to change the origin to reflect their movement and any orientation changes they make. To move or rotate the user's view of the world, you need to change the XRReferenceSpace used to represent that viewpoint. However, XRReferenceSpace is immutable, so you need to instead create a new reference space representing the changed viewpoint. This is easily done using the getOffsetReferenceSpace() method. let offsetTransform = new XRRigidTransform({x: 2, y: 0, z: 1}, {x: 0, y: 1, z: 0, w: 1}); xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace(offsetTransform); This replaces the XRReferenceSpace with a new one whose origin and orientation are adjusted to place the new origin at (2, 0, 1) relative to t...
ARIA Test Cases - Accessibility
e useful for some readers. For more up-to-date examples, see the OpenAjaxAlliance ARIA examples page. Or copy-paste: http://oaa-accessibility.org/examples/ For each example we test the "Expected" results with assistive technologies, for each browser that AT supports WAI-ARIA in. Where a failure occurs we will test the browser for API incorrectness, using tools such as MSAA Inspect. This must be done in order to determine where to file a bug (browser or AT). There are several purposes for providing this information: Help browser vendors provide correct implementations Help AT vendors provide correct implementations Inform authors as to what actually works reliably In general we're testing with the latest public releases. However, where things don't work we may test with nightly builds...
... Window-Eyes - - - - NVDA - n/a - - Zoom (Leopard) pass n/a pass pass ZoomText - - - - Orca - - - - Menu Button dojo nightly build Expected AT Behavior: Screen readers should indicate that this button has an associated menu. Screen magnifiers should give indication (if this is not done visually anyway). When the button is pressed, the menu should be tracked like any other menu. When closing the menu, this should be indicated, and focus should be repeated for the menu button the menu was opened from, or the new focus location if the activated menu item results in that. Markup used: Notes: Results: AT Firefox IE Opera Safari JAWS 9 - - ...
Alerts - Accessibility
The problem You have a form -- a contact form, for example -- that you want to put some accessible error checking into. Examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname. The form First, please read about the aria-required technique if you have not done so, as this technique expands upon that. Here is a simple form: <form method="post" action="post.php"> <fieldset> <legend>Please enter your contact details</legend> <label for="name">Your name (required):</label> <input name="name" id="name" aria-required="true"/> <br /> <label for="email">E-Mail address (required):</label> <input name="email" id="email" aria-required="true"/> <br /> <label f...
...ant to give an indication that this is a required field. Q. Why don't you set focus back to the invalid field automatically? A. Because this is not allowed by the Windows API specs, and possibly others. Also, letting the focus jump around without real user interaction too often is not a nice thing to do in general. TBD: let's rethink this -- personally, I think setting focus might be good if done without causing a keyboard trap. ...
Architecture - Accessibility
object are an exact match to the links it exposes. The implementation simply doesn't create AtkObjects for a whitespace or text leaf nsIAccessibles. See the ATK uses of IsEmbeddedObject() for more information on how we do this. IAccessible2: Same as nsIAccessible. Text and whitespace leaf nodes are exposed, but are redundant with the information in the parent object's nsIAccessibleText. This is done for backward compatibility with older MSAA clients which didn't have access to a text interface. The children of a Hypertext object are a superset of the links it exposes. The new system makes it easier to show caret positions etc., which will be an improvement in IA2 over MSAA. Example Take the following HTML code: <div>Hello<a href="http://www.mozilla.org/access">My link<img src="image.gif">i...
... If the next character does not exist, proceed to the next accessible in depth first search order and recurse on the first character until a non-embed is found. If the current character falls within a text substring, locate the line ending of that substring or the next embed, whichever comes first: Get the current line ...
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
sed flex item is removed from rendering entirely, but leaves behind a "strut" that keeps the flex line's cross-size stable. Thus, if a flex container has only one flex line, dynamically collapsing or uncollapsing items may change the flex container's main size, but is guaranteed to have no effect on its cross size and won't cause the rest of the page's layout to "wobble". Flex line wrapping is re-done after collapsing, however, so the cross-size of a flex container with multiple lines might or might not change." - Collapsed items This behaviour is useful if you want to target flex items using JavaScript to show and hide content for example. The example in the specification demonstrates one such pattern. In the following live example I have a non-wrapped flex container. The third item has mo...
...ity: collapse from the CSS or change the value to visible, you will see the item disappear and the space redistribute between non-collapsed items; the height of the flex container should not change. Note: Use Firefox for the below two examples as Chrome and Safari treat collapse as hidden. When dealing with multiple-line flex containers however you need to understand that the wrapping is re-done after collapsing. So the browser needs to re-do the wrapping behaviour to account for the new space that the collapsed item has left in the inline direction. This means that items might end up on a different line to the one they started on. In the case of an item being shown and hidden it could well cause the items to end up in a different row. I have created this behaviour in the next live exa...
break-after - CSS: Cascading Style Sheets
avoid-region; break-after: region; /* Global values */ break-after: inherit; break-after: initial; break-after: unset; Each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. To determine if a break must be done, the following rules are applied: If any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. If more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has precedence over the break-inside ...
...ent condimentum dui dui, sit amet rutrum diam tincidunt eu. Cras suscipit porta leo sit amet rutrum. Sed vehicula ornare tincidunt. Curabitur a ipsum ac diam mattis volutpat ac ut elit. Nullam luctus justo non vestibulum gravida. Morbi metus libero, pharetra non porttitor a, molestie nec nisi.</p> <h2>Subheading</h2> <p>Vivamus eleifend metus vitae neque placerat, eget interdum elit mattis. Donec eu vulputate nibh. Ut turpis leo, malesuada quis nisl nec, volutpat egestas tellus. <h2>Subheading</h2> <p>In finibus viverra enim vel suscipit. Quisque consequat velit eu orci malesuada, ut interdum tortor molestie. Proin sed pellentesque augue. Nam risus justo, faucibus non porta a, congue vel massa. Cras luctus lacus nisl, sed tincidunt velit pharetra ac. Duis suscipit faucibus dui sed ...
break-before - CSS: Cascading Style Sheets
id-region; break-before: region; /* Global values */ break-before: inherit; break-before: initial; break-before: unset; Each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. To determine if a break must be done, the following rules are applied: If any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. If more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has precedence over the break-inside ...
...ent condimentum dui dui, sit amet rutrum diam tincidunt eu. Cras suscipit porta leo sit amet rutrum. Sed vehicula ornare tincidunt. Curabitur a ipsum ac diam mattis volutpat ac ut elit. Nullam luctus justo non vestibulum gravida. Morbi metus libero, pharetra non porttitor a, molestie nec nisi.</p> <h2>Subheading</h2> <p>Vivamus eleifend metus vitae neque placerat, eget interdum elit mattis. Donec eu vulputate nibh. Ut turpis leo, malesuada quis nisl nec, volutpat egestas tellus. <h2>Subheading</h2> <p>In finibus viverra enim vel suscipit. Quisque consequat velit eu orci malesuada, ut interdum tortor molestie. Proin sed pellentesque augue. Nam risus justo, faucibus non porta a, congue vel massa. Cras luctus lacus nisl, sed tincidunt velit pharetra ac. Duis suscipit faucibus dui sed ...
text-emphasis-position - CSS: Cascading Style Sheets
d therefore are not reset either, using the text-emphasis shorthand property. Formal definition Initial valueover rightApplies toall elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax [ over | under ] && [ right | left ] Examples Preferring ruby over emphasis marks Some editors prefer to hide emphasis marks when they conflict with ruby. ...
...mal syntax [ over | under ] && [ right | left ] Examples Preferring ruby over emphasis marks Some editors prefer to hide emphasis marks when they conflict with ruby. In HTML, this can be done with the following style rule: ruby { text-emphasis: none; } Preferring emphasis marks over ruby Some other editors prefer to hide ruby when they conflict with emphasis marks. In HTML, this can be done with the following pattern: em { text-emphasis: dot; /* Set text-emphasis for <em> elements */ } em rt { display: none; /* Hide ruby inside <em> elements */ } Specifications Specification Status Comment CSS Text Decoration Module Level 3The definition of 'text-emphasis' in that specification. Candidate Recommendation Initial definition ...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
and sensitive pieces of a browser. It controls how your HTML source code is turned into web pages and, as such, changes to it are rare. The new parser is faster, complies with the HTML5 standard, and enables a lot of new functionality as well. The new parser introduces these major improvements: You can now use SVG and MathML inline in HTML5 pages, without XML namespace syntax. Parsing is now done in a separate thread from Firefox's main UI thread, improving overall browser responsiveness. Calls to innerHTML are a lot faster. Dozens of long-standing parser related bugs are now fixed. The HTML5 specification provides a more detailed description than previous HTML standards of how to turn a stream of bytes into a DOM tree. This will result in more consistent behavior across browser imple...
...tags that match this pattern, and they will behave differently with Gecko 2. Calling document.write() during parsing Prior to HTML5, Gecko and WebKit allowed calls to document.write() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call to document.open(), replacing the document. In HTML5, document.write() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write() in any other context either are ignored or replace the docum...
<dfn>: The Definition element - HTML: Hypertext Markup Language
Web › HTML › Element › dfn
th an id attribute, "definition-dfn", which can be used as the target of a link. Later on, a link is created using <a> with the href attribute set to "#definition-dfn" to set up the link back to the definition. Result The resulting content looks like this: Using abbreviations and definitions together In some cases, you may wish to use an abbreviation for a term when defining it. This can be done by using the <dfn> and <abbr> elements in tandem, like this: HTML <p>The <dfn><abbr title="Hubble Space Telescope">HST</abbr></dfn> is among the most productive scientific instruments ever constructed. It has been in orbit for over 20 years, scanning the sky and returning data and photographs of unprecedented quality and detail.</p> <p>Indeed, the <abbr title="Hubble Space Telescope">HST</abbr...
...dfn> and <abbr> elements in tandem, like this: HTML <p>The <dfn><abbr title="Hubble Space Telescope">HST</abbr></dfn> is among the most productive scientific instruments ever constructed. It has been in orbit for over 20 years, scanning the sky and returning data and photographs of unprecedented quality and detail.</p> <p>Indeed, the <abbr title="Hubble Space Telescope">HST</abbr> has arguably done more to advance science than any device ever built.</p> Note the <abbr> element nested inside the <dfn>. The former establishes that the term is an abbreviation ("HST") and specifies the full term ("Hubble Space Telescope") in its title attribute. The latter indicates that the abbreviated term represents a term being defined. Result The output of the above code looks like this: Specificatio...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. As all input types except for input of type hidden are focusable, this attribute should not be used on form controls, because doing so would require the management of the focus order for all elements within the document with the risk of harming usability and accessibility if done incorrectly. title Global attribute valid for all elements, including all input types, containing a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip. The title should NOT be used as the primary explanation of the purpose of the form control. Instead, use the <label> element...
...ill be taken if the user presses the Enter or Return key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard. Note: This has been standardized as the global attribute enterkeyhint, but is not yet widely implemented. To see the status of the change being implemented in Firefox, see bug 1490661. Permitted values are: go, done, next, search, and send. The browser decides, using this hint, what label to put on the enter key. orient results The results attribute--supported only by Safari--is a numeric value that lets you override the maximum number of entries to be displayed in the <input> element's natively-provided drop-down menu of previous search queries. The value must be a non-negative decimal number. If ...
HTTP conditional requests - HTTP
ical to the one it is compared too. This is mandatory for some conditional headers, and the default for the others. Strong validation is very strict and may be difficult to guarantee at the server level, but it does guarantee no data loss at any time, sometimes at the expense of performance. It is quite difficult to have a unique identifier for strong validation with Last-Modified. Often this is done using an ETag with the MD5 hash of the resource (or a derivative). Weak validation Weak validation differs from strong validation, as it considers two versions of the document as identical if the content is equivalent. For example, a page that would differ from another only by a different date in its footer, or different advertising, would be considered identical to the other with weak validati...
...in. If the resource has changed, the server just sends back a 200 OK response, with the new version of the resource, like if the request wasn't conditional and the client uses this new resource (and caches it). Besides the setting of the validators on the server side, this mechanism is transparent: all browsers manage a cache and send such conditional requests without any special work to be done by Web developers. 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 already obtained information: A server supporting partial downloads broadcasts this by sending the Accept-Ranges header. Once this happens, the client can resume a download by sending a Ranges header wi...
Index - HTTP
Web › HTTP › Headers › Index
ference, Request header The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending on the context where the request is done: when fetching a CSS stylesheet a different value is set for the request than when fetching an image, video or a script. 3 Accept-Charset Content Negotiation, HTTP, HTTP Header, Reference, Request header The Accept-Charset request HTTP header advertises which character set the client is able to understand. Using content negotiation, the server then selects one of the proposal...
...e control over the data stored locally by a browser for their origins. 21 Connection HTTP, Headers, Reference, Web The Connection general header controls whether or not the network connection stays open after the current transaction finishes. If the value sent is keep-alive, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. 22 Content-Disposition HTTP, Reference, header In a multipart/form-data body, the HTTP Content-Disposition general header is a header that can be used on the subpart of a multipart body to give information about the field it applies to. The subpart is delimited by the boundary defined in the Content-Type header. Used on the body itself, Content-Disposition has no effect. ...
A re-introduction to JavaScript (JS tutorial) - JavaScript
lorer 3. It was a mostly-compatible JavaScript work-alike. Several months after that, Netscape submitted JavaScript to Ecma International, a European standards organization, which resulted in the first edition of the ECMAScript standard that year. The standard received a significant update as ECMAScript edition 3 in 1999, and it has stayed pretty much stable ever since. The fourth edition was abandoned, due to political differences concerning language complexity. Many parts of the fourth edition formed the basis for ECMAScript edition 5, published in December of 2009, and for the 6th major edition of the standard, published in June of 2015. Because it is more familiar, we will refer to ECMAScript as "JavaScript" from this point on. Unlike most programming languages, the JavaScript language...
...r charsInBody = (function counter(elm) { if (elm.nodeType == 3) { // TEXT_NODE return elm.nodeValue.length; } var count = 0; for (var i = 0, child; child = elm.childNodes[i]; i++) { count += counter(child); } return count; })(document.body); The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging. Note that JavaScript functions are themselves objects -- like everything else in JavaScript -- and you can add or change properties on them just like we've seen earlier in the Objects section. Custom objects For a more detailed discussion of obj...
Array.from() - JavaScript
rn function getItem(k) { return isIterator ? iterator.next() : items[k]; }; }; var getArray = function getArray( T, A, len, getItem, isIterator, mapFn ) { // 16. Let k be 0. var k = 0; // 17. Repeat, while k < len... ...
... getItem, isIterator, mapFn ) { // 16. Let k be 0. var k = 0; // 17. Repeat, while k < len... ...
FinalizationRegistry.prototype.unregister() - JavaScript
en later unregistering it via unregister: class Thingy { #cleanup = label => { // ^^^^^----- held value console.error( `The \`release\` method was never called for the object with the label "${label}"` ); }; #registry = new FinalizationRegistry(this.#cleanup); /** * Constructs a `Thingy` instance. Be sure to call `release` when you're done with it. * * @param label A label for the `Thingy`. */ constructor(label) { // vvvvv----- held value this.#registry.register(this, label, this); // target -----^^^^ ^^^^----- unregister token } /** * Releases resources held by this `Thingy` instance. */ release() { this.#r...
...bject using a different object as its unregister token: { // ^^^^----- held value console.error( `The \`release\` method was never called for the \`Thingy\` for the file "${file.name}"` ); }; #registry = new FinalizationRegistry(this.#cleanup); /** * Constructs a `Thingy` instance for the given file. Be sure to call `release` when you're done with it. * * @param filename The name of the file. */ constructor(filename) { this.#file = File.open(filename); // vvvvv----- held value this.#registry.register(this, label, this.#file); // target -----^^^^ ^^^^^^^^^^----- unregister token } /** * Releases resources held by this `Thin...
Generator.prototype.return() - JavaScript
The return() method returns the given value and finishes the generator. Syntax gen.return(value) Parameters value The value to return. Return value The value that is given as an argument. Examples Using return() The following example shows a simple generator and the return method. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } If return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. If no argument is provided, the value property of returned object is the same as if .next(). If an argument is provided, it will be set to the value of the v...
...alled on a generator that is already in "completed" state, the generator will remain in "completed" state. If no argument is provided, the value property of returned object is the same as if .next(). If an argument is provided, it will be set to the value of the value property of the returned object. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done: true } g.return(); // { value: undefined, done: true } g.return(1); // { value: 1, done: true } Specifications Specification ECMAScript (ECMA-262)The definition of 'Generator.prototype.return' in that specification. ...
Generator.prototype.throw() - JavaScript
The throw() method resumes the execution of a generator by throwing an error into it and returns an object with two properties done and value. Syntax gen.throw(exception) Parameters exception The exception to throw. For debugging purposes, it is useful to make it an instanceof Error. Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using throw() The followin...
...he iterator. Can be omitted when done is true. Examples Using throw() The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual. function* gen() { while(true) { try { yield 42; } catch(e) { console.log('Error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new Error('Something went wrong')); // "Error caught!" // { value: 42, done: false } Specifications Specification ECMAScript (ECMA-262)The definition of 'Generator.prototype.throw' in that specification. ...
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
default locale. Description Returns an array with a subset of the language tags provided in locales. The language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. Examples Using supportedLocalesOf Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decid...
...German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well. var locales = ['ban', 'id-u-co-pinyin', 'de-ID']; var options = { localeMatcher: 'lookup' }; console.log(Intl.DateTimeFormat.supportedLocalesOf(locales, options).join(', ')); // -> "id-u-co-pinyin, de-ID" Specifications Specification ...
Intl.DisplayNames.supportedLocalesOf() - JavaScript
default locale. Description Returns an array with a subset of the language tags provided in locales. The language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. Examples Using supportedLocalesOf Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decid...
...German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well. const locales = ['ban', 'id-u-co-pinyin', 'de-ID']; const options = { localeMatcher: 'lookup' }; console.log(Intl.DisplayNames.supportedLocalesOf(locales, options).join(', ')); // -> "id-u-co-pinyin, de-ID" Specifications Specification...
Intl.ListFormat.supportedLocalesOf() - JavaScript
default locale. Description Returns an array with a subset of the language tags provided in locales. The language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. Examples Using supportedLocalesOf Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decid...
...German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well. const locales = ['ban', 'id-u-co-pinyin', 'de-ID']; const options = { localeMatcher: 'lookup' }; console.log(Intl.ListFormat.supportedLocalesOf(locales, options).join(', ')); // -> "id-u-co-pinyin, de-ID" Specifications Specification ...
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
default locale. Description Returns an array with a subset of the language tags provided in locales. The language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. Examples Using supportedLocalesOf Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decid...
...German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the "lookup" algorithm here -- a "best fit" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well. const locales = ['ban', 'id-u-co-pinyin', 'de-ID']; const options = { localeMatcher: 'lookup' }; console.log(Intl.RelativeTimeFormat.supportedLocalesOf(locales, options).join(', ')); // -> "id-u-co-pinyin, de-ID" Specifications Specifi...
eval() - JavaScript
nesday Thursday Friday Saturday Sunday".split(" ")[a%7||0]})); There are also additional safer (and faster!) alternatives to eval() or Function() for common use-cases. Accessing member properties You should not use eval() to convert property names into properties. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with eval(): var obj = { a: 20, b: 30 }; var propName = getPropName(); // returns "a" or "b" eval( 'var result = obj.' + propName ); However, eval() is not necessary here. In fact, its use here is discouraged. Instead, use the property accessors, which are much faster and safer: var obj = { a: 20, b: 30 }; var propName = getPropName(); // returns "a" or "b" var result = obj[ propName ]; /...
... obj = { a: 20, b: 30 }; var propName = getPropName(); // returns "a" or "b" var result = obj[ propName ]; // obj[ "a" ] is the same as obj.a You can even use this method to access descendant properties. Using eval() this would look like: var obj = {a: {b: {c: 0}}}; var propPath = getPropPath(); // returns e.g. "a.b.c" eval( 'var result = obj.' + propPath ); Avoiding eval() here could be done by splitting the property path and looping through the different properties: function getDescendantProp(obj, desc) { var arr = desc.split('.'); while (arr.length) { obj = obj[arr.shift()]; } return obj; } var obj = {a: {b: {c: 0}}}; var propPath = getPropPath(); // returns e.g. "a.b.c" var result = getDescendantProp(obj, propPath); Setting a property that way works similarly: fun...
Spread syntax (...) - JavaScript
, as the following example shows. (The same is true with Object.assign() and spread syntax.) const a = [[1], [2], [3]]; const b = [...a]; b.shift().shift(); // 1 // Oh no! Now array 'a' is affected as well: a // [[], [2], [3]] A better way to concatenate arrays Array.prototype.concat() is often used to concatenate an array to the end of an existing array. ...
...rr2 onto arr1 arr1 = arr1.concat(arr2); With spread syntax this becomes: let arr1 = [0, 1, 2]; let arr2 = [3, 4, 5]; arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5] // Note: Not to use const otherwise, it will give TypeError (invalid assignment) Array.prototype.unshift() is often used to insert an array of values at the start of an existing array. ...
for await...of - JavaScript
d with const, let, or var. iterable Object whose iterable properties are to be iterated over. Examples Iterating over async iterables You can also iterate over an object that explicitly implements async iterable protocol: const asyncIterable = { [Symbol.asyncIterator]() { return { i: 0, next() { if (this.i < 3) { return Promise.resolve({ value: this.i++, done: false }); } return Promise.resolve({ done: true }); } }; } }; (async function() { for await (let num of asyncIterable) { console.log(num); } })(); // 0 // 1 // 2 Iterating over async generators Since the return values of async generators conform to the async iterable protocol, they can be looped using for await...of. async function* asyncGenerator() ...
...; // 0 // 1 // 2 For a more concrete example of iterating over an async generator using for await...of, consider iterating over data from an API. This example first creates an async iterable for a stream of data, then uses it to find the size of the response from the API. async function* streamAsyncIterable(stream) { const reader = stream.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaseLock(); } } // Fetches data from url and calculates response size using the async generator. async function getResponseSize(url) { const response = await fetch(url); // Will hold the size of the response, in bytes. let responseSize = 0; // The for-await-of l...
for...of - JavaScript
agraph of articleParagraphs) { paragraph.classList.add('read'); } Closing iterators In for...of loops, abrupt iteration termination can be caused by break, throw or return. In these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator, execution continues outside of the loop } console.log('done'); Iterating over generators You can also iterate over generators, i.e. functions generating an iterable object: function* fibonacci() { // a generator function let [prev, curr] = [0, 1]; while (true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (const n of fibonacci()) { console.log(n); // truncate the sequence at 1000 if (n >= 1000) { break; } } Do ...
...enerator should not be re-used, the following does not make sense! for (const o of gen) { console.log(o); // Never called. } Iterating over other iterable objects You can also iterate over an object that explicitly implements the iterable protocol: const iterable = { [Symbol.iterator]() { return { i: 0, next() { if (this.i < 3) { return { value: this.i++, done: false }; } return { value: undefined, done: true }; } }; } }; for (const value of iterable) { console.log(value); } // 0 // 1 // 2 Difference between for...of and for...in Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of ...
Transitioning to strict mode - JavaScript
or a property name in an object literal {a: 1, b: 3, a: 7} This is no longer the case in ECMAScript 2015 (bug 1041128). Declaring two function parameters with the same name function f(a, b, b) {} These errors are good, because they reveal plain errors or bad practices. They occur before the code is running. New runtime errors JavaScript used to silently fail in contexts where what was done was an error. Strict mode throws in such cases. If your code base contains such cases, testing will be necessary to be sure nothing is broken. Once again, it can happen at the function granularity level. Setting a value to an undeclared variable function f(x) { 'use strict'; var a = 12; b = a + x * 35; // error! } f(42); This used to change a value on the global object which is rarely t...
...'none'; else setTimeout(fadeOut, 40); // use the name of the function })(); Semantic differences These differences are very subtle differences. It's possible that a test suite doesn't catch this kind of subtle difference. Careful review of your code base will probably be necessary to be sure these differences don't affect the semantics of your code. Fortunately, this careful review can be done gradually down the function granularity. this in function calls In function calls like f(), the this value was the global object. In strict mode, it is now undefined. When a function was called with call or apply, if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null). In strict mode, the value is passed directly without conversion or...
Autoplay guide for media and Web Audio APIs - Web media technologies
e or app can begin whatever it needs to do that relies upon the video having been started up. Note: This approach doesn't differentiate between autoplay and the user starting playback manually. The play() method The term "autoplay" also refers to scenarios in which a script tries to trigger the playback of media that includes audio, outside the context of handling a user input event. This is done by calling the media element's play() method. Note: It is strongly recommended that you use the autoplay attribute whenever possible, because support for autoplay preferences are more widespread for the autoplay attribute than for other means of playing media automatically. It also lets the browser take responsibility for starting playback, letting it optimize the timing of that taking place. ...
... versions of the HTML specification, play() didn't return a value. Returning a promise to allow you to determine success or failure of the operation was added more recently. Checking for undefined prevents this code from failing with an error on older versions of web browsers. If the promise returned by play() is resolved without error, the then() clause is run and can begin whatever needs to be done when autoplay has begun. We then add a catch() handler to the promise. This looks at the error's name to see if it's NotAllowedError. This indicates that playback failed due to a permission issue, such as autoplay being denied. If that's the case, we should present a user interface to let the user manually start playback; that's handled here by a function showPlayButton(). Any other errors are ...
Codecs used by WebRTC - Web media technologies
WebRTC video stream must be able to handle video at at least 20 FPS at a minimum resolution of 320 pixels wide by 240 pixels tall. It's encouraged that video be encoded at a frame rate and size no lower than that, since that's essentially the lower bound of what WebRTC generally is expected to handle. SDP supports a codec-independent way to specify preferred video resolutions (RFC 6236. This is done by sending an a=imageattr SDP attribute to indicate the maximum resolution that is acceptable. The sender is not required to support this mechanism, however, so you have to be prepared to receive media at a different resolution than you requested. Beyond this simple maximum resolution request, specific codecs may offer further ways to ask for specific media configurations. Supported video codecs...
...method of both RTCRtpSender and RTCRtpReceiver. If the media is video, we call a method called preferCodec() for both the sender's and receiver's codec lists; this method rearranges the codec list the way we want (see below). Finally, we call the RTCRtpTransceiver's setCodecPreferences() method to specify that the given send and receive codecs are allowed, in the newly rearranged order. That's done for each transceiver on the RTCPeerConnection; once all of the transceivers have been updated, we call the onnegotiationneeded event handler, which will create a new offer, update the local description, send the offer along to the remote peer, and so on, thereby triggering the renegotiation of the connection. The preferCodec() function called by the code above looks like this to move a specified...
Animation performance and frame rate - Web Performance
The performance cost of animating a CSS property can vary from one property to another, and animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate. For animated media, such as video and animated gifs, the main performance concern is file size - downloading the file size fast enough to not negatively impact performance is the greatest issue. Code based animations, be it CSS, SVG, <canvas>, webGL or other JavaScript animations, can cause performance issues even if the bandwidth footprint is small. ...
...icular system and its load, performance tools can help you understand the work the browser's doing to render your site, and help you prevent and diagnose problems when they occur. Users expect all interface interactions to be smooth and all user interfaces to be responsive. Animation can help make a site feel faster and responsive, but animations can also make a site feel slower and janky if not done correctly. Responsive user interfaces have a frame rate of 60 frames per second (fps). While it is not always possible to maintain 60fps, it is important to maintain a high and steady frame rate for all animations. Let's take a look at how we can use browser tools to inspect the frame rate. We'll also discuss some tips to create and maintain a fast and steady frame rate. The developer tool's fra...
Performance fundamentals - Web Performance
pipeline in Gecko that underpins HTML, CSS, and Canvas is optimized in several ways. The HTML/CSS layout and graphics code in Gecko reduces invalidation and repainting for common cases like scrolling; developers get this support "for free". Pixel buffers painted by both Gecko "automatically" and applications to canvas "manually" minimize copies when being drawn to the display framebuffer. This is done by avoiding intermediate surfaces where they would create overhead (such as per-application "back buffers" in many other operating systems), and by using special memory for graphics buffers that can be directly accessed by the compositor hardware. Complex scenes are rendered using the device's GPU for maximum performance. To improve power usage, simple scenes are rendered using special dedicated ...
...ractical tips will help improve one or more of the Application performance factors discussed above. Use CSS animations and transitions Instead of using some library's animate() function, which probably currently uses many badly performing technologies (window.setTimeout() or top/left positioning, for example) use CSS animations. In many cases, you can actually use CSS Transitions to get the job done. This works well because the browser is designed to optimize these effects and use the GPU to handle them smoothly with minimal impact on processor performance. Another benefit is that you can define these effects in CSS along with the rest of your app's look-and-feel, using a standardized syntax. CSS animations give you very granular control over your effects using keyframes, and you can even w...
Example - SVG: Scalable Vector Graphics
In this example, we use XHTML, SVG, JavaScript, and the DOM to animate a swarm of "motes". These motes are governed by two simple principles. First, each mote tries to move towards the mouse cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural-looking behavior. This is done completely in W3C Standards-XHTML, SVG, and JavaScript-no Flash or any vendor-specific extensions. This example should work in Firefox 1.5 and above. View the example <?xml version='1.0'?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <title>A swarm of motes</title> <style type='text/css'> <![CDATA[ label, input { width: 150px; display: block; float: left; margin-bottom: 10px; } label ...
...splay' width='400' height='300'> <svg:circle id='cursor' cx='200' cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/> </svg:svg> <p>A swarm of motes, governed by two simple principles. First, each mote tries to move towards the cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural looking behavior. </p> <p> This is done completely in W3C Standards-XHTML, SVG and JavaScript-no flash or any vendor specific extensions. Currently, this will work in Mozilla Firefox version 1.5 and above. </p> <div> (C) 2006 <a id='emailme' href='#'>Nick Johnson</a> <script type='text/javascript'> <![CDATA[ // foil spam bots var email = '@riovia.net'; email ='nick' + email; document.getElementById('email...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
t-param-namespace?>. Both PIs can contain "pseudo attributes" the same way that the xml-stylesheet PI does. The following document passes the two parameters "color" and "size" to the stylesheet "style.xsl". <?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> Note that these PIs have no effect when transformation is done using the XSLTProcessor object in JavaScript. Processing instructions The attributes in the xslt-param and xslt-param-namespace PIs are parsed using the rules defined in xml-stylesheet. Any unrecognized attributes must be ignored. Parsing of any attribute must not fail due to the presence of an unrecognized attribute as long as that attribute follows the syntax in xml-stylesheet. Both the xslt...
...f there are multiple xml-stylesheet PIs the parameters apply to all stylesheets as a consequence of that all stylesheets are imported into a single stylesheet per the XSLT spec.reference? Note that multiple xml-stylesheet XSLT PIs are not supported in Firefox currently. xslt-param The xslt-param PI supports 4 attributes: name The local-name part of the parameter name. No syntax checking is done on the attribute, however if it is not a valid NCName it will never match any parameter in the stylesheet. namespace The namespace of the parameter name. No syntax checking is done on the attribute. value Contains the string value for the parameter. The value of the attribute is used as value for the parameter. The datatype will always bestring. select An XPath expression for the paramet...
Navigator.mozNotification - Archive of obsolete content
tification. iconURL Optional A URL identifying the image to display in the notification. Return value A new notification object. Permissions When using notifications in an open web app, be sure to add the desktop-notification permission in your manifest file: "permissions": { "desktop-notification": {} } Usage notes In Firefox 22+, the instantiation of a new notification should be done with the Notification object by calling new Notification(title, options). Nick Desaulniers has written a Notification shim to cover both newer and older implementations. ...
Classes and Inheritance - Archive of obsolete content
); context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); context.fill(); } }); Unlike the definition of Circle in the previous section, we no longer have to override its prototype, or set its constructor property. This is all handled automatically. On the other hand, the call to the constructor for Shape still has to be made explicitly. This is done by forwarding to the initialize method of the prototype of the base class. Note that this is always safe, even if there is no initialize method defined on the base class: in that case the call is forwarded to a stub implementation defined on Class itself. The last special property we will look into is implements. It specifies a list of objects, which properties are to be copied to the prototype ...
Porting the Library Detector - Archive of obsolete content
e defined. For example, if window.jQuery is defined, then the page has loaded jQuery. For each library that it finds, the library detector adds an icon representing that library to the status bar. It adds a tooltip to each icon, which contains the library name and version. You can browse and run the ported version in the SDK's examples directory. How the Library Detector Works All the work is done inside a single file, librarydetector.xul This contains: a XUL overlay a script The XUL overlay adds a box element to the browser's status bar: The script does everything else. The bulk of the script is an array of test objects, one for each library. Each test object contains a function called test(): if the function finds the library, it defines various additional properties for the test...
Testing the Add-on SDK - Archive of obsolete content
le_folder_name>: a suite of tests which run test code for some example add-ons. This suite builds the example code, then runs these example add-on's test code. cfx testaddons --filter <addon_folder_name>: a suite of tests which run add-ons, which are themseleves tests. This suite builds add-ons which are tests (ie: their main.js script's merely run tests and close firefox when their tests are done), and runs them as cfx run would. cfx testpkgs --filter <file_name>:<test_name>: a suite of tests which run sdk module unit tests. This suite builds the entire addon-sdk repo as an add-on, like cfx xpi would, then runs the add-on like cfx test would. The majority of the tests run here are module unit tests, but there are various other tests included here as well. Note: You must remember to r...
clipboard - Archive of obsolete content
"bWRR9AAAAABJRU5ErkJggg%3D%3D"); If the clipboard contains an image, open it in a new tab. var clipboard = require("sdk/clipboard"); if (clipboard.currentFlavors.indexOf("image") != -1) require("sdk/tabs").open(clipboard.get()); As noted before, data type can be easily omitted for images. If the intention is set the clipboard to a data URL as string and not as image, it can be done by specifying a different flavor, like text. var clipboard = require("sdk/clipboard"); clipboard.set("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYA" + "AABzenr0AAAASUlEQVRYhe3O0QkAIAwD0eyqe3Q993AQ3cBSUKpygfsNTy" + "N5ugbQpK0BAADgP0BRDWXWlwEAAAAAgPsA3rzDaAAAAHgPcGrpgAnzQ2FG" + "bWRR9AAAAABJRU5ErkJggg%3D%3D", "text"); Globals Functions set...
page-mod - Archive of obsolete content
ct. Once created a page-mod will execute the supplied content scripts, and load any supplied stylesheets, in the context of any documents matching the pattern specified by the include property. Methods destroy() Stops the page-mod from making any more modifications. Once destroyed the page-mod can no longer be used. Modifications already made to open documents by content scripts will not be undone, but stylesheets added by contentStyle or contentStyleFile, will be unregistered immediately. Properties include A list of match pattern strings. These define the documents to which the page-mod applies. See the documentation of the include option above for details of include syntax. Events attach This event is emitted when the page-mod's content scripts are attached to a document whose URL...
/loader - Archive of obsolete content
ate, which can cause problems. For example, unload of a loader won't trigger unload hooks on pseudo-modules. Globals Each module loaded via the loader instance is secured in own JS sandbox. These modules don't share scope and get their own set of built-ins (Object, Array, String ...). But sometimes it's convenient to define a set of common globals that will be shared across modules. This can be done using the optional globals option. For example, the SDK uses this feature to provide a global console object: let { Loader } = require('toolkit/loader'); let loader = Loader({ globals: { console: { log: dump.bind(dump, 'log: '), info: dump.bind(dump, 'info: '), warn: dump.bind(dump, 'warn: '), error: dump.bind(dump, 'error: ') } } }); Be careful not to misus...
net/xhr - Archive of obsolete content
regular expression may be ineffective if it's easy to write a regular expression that looks safe but contains a special character or two that makes it far less secure than it seems at first glance. Possible Attenuations Before being exposed to unprivileged code, this object needs to be attenuated in such a way that, at the very least, it can't access the user's filesystem. This can probably be done most securely by white-listing the protocols that can be used in the URL passed to the open() method, and limiting them to http:, https:, and possibly a special scheme that can be used to access the add-on's packaged, read-only resources. Finally, we need to also consider attenuating http/https requests such that they're "sandboxed" and don't communicate potentially sensitive cookie information.
places/bookmarks - Archive of obsolete content
ions: Name Type group Group The parent group that the bookmark group lives under. Defaults to the Bookmarks.UNSORTED group. index number The index of the bookmark group within its parent group. Last item within the group by default. Functions save(bookmarkItems, options) Creating, saving, and deleting bookmarks are all done with the save() function. This function takes in any of: a bookmark item (Bookmark, Group, Separator) a duck-typed object (the relative properties for a bookmark item, in addition to a type property of 'bookmark', 'group', or 'separator') an array of bookmark items. All of the items passed in are pushed to the platform and are either created, updated or deleted. adding items: if passing...
ui/sidebar - Archive of obsolete content
a vertical strip of user interface real estate for your add-on that's attached to the left-hand side of the browser window. You specify its content using HTML, CSS, and JavaScript, and the user can show or hide it in the same way they can show or hide the built-in sidebars. Usage Creating, showing, and hiding sidebars You construct a Sidebar object using the Sidebar() constructor. Once you've done that, you can show the sidebar by calling the Sidebar's show() method. If a new window is opened from a window that has a sidebar visible, the new window gets a sidebar, too. You can hide the sidebar by calling its hide() method. Called with no arguments, show() and hide() will operate on the currently active window. From Firefox 33 onwards you can pass a BrowserWindow into these methods, and t...
console - Archive of obsolete content
rror message console.exception(exception) Logs the given exception instance as an error, outputting information about the exception's stack traceback if one is available. try { doThing(); } catch (e) { console.exception(e); } function UserException(message) { this.message = message; this.name = "UserException"; } function doThing() { throw new UserException("Thing could not be done!"); } error: my-addon: An exception occurred. UserException: Thing could not be done! console.info(object[, object, ...]) A synonym for console.log(). console.log(object[, object, ...]) Logs the arguments to the console, preceded by "info:" and the name of your add-on: console.log("This is an informational message"); info: my-addon: This is an informational message console.time(name) S...
Creating Reusable Modules - Archive of obsolete content
ly that same way that you import core SDK modules like page-mod or panel. It can often make sense to structure a larger or more complex add-on as a collection of modules. This makes the design of the add-on easier to understand and provides some encapsulation as each module will export only what it chooses to, so you can change the internals of the module without breaking its users. Once you've done this, you can package the modules and distribute them independently of your add-on, making them available to other add-on developers and effectively extending the SDK itself. In this tutorial we'll do exactly that with a module that calculates file hashes. A hashing add-on A hash function takes a string of bytes of any length, and produces a short, fixed length string of bytes as output. It's ...
Getting Started (jpm) - Archive of obsolete content
jpm. This tutorial walks through creating a simple add-on using the SDK. Prerequisites To create add-ons for Firefox using the SDK, you'll need: Firefox version 38 or later. If you need to work with earlier versions of Firefox, you'll need to use the old cfx tool. See instructions for getting started with cfx. the command-line jpm tool. See the instructions for installing jpm. Once you've done that, you'll be looking at a command prompt. Install Firefox Developer Version for testing your add-on. Initializing an empty add-on In the command prompt, create a new directory. Navigate to it, type jpm init, and hit enter: mkdir my-addon cd my-addon jpm init You'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file. Fo...
Bootstrapped extensions - Archive of obsolete content
n's user interface relatively easy, it means that updating, installing, or disabling an extension requires an application restart. Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) introduces bootstrapped extensions. These are special extensions that, instead of using overlays to apply their user interface to the application, programmatically insert themselves into the application. This is done using a special script file that's included in the extension that contains functions the browser calls to command the extension to install, uninstall, start up, and shut down. All the application does is call into this script file; the extension is responsible for adding and removing its user interface and handling any other setup and shutdown tasks it requires. This article discusses how boots...
Bookmarks - Archive of obsolete content
g the bookmarks service. Initiating the bookmarks service As is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getService(Components.interfaces.nsINavBookmarksService); Creating a bookmark folder Creating a new bookmark folder is done using the nsINavBookmarksService.createFolder() method. For example, to create a new folder in the Bookmarks menu: var menuFolder = bmsvc.bookmarksMenuFolder; // Bookmarks menu folder var newFolderId = bmsvc.createFolder(menuFolder, "Folder name here", bmsvc.DEFAULT_INDEX); This code locates the Bookmarks menu's folder, then creates a new folder named "Folder name here" in it. Specifying DEFAU...
Dialogs and Prompts - Archive of obsolete content
xul and pass it arguments: var params = {inn:{name:"foo", description:"bar", enabled:true}, out:null}; window.openDialog("chrome://myext/content/mydialog.xul", "", "chrome, dialog, modal, resizable=yes", params).focus(); if (params.out) { // User clicked ok. Process changed arguments; e.g. write them to disk or whatever } else { // User clicked cancel. Typically, nothing is done here. } mydialog.xul: <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="myDialogId" title="My Dialog" ondialogaccept="return onOK();" onload="onLoad();" persist="screenX screenY width height" windowtype="myDialogWindowType"> <script type="application/javascript" src="chrome://myext/content/mydialog.js"/> <grid> <columns><column/><column/...
HTML in XUL for rich tooltips - Archive of obsolete content
content element, although it is an element of chrome. This is recommended for security reasons, especially if remote HTML is to be inserted. A number of menuitems have a tooltip attribute pointing to the same tooltip. That tooltip is empty now, but we will use the mouseover event to dynamically populate the tooltip (which is about to be shown) with a different message for each menuitem. This is done by calling the onMouseTooltip function, which will take the tooltipHTML attribute of the element that is being hovered over and safely convert that into DOM and inject it into the tooltip that will soon be shown. The tooltipHTML attribute is an HTML string which is set sometime beforehand for each element. For security reasons, the conversion will strip out some of the more dangerous elements in ...
HTML to DOM - Archive of obsolete content
e; frame.webNavigation.allowSubframes = false; // listen for load frame.addEventListener("load", function (event) { // the document of the HTML in the DOM var doc = event.originalTarget; // skip blank page or frame if (doc.location.href == "about:blank" || doc.defaultView.frameElement) return; // do something with the DOM of doc alert(doc.location.href); // when done remove frame or set location "about:blank" setTimeout(function (){ var frame = document.getElementById("sample-frame"); // remove frame // frame.destroy(); // if using browser element instead of iframe frame.parentNode.removeChild(frame); // or set location "about:blank" // frame.contentDocument.location.href = "about:blank"; },10); }, true); } /...
Miscellaneous - Archive of obsolete content
ostData. This example obtains the post data of the last page. var postdata = history.getEntryAtIndex(history.index-1,false).QueryInterface(Ci.nsISHEntry).postData; If you got here all by yourself, your problem must be at reading the postData, because it's a nsIInputStream object, whose available function always returns 0. And if you read it directly, you always got nothing. ...
StringView - Archive of obsolete content
depending on the chosen encoding). StringView instances' methods makeIndex() Syntax stringView.makeIndex([charactersLength[, startFrom]]) Description If the charactersLength argument is a number it will be taken as codepoints length and makeIndex() will return the index in elements of that position starting from 0. If the startFrom argument is passed the analysis will be done starting from it. If the charactersLength argument is omitted, makeIndex() will return the length in codepoints (ASCII or UTF-encoded) of the stringView object. Arguments charactersLength Optional A number expressing the distance in codepoints from startFrom of the index of stringView.rawData to be returned. startFrom Optional A number expressing the position in raw elements o...
Toolbar - Archive of obsolete content
rking 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. The user has to drag it onto the toolbar. The following code will place your button on the toolbar by default. This should only be done on the first run of your add-on after installation so that if the user decides to remove your button, it doesn't show up again every time they start the application. Notes Insert your button by default only once, at first run, or when an extension update adds a new button. Please only add your button by default if it adds real value to the user and will be a frequent entry point to your exte...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
Yippee-ki-yay! Now you have an extension that does, well, absolutely nothing. It's time to do something with those groovy components that you've implemented and registered. The simplest way to do this is to write some JavaScript and XUL code. At this point, it would be very helpful to have a bit of experience writing "regular" extensions (i.e. without using custom C++ components). If you've never done this, I strongly recommend that you think of a cool idea for something simple that you've always wanted to tweak in Firefox and write it. Just displaying a new menu item that opens a "Hello, World!" dialog box would be already be a great exercise to get warmed up with. Assuming you know how to write XUL/JavaScript extensions, you're aware that the most important stuff goes in the chrome/ d...
Displaying web content in an extension without security issues - Archive of obsolete content
arm disabling everything else as well unless it is really required: frame.docShell.allowAuth = false; frame.docShell.allowImages = false; frame.docShell.allowJavascript = false; frame.docShell.allowMetaRedirects = false; frame.docShell.allowPlugins = false; frame.docShell.allowSubframes = false; But what about interactivity, for example if you want a certain reaction to mouse clicks? ...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
es are downloaded and injected into the extension. This usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change. In this case, JavaScript sandboxing should be used to isolate the downloaded JavaScript from the rest of the extension, and host application. Sandboxing is done using Components.utils.evalInSandbox(). The JavaScript code is added to the sandbox along with any "safe" objects the JavaScript needs to interact. Sandboxing is not without its dangers and developers should read the sandboxing page carefully to make sure untrusted code is not leaked out of the sandbox. ...
Extension Packaging - Archive of obsolete content
xtension Manager window. The XPI file must contain only uncompressed files, or files compressed using the deflate algorithm. The MIME type recognized by Firefox for XPI files is application/x-xpinstall. Since most HTTP servers are not configured to return this MIME type for the .xpi extension by default, you will probably need to configure your HTTP server. In the Apache HTTP Server, this can be done by adding the following directive to the configuration file or .htaccess: AddType application/x-xpinstall .xpi Install extension files directly If you know the location of the application (if you are installing an extension as part of the application installer, for example), you can install the extension files directly to <appdir>/extensions/<extensionID>. The extension will be found automati...
Extension Etiquette - Archive of obsolete content
the use of an icon next to the menu items. Other UI elements In general, toolbar items are very useful to end users because they can be removed or added to various toolbars as necessary. Status bar items should only be added for extensions that need constant monitoring, such as ad blocking, page ranking, or cookie management. Likewise, use context menu items sparingly -- only for tasks that are done frequently or on specific elements of a web page. Focus Don't steal focus. It's not your extension's job to take focus from the web content. If the user loads a website and they ask for focus, they should get it. Overriding their request isn't very nice. About dialogs There is a default popup About dialog that is created from install.rdf data; creating a new XUL About box is usually unnecessa...
Hiding browser chrome - Archive of obsolete content
This can be accomplished by augmenting the behavior of the XULBrowserWindow object's hideChromeForLocation() method. Note: Don't simply replace the hideChromeForLocation() method; this will likely hurt the functionality of Firefox itself as well as other extensions. Use the technique demonstrated here. ...
Interaction between privileged and non-privileged pages - Archive of obsolete content
d document To "answer" the web page (e.g., return code), your extension can set an attribute or attach child elements on the event target element (<MyExtensionDataElement/> in this example). You can optionally clean up the created element, or create it once when the web page loads then re-use it each time. Another option is to send a return event from the extension to the web page. This can be done using the same principle as the above example. There is only one extension, but there can be many active web pages. So to trigger the right event on the right page we have to tell the extension which page to call. The information we need for that is contained in evt.target.ownerDocument. We can extend the above example with some data transfer from the extension to the web page. In the following...
Listening to events in Firefox extensions - Archive of obsolete content
ntation covering each of them. It also provides some use cases that may be of specific interest. Types of events There are multiple types of events that application and extension authors can use to receive notifications from <xul:browser> and <xul:tabbrowser> elements to hear about changes relating to loads of the content contained within them. Simple DOM events Registering for a DOM event is done using with code such as the following: function callback(evt) { // Do your processing here. Check evt.target for the target of the event. } b.addEventListener("event", callback, false) Where b is the browser or tabbrowser you wish to watch for events from. Keep in mind that the events may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. Some of th...
Multiple item extension packaging - Archive of obsolete content
="urn:mozilla:install-manifest"> <!-- nsIUpdateItem type for a Multiple Item Package --> <em:type>32</em:type> ... When specifying em:targetApplication the minVersion specified should be the highest minVersion and the maxVersion specified should be the lowest maxVersion from all of the installable bundles contained by the multiple item package for the em:targetApplication. If this is not done, any items that are not compatible will not be installed unless a compatibility check discovers updated compatibility information. Installation Installation can be performed using any of the existing methods used for installing extensions / themes. The same user interface is used for installing a multiple item package (i.e. the individual packages contained in the multiple item package will not...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
ard to read, so you can point out specific variables that you want to watch (Figure 4). Watched variables appear under the Watches tab, and are updated every time they are evaluated. You can then continue with stepwise execution and watch the changes in the program and variables. Once you've finished your inspection, you can continue and let the halted program resume execution. The author has done almost no work developing extensions, but has used this to investigate how extensions were implemented. In the QuickNote example, we first set one breakpoint and then stepped through it. Use Step Over to avoid a function, and Step Into to always call it; once you are done investigating a function, use Step Out, and then you can Step Into the next function. Set breakpoints in locations of intere...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
{ var textbox = document.getElementById("currentTime"); textbox.value = new Date().toLocaleTimeString(); textbox.select(); } Operations check Perform an operations check to make sure that your changes to the source file are correct. At this point, it's important that you disabled the XUL cache as discussed in the earlier section, "Setting up your development environment". Assuming you've done that, you'll be able to confirm the changes to overlay.xul and clock.xul without the bother of relaunching Firefox or reinstalling the extension. If the browser.xul file, which is the target of the overlay in overlay.xul is being read in again, the changes will be reflected, and you'll be able to see the changes by opening a new browser window. The files clock.xul and clock.js will be read in eve...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
hoolChrome.BrowserOverlay.init(); }, false); Then all we need is some persistent flag that ensures that the first run code is only run once. The best approach in this case is to use a preference, as explained in the Handling Preferences section. So, if we were to use FUEL, we can do the following in the init function: init : function() { let firstRunPref = "extensions.xulschoolhello.firstRunDone"; if (!Application.prefs.getValue(firstRunPref, false)) { Application.prefs.setValue(firstRunPref, true); // all the rest of the first run code goes here. } } In this case you would need to declare the first run preference in your default preferences file, with a default value of false. You should also change the preference value before you run any other first run code. Keep in mind...
Appendix F: Monitoring DOM changes - Archive of obsolete content
created. While it is no longer possible for web sites to use XBL directly, chrome code can still attach XBL bindings to web content from stylesheets loaded via the stylesheet service. As it is currently possible to attach only a single binding to a given DOM node at once, it is important when using this method to detach your binding from a node once your constructor has run. This is most easily done by adding a :not clause to the CSS selector that attaches your binding. For instance, when using the selector div:not([foo-binding-done]), you can detach your binding by running this.setAttribute("foo-binding-done", true) in your constructor. Monkey patching DOM methods When you are interested in changes to particular nodes, sometimes the best way is to wrap the DOM methods of those elements, a...
Connecting to Remote Content - Archive of obsolete content
usly or not. In asynchronous mode code execution continues immediately after the send call. In synchronous mode the code and user interface are blocked while waiting for a response to come back. Note: Requests can take a long time to process and you don't want users to be stuck waiting while a request is obtained and processed. Therefore, it is very important that XMLHttpRequest calls are always done asynchronously. Now let's look at the most common types of content you can use to communicate with remote servers. JSON content JSON is a very lightweight and simple data representation format, similar to the object representation used in JavaScript. Unlike JavaScript, the JSON format doesn't allow any kind of code that can be run, only data. JSON used to be risky in terms of security because...
Custom XUL Elements with XBL - Archive of obsolete content
is is very powerful: it allows you to change almost any aspect of the interface of any XUL window. In conjuntion with inheritance, it's even easy to do. You can enrich the UI of a Firefox window by extending and replacing elements, which is what the Console2 extension does in order to improve the Error Console window. Replacing elements should always be a last resort solution, specially if it is done on the main browser window. It's very easy to break the UI of the application or other extensions if you do this the wrong way, so be very careful about it. If you only need to change some specific instances of an element, use very specific CSS rules. You can use the -moz-binding property with any CSS selector. << PreviousNext >> This tutorial was kindly donated to Mozilla by Appcoast. ...
Handling Preferences - Archive of obsolete content
type on the "Filter" textbox to search for specific preferences. If you type the word "homepage", it will filter all the preferences and display only the ones which include the word "homepage" in its name or value. Right-clicking on the list reveals several options that allow you to modify preference values and add new ones. Preferences with non-default values are highlighted in bold. All changes done in about:config are saved to the prefs.js file. The list in about:config is not complete. Some Firefox preferences have no default value, so they are left out unless you add them manually. An extensive specification of Firefox preferences can be seen in this page. You don't need to know them by heart; if doing task X requires some preference, then it's better to look for an explanation on how to...
JavaScript Object Management - Archive of obsolete content
ther ahead). Do this even if you don't need them now. It's better to just make a habit out of it. This is a point that is worth highlighting: modules work outside of the window scope. Unlike scripts in the chrome, modules don't have access to objects such as window, document, or other global functions, such as openUILink. These are all UI components and UI operations anyway, so they are better done in the chrome. As a general guideline, we keep all of our business logic in JSM, available through service objects, and chrome scripts are limited to handle presentation logic. We handle most of our code through static objects, singleton objects that don't require instantiation. But it is sometimes necessary to define classes and be able to create multiple instances. Common cases include in...
The Essentials of an Extension - Archive of obsolete content
nts. The content folder, chrome.manifest, install.rdf, and other files and directories should be at the root level of your archive. If you zip the containing folder, your extension will not load. Note that the Tools menu is hidden by default on Firefox 4 and above, on Windows and some Linux distributions. Check Menu Bar under the Options menu of the Firefox menu button to enable it. Once you're done, you can look at this reference solution: Hello World 2. << PreviousNext >> This tutorial was kindly donated to Mozilla by Appcoast. ...
User Notifications and Alerts - Archive of obsolete content
Users will find them annoying and probably will learn to dismiss them as quickly as possible without even reading what they have to say. Or they will just get rid of your add-on. ...
Performance best practices in extensions - Archive of obsolete content
e or expensive chunks of code fragments can be significantly deferred. Defer everything that you can Most extensions have a load event listener in the main overlay that runs their startup functions. Do as little as possible here. The browser window is blocked while your add-on's load handler runs, so the more it does, the slower Firefox will appear to the user. If there is anything that can be done even a fraction of a second later, you can use an nsITimer or the window.setTimeout() method to schedule that work for later. Even a short delay can have a big impact. General Performance Tips Avoid Creating Memory Leaks Memory leaks require the garbage collector and the cycle collector to work harder, which can significantly degrade performance. Zombie compartments are a particular kind of ...
Signing an XPI - Archive of obsolete content
copy chrome.manifest build >>%x%\build.log signtool.exe -d C:\Projects\CodeSigning -k "Code Signing (Certum)" -p "password" build/ >> %x%\build.log cd build zip "%x%.xpi" META-INF/zigbert.rsa >> %x%\build.log zip -r -D "%x%.xpi" * -x META-INF/zigbert.rsa >> %x%\build.log rem copy "%x%.xpi" ..\..\..\http\fsb.xpi >> %x%\build.log move "%x%.xpi" ..\ >> %x%\build.log cd .. rd build /s/q echo Done. Make sure to replace password with your NSS Certificate database password. Alternatives to NSS/signtool There are several alternatives to using signtool that might suit your needs better, however please note that these alternatives are unofficial third party products. Key Manager XUL Extension Wladimir Palant's Python Script (blog post) xpisign.py Python Script XPISigner Java Tool Ref...
Signing an extension - Archive of obsolete content
Set the trust for the root and intermediate certificates. Here's an example of VeriSign: nss-certutil -M -n "Verisign Class 3 Public Primary Certification Authority" -t "C,C,C" -d . nss-certutil -M -n "VeriSign Class 3 Public Primary Certification Authority - G5 - VeriSign, Inc." -t "C,C,C" -d . nss-certutil -M -n "VeriSign Class 3 Code Signing 2010 CA - VeriSign, Inc." -t "C,C,C" -d . It's all done. Sign The basic usage of the signing tool is as follows: nss-signtool \ -d (path to the directory that contains your certificate database files) \ -k (your certificate nickname) \ -p (your certificate password) \ -X -Z (output path/name of signed file) \ (path to your extension working directory that contains chrome directory, chrome.manifest file, install.rdf file, etc.) Writing you...
Promises - Archive of obsolete content
It is also available for use off-main-thread in Workers as a synchronous API. This interface replaces the previous, complicated XPCOM nsIFile and streams APIs, and their related JavaScript helper modules. These older interfaces should be avoided, even in their ...
Search Extension Tutorial (Draft) - Archive of obsolete content
E_ADDED); } // If we've already removed this observer, ignore the error. catch (e) {} } // Observer called after our engine has been successfully added function searchObserver(engine, topic, data) { if (data != "engine-added") return; engine.QueryInterface(Ci.nsISearchEngine); if (engine.name == ENGINE_DETAILS.name) { // Remove our observer now that we're done with it. removeObserver(); // If the engine is not hidden and this is the first run, move // it to the first position in the engine list and select it if (selectSearch && !engine.hidden) { Services.search.moveEngine(engine, 0); Services.search.currentEngine = engine; } } } // Observer topic const ENGINE_ADDED = "browser-search-e...
Underscores in class and ID Names - Archive of obsolete content
of a "space" in variable and function names. For example, a function whose job is to "get the length of a string" might be called get_string_length, and a variable representing the number of people who voted Republican might be voted_Republican. Given this fact, authors who write CSS often attempt to employ the underscore in a similar fashion when creating class and ID names. This should not be done. Although underscores are, as of this writing, technically permitted in class and ID names, there are many historical and practical reasons why they should be avoided. The CSS1 specification, published in its final form in 1996, did not allow for the use of underscores in class and ID names unless they were "escaped." An escaped underscore would look something like this: p.urgent\_note {color: ...
CSS3 - Archive of obsolete content
ine how resize of the object should be handled. ...
JXON - Archive of obsolete content
The points 1 and 2 are automatically managed by the JavaScript method JSON.stringify(). In summary Let's take the third algorithm as the most representative JXON parsing algorithm. A single structured XML Element might have eight different configurations: an empty element, an element with ...
MMgc - Archive of obsolete content
e other hand if the black is a huge array and only a couple slots had new objects written to them we are wasting time by marking the whole thing. A popular solution to this is what's called card marking. Here you divide memory into "cards" and when a white object is written to a black object you mark the card containing the slot the pointer to the white object was written to. After all marking is done you circle back and remark the black portion of any card that was flagged by the write barrier. There are two techniques to optimize this process. One is to save all the addresses of all pages that had cards marked (so you don't have to bring every page into memory to check its hand, so to speak). Another option is to check every page while doing the normal marking and it any of its cards where f...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
ike "j", "y", and "q" are drawn. Figure 4 shows what happens when we add an image to the mix. Note where the image sits by default: its bottom edge is aligned with the baseline of the line box. This placement can be changed with vertical-align-- we'll talk about that in a bit-- but almost nobody ever changes the value from its default. Let's take away the text, and leave only the image, as was done in Figure 5. So we have an image sitting on the baseline of a line box that contains only the image. Now consider what happens when we put that line in a table cell (Figure 6). And there you have it-- spaces opening up where none have ever been seen before. It gets even worse with small images, like ones that are one pixel tall, as illustrated in Figure 7. Now there's all kinds of space ...
Adding the structure - Archive of obsolete content
tus="none"/> <statusbarpanel class="statusbarpanel-iconic" id="offline-status"/> <statusbarpanel class="statusbarpanel-iconic" id="security-button" onclick="BrowserPageInfo(null, 'securityTab')"/> </statusbar> The statusbar XUL element defines a horizontal status bar where informative messages about an application's state can be displayed. It can contain both text messages (i.e. "Done" in Mozilla when a document finishes loading) and graphical messages (f.e. the lock icon in Mozilla that shows whether or not a loaded document was encrypted with SSL). Status bars comprise a series of panels, each one defined by a statusbarpanel XUL element. Each status bar panel displays a different kind of status information. Graphical panels (like the one we are creating here that displays a...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
e's onload property to updateTinderboxStatus(), the function we want to execute when the document finishes loading, call its open method with the type of HTTP request we want to make and the URL of the document to retrieve, and then call its send method to send the request. XMLHttpRequest will retrieve the document located at the given URL and call the updateTinderboxStatus() function when it is done. Notice that we defined the instance of XMLHttpRequest as a global variable. This is because we need to reference it in the updateTinderboxStatus() function as well as the current function, and we can't pass the object from one function to the other because the one doesn't call the other directly. << PreviousNext >> ...
Making a Mozilla installation modifiable - Archive of obsolete content
hrome subdirectory of the Mozilla installation directory. Use your unzip utility to extract all files in that directory with a .jar extension. Make sure you extract them into the same (chrome) directory in which they are located. On Unix-like operating systems with bash-like shells, you can run the following command within that directory to accomplish this task: for file in *.jar; do unzip $file; done On operating systems with DOS-like shells, the following command accomplishes this task: for %file in (*.jar); do unzip %file Note that there are platform-specific files -- en-mac.jar, en-unix.jar, and en-win.jar -- in that directory. Extract only the one appropriate for your platform. After extracting the files we will modify the Mozilla chrome registry to use the extracted files instead of th...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
all.rdf and place it in the My_Theme directory, then open it up in your text editor. This file is a small XML database that describes the skin. <Description about="urn:mozilla:install-manifest"> <em:id>{Themes_UUID}</em:id> <em:version>Themes_Version</em:version> The first section requires that you establish a UUID for your theme and that you give your theme a version number. Once you've done this, insert the information as above, and scroll down. You will also have to update the minimum and maximum compatible versions for the target application (Firefox) in the following section: <em:targetApplication> <Description> <!-- Firefox's UUID --> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minVersion>Min_FF_Version</em:minVersion> <em:maxVersion...
Dehydra - Archive of obsolete content
Use at your own risk. The development focus switched to DXR (where the "D" comes from "Dehydra"), which is based on clang instead of gcc. Try DXR instead, or else try the gcc python plugin: https://fedorahosted.org/gcc-python-plugin/. Dehydra was a lightweight, scriptable, general purpose static analysis tool capable of application-specific analyses of C++ code. In the simplest sense, Dehydra could be thought of as a semantic grep tool. It presented a wealth of semantic information that can be queried with concise JavaScripts. It was also useful to find bugs in source code as it allows for much more error checking than C++ is capable of by itself. ...
Developing New Mozilla Features - Archive of obsolete content
de a long time to work their way through it. And if it's not possible to design the feature in bite-size chunks, it probably won't be possible to review it that way either. We expect our reviewers to understand the code they approve for check-in, not to simply glance at it and say OK. Finding the focus to digest a massive patch in the midst of multiple other demands will take time, even if you've done a perfect job. And since few of us are perfect, chances are that revisions will be requested. If you've got a large patch, let the likely reviewers know when they might expect to see it If your timeframe is tight, check out the Mozilla roadmap for milestone dates and see if your feature will arrive at a time of furious activity. If so, and if your feature is not of general interest, prepare to ...
Devmo 1.0 Launch Roadmap - Archive of obsolete content
Comments, ideas, questions and other discussion should be added on the Devmo talk:1.0 Launch Roadmap page. Further details on smaller tasks being done are available at User:Dria:TODO page. See also Current Events. Design Document Items Things that need to happen prior to a Devmo 1.0 Launch... Timeline Currently undetermined. ...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
rface is stored in the global package, in the file chrome://global/content/nsDragAndDrop.js. You can include this file in your XUL file with the script tag in the same way you would include your own scripts. The library also depends on another script library, which you should also include, usually at the top of your XUL file. You can look at the contents of these files to see how drag and drop is done at a lower level. Note that you can only use these libraries from within XUL loaded via a chrome URL. <script src="chrome://global/content/nsDragAndDrop.js" /> <script src="chrome://global/content/nsTransferable.js" /> This drag and drop library creates an object stored in the variable nsDragAndDrop. The object contains a series of functions, one for each event handler (except for dragenter wher...
Editor Embedding Guide - Archive of obsolete content
Then simply call nsIWebBrowser->do_GetInterface on the nsIWebBrowser to retrieve the nsIEditingSession from it. From there you call editingSession->MakeWindowEditable(domWindow, editortype, PR_TRUE). The first parameter is the nsIDOMWindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. In calling this method, the editor is created underneath and the event listeners are all prepa if (NS_FAILED(rv)) return NS_ERROR_FAILURE; // we are not setup??!! nsCOMPtr<nsIEditingSession> editingSession; nsIWebBrowser->do_GetInterface(getter_AddRefs(editingSession)); if (editingSession) editingSession->MakeWindowEditable(domWindow, "html", PR_TRUE); The valid editor types are: "te...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
COM where to find certain files and directories. If your code cannot find the GRE and keeps throwing FileNotFoundExceptions during the getGREPathWithProperties(...) call, check whether you already registered the GRE on your system: GRE Registration The initEmbedding method kicks off the embedding process, allowing the Java application to work with XPCOM and Mozilla. Once the Java application is done using Mozilla, it needs to terminate the embedding process: try { mozilla.termEmbedding(); } catch (XPCOMException e) { // this exception is thrown if termEmbedding failed } Working with XPCOM objects Now that Mozilla is embedded, the Java application can work with XPCOM objects. The Mozilla class provides several methods to facilitate this, such as getServiceManager, getComponentMan...
Fast Graphics Performance With HTML - Archive of obsolete content
xed">Simple</div>lots of text...</div> Make the content of scrollable sub frames opaque e.g. use <div style="overflow:scroll><div style="background:white"><p>This is some text</p><p>And some more</p></div></div> instead of <div style="overflow:scroll><p>This is some text</p><p>And some more</p></div> Animating 'transform' and 'opacity' properties can be done with the compositor which makes them efficient to animate ...
Content states and the style system - Archive of obsolete content
ent state are handled. Generally, whenever a node's content state changes, style has to be reresolved (recomputed) for that node and all of its descendants. This is an expensive operation, however, so the style system tries to minimize the number of style reresolves it does. To this end, when a <code>ContentStatesChanged</code> notification is dispatched for a content node the first thing that's done is to is to check whether the content state change something could affect any styles. This is done by walking the list of all CSS2.1 simple selectors in all style sheets applied to the page that have a state-dependent pseudo-class as part of the selector. This list is created during the parsing of the stylesheets involved. For each selector in this list we check whether it might have stopped mat...
Style System Overview - Archive of obsolete content
ge list. Rebuilds rule tree if stylesheet was removed to avoid dangling pointers (and perhaps aliasing that would cause problems). Otherwise we'd have to walk rule tree and compare each rule node to every rule in the sheet (O(rules * rule-nodes)). When rebuilding rule tree, we have to clear cached style contexts from XUL menus and trees. Style rule changes Handling of style rule changes is done in frame constructor (called from style set, called from pres shell, which is a document observer) and in the pres shell. Code should be merged. Rule change applies the rule-struct hint as if the rule matched the root element. (inefficient) It does clearing of style data (through StyleSetImpl::ClearStyleData) by walking the rule tree and then the style context tree. (could be handled by simultan...
Gecko Coding Help Wanted - Archive of obsolete content
he help. Here are some fixes that are straightforward; they just need some time and attention: deCOMtamination Convert weird, ugly and inefficient method signatures to more natural C++ method signatures. It's really improved code readability, reduced code size, and sped up performance. It's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. We've done a lot, but there's a lot more to do. roc is willing to work closely with anyone with reasonable C++ experience to get them started on this. Just send him mail. Not up for coding yet? Join the Gecko BugAThon and help save Gecko engineers from imminent doom! Original Document Information Author(s): fantasai Last Updated Date: May 4, 2004 Copyright Information: Portions of this c...
Helper Apps (and a bit of Save As) - Archive of obsolete content
HelperAppLauncherDialog, which asynchronously puts up the helper app dialog. nsExternalAppHandler::OnDataAvailable Here we just copy the newly arrived data over into our temporary file. If any read or write errors occur, abort the whole process: Cancel the channel. Pull down the helper app dialog (if any). Remove the temp file. nsExternalAppHandler::OnStopRequest Set a flag that we're done, then do whatever the user wants if the user has decided (save to disk and open in helper are the current options the user has). Helper App dialog This is our implementation of nsIHelperAppLauncherDialog It calls back to the nsExternalAppHandler to let it know what the user picked Saving to disk If a user decides to "save to disk", we just move/copy the temporary file over to the chosen lo...
Introducing the Audio API extension - Archive of obsolete content
scripts can specify the audio stream's characteristics, then write audio samples. Users must create an audio object and then use the mozSetup() function to specify the number of channels and the frequency (in Hz). For example: // Create a new audio element var audioOutput = new Audio(); // Set up audio element with 2 channel, 44.1KHz audio stream. audioOutput.mozSetup(2, 44100); Once this is done, the samples need to be created. Those samples have the same format as the ones in the mozAudioAvailable event. Then the samples are written in the audio stream with the function mozWriteAudio(). It's important to note that not all the samples might get written in the stream. The function returns the number of samples written, which is useful for the next writing. You can see an example below: /...
Litmus tests - Archive of obsolete content
Litmus tests are (non-automated) tests that are documented in the litmus database. See http://litmus.mozilla.org. If you're interested in automated testing, see Mozilla automated testing. Smoke Tests There are types of litmus tests. Smoke tests were the first developed. These were developed before litmus, but then pulled in. A "smoke test" is a quick check, done to verify the basic functionality of a certain feature, or a sanity check of the build process. BFTs, or Basic Functionality Tests This set of tests would take longer to run, but will cover an entire release. It may not cover it at much depth, but it does try to cover the major features. FFTs, or Full Functionality Tests This is supposed to be more comprehensive and will take longer to run. ...
Modularization techniques - Archive of obsolete content
return a new interface should call AddRef() on that interface before returning it. nsresult GetFoo(IFoo **aFooRes) { if (aFooRes == NULL) { return NS_ERROR_NULL_POINTER; } *aFooRes = mFoo; NS_ADDREF(*aFooRes); return NS_OK; } Remember that this applies to the interfaces returned by QueryInterface(), CreateInstance() and NS_NewX(), and you must call Release() on them when you are done to avoid memory leaks. In Parameters and Local Pointers Interfaces that are passed in to a function and local copies of that interface pointer are assumed to be in the lifetime of the calling function, and do not need to have AddRef() called. nsresult TweekFoo(IFoo *aFoo1, IFoo *aFoo2) { IFoo local = aFoo; if (aFoo->Bar() == NS_OK) { local = aFoo2; } return local->Boff(); } In-...
Porting NSPR to Unix Platforms - Archive of obsolete content
s article to document the more mechanical part of the Unix porting task. For certain more "standard" Unix platforms, this may be all you have to do. On other platforms, you may need to do extra work to deal with their idiosyncrasies. Porting Instructions You can use different threading packages to implement NSPR threads. NSPR has a user-level threading library where thread context switches are done by <tt>setjmp/longjmp</tt> or <tt>sigsetjmp/siglongjmp</tt>. This is called the local threads only version of classic NSPR. You should attempt to do a local threads only port first. The classic NSPR source files are in <tt>mozilla/nsprpub/pr/src/threads</tt> and <tt>mozilla/nsprpub/pr/src/io</tt>. If the platform has pthreads, you can also use pthreads as an implementation strategy. This is refer...
Build - Archive of obsolete content
directory. The contents of the file should look something like this : mk_add_options MOZ_CO_PROJECT=xulrunner mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/mozilla-obj ac_add_options --enable-application=xulrunner ac_add_options --disable-debug ac_add_options --enable-optimize ac_add_options --disable-tests ac_add_options --disable-javaxpcom Build xulrunner : make -f client.mk build Once the build is done, there will be a directory called mozilla-obj. Go into the prism/ directory and create a .mozconfig file mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/mozilla-obj/prism ac_add_options --with-libxul-sdk=../dist ac_add_options --enable-application=prism You need to define an environment variable to point the build to the new .mozconfig. This variable is called MOZCONFIG export MOZCONFIG=$PWD/.mozconfig #t...
Priority Content - Archive of obsolete content
dge Article Migrators: Mathieu Deaudelin There are inline examples on this page that cannot be migrated. They are dependant on some style instructions that can only be placed in the header of the page. Started: Scripting Plugins: Macromedia Flash Original: Scripting Plugins: Macromedia Flash Wiki Location: Scripting Plugins: Macromedia Flash Migrators: Dependant on (these parts need to be done, put your name down) Completed: SOAP in Netscape Gecko-based Browsers Original: SOAP in Netscape Gecko-based Browsers Wiki Location: SOAP in Gecko-based Browsers Migrators: Doron Rosenberg In progress: CSS Support Charts Original: CSS Support Charts and Archive.org mirror Wiki Location: CSS Support Charts Migrators: Serge K. Keller Licensing: These CSS charts appear to be under a CC:...
Same origin policy for XBL - Archive of obsolete content
r the element whose style attribute is being looked at). For the nsIDOMDocumentXBL interface's nsIDOMDocumentXBL.addBinding() and nsIDOMDocumentXBL.loadBindingDocument() methods, the originating principal is the one of the script making the call, or the principal of the document the call is made on if there isn't a script. Checks performed Once the originating principal is determined, checks are done to make sure the load should be allowed. The checks performed are: If the principal originating the load is the system principal, the load is allowed. A call to ChecLoadURIWithPrincipal() is done to make sure the principal is able to link to the given URI in the first place. A content policy check is performed. If the URI is a chrome: URI, the load is allowed. Note that step 2 already denied the...
Space Manager Detailed Design - Archive of obsolete content
e SpaceManager. Next, create a rect from the occupied space passed in by the caller,transforming it first to world-coordinates by adding the Space Manager's offset to the occupied space rect passed in. Create a new Frame Info instance for the frame and rect, returning an error if allocation fails. Check if the occupied space rect (adjusted) is empty, if so, return an error (NOTE: this could be done earlier, or prevented by the caller) Allocate a new BandRect instance with the rect and frame as constructor arguments, and insert it into the collection via InsertBandRect InsertBandRect: Internal method to insert a band rect into the BandList in the correct location. There are several cases it has to handle, as specified in the source file comments: // When comparing a rect to a band there...
Supporting private browsing mode - Archive of obsolete content
teBrowsingMode; pbs.privateBrowsingEnabled = true; /* this is all private */ pbs.privateBrowsingEnabled = oldPrivateMode; In this example, we save the current state of the private browsing mode setting in the oldPrivateMode variable, then turn on private browsing by setting its value to true. From that point until we restore the original value of the private browsing mode setting, things are done privately. This allows us to, for example, work with the Places database without affecting its contents. Private browsing notifications There are notifications available that allow you to easily watch for changes to the status of the private browsing mode, including detecting when it turns on and off. In addition, there is a browser:purge-session-history notification that is sent when the brows...
Tamarin - Archive of obsolete content
in pages at wiki.mozilla.org More documentation. MMgc overview An overview of the Tamarin garbage collector. Nanojit LIR In Nanojit, LIR is the source language for compilation to machine code. Tamarin strings documentation The implementation of Tamarin strings has changed. This page is a how-to about the changes, and what can be done to adapt source code to the changes. Tamarin doxygen documentation Documentation for the latest release. Get Involved! log a bug against Tamarin tamarin-devel mailing list #tamarin channel on irc.mozilla.org Blogroll Mason Chang David Mandelin Related Topics JavaScript SpiderMonkey ...
Treehydra - Archive of obsolete content
Use at your own risk. Try the gcc python plugin instead: https://fedorahosted.org/gcc-python-plugin/. Treehydra is a GCC plugin that provides a low level JavaScript binding to GCC's GIMPLE AST representation. Treehydra is intended for precise static analyses. Most of Treehydra is generated by Dehydra. A Dehydra script walks the GCC tree node structure using the GTY attributes present in GCC. Treehydra is included in Dehydra source, and is built when a plugin-enabled CXX is detected. For description of node types used in Treehydra see tree.def and cp-tree.def in the GCC sources. ...
XML in Mozilla - Archive of obsolete content
To fully implement XLink, we need something called a link manager. See some initial design documents. Testing and QA We have a lot of testcases linked to from the browser standards compliance QA page. Most of the core XML test documents on the mercurial repository are located in content/xml/tests. We also have ...
Install script template - Archive of obsolete content
ableError; } // If we can't find the plidPath create the key if (!winreg.keyExists(plidPath)) { logComment("Moz registerPLID: creating missing key "+plidPath+"."); myRegStatus = winreg.createKey(plidPath, ""); if (myRegStatus != 0) { logComment("Moz registerPLID: Could not create the key, "+plidPath+"as expected. Errorcode="+myRegStatus); return myRegStatus; } } // OK were done, let's write info about our plugin, path, productname, etc // Write a subkey to MozillaPlugins with our PLID //var mySetStrRC = winreg.setValueString(plidPath, plidID, dllAbsolutePath); myMozillaPluginPath = plidPath+"\\"+plidID; // For instance. SOFTWARE\MozillaPlugins\@Cycore.com/Cult3DViewer myRegStatus = winreg.createKey(plidPath+"\\"+plidID, ""); if (myRegStatus != 0) { logComment...
A XUL Bestiary - Archive of obsolete content
ired somewhere below them in the hierarchy. A menubar in XUL, for instance, can contain event handlers for events fired by its child menuitems. Mozilla XPArchitecture Mozilla is obviously a lot more than simply an interface. It's cross-platform, and standards-based, and yet in some way, the event handlers written once in JavaScript and living in the XUL interface are getting very serious things done down in the application core. Things like socket interfaces, editing, mail/news, security. The technologies that make this possible are perhaps the least understood of the phalanx of innovations that is Mozilla. In addition to the small matter of programming these serious things in C++ and compiling them platform for platform, the architects and developers of Mozilla use three "XP" technologies t...
disableKeyNavigation - Archive of obsolete content
This feature may be disabled by setting this attribute to true. ...
sizemode - Archive of obsolete content
e window is maximized, and occupies the full size of the screen. normal The window appears in a normal state at the desired size. This attribute is used to save and restore the state of a window (together with the persist attribute) and for CSS styles (e.g. to hide the resizer grippy on maximized windows). Note: When a window is minimized, the sizemode attribute is not updated. This is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. Setting this attribute does not change the window state. Use window.maximize(), window.restore(), or window.minimize() to change the window state. To get the window state from JavaScript code, use window.windowState. Listen to the sizemodechange event dispatched to the DOM window to get notifi...
XUL Events - Archive of obsolete content
on an element. attribute: onmouseup select This event is sent to a listbox or tree when an item is selected. attribute: onselect unload This event is sent to a window when the window has closed. This is done after the close event. You should place this event handler on the window element. attribute: onunload Mutation DOM events Event Description DOMAttrModified This event is sent to an element when one of its attributes is...
Accessing Files - Archive of obsolete content
this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Accessing Files This section describes how to create a file reference. Retrieving a File When working with files, usage is always done via a File object and not via string paths. This allows files to used in a portable way. Because string paths are not used, references to files in a File object are made relative to some starting directory. A number of starting directories may be used, for instance, the user's home directory, the desktop, the system's temporary folder, and so forth. Once one of these starting directories is deter...
Reading from Files - Archive of obsolete content
he bytes being read into characters in a particular character encoding whereas binary streams always read bytes. First, let's look at reading form text files. Reading Text Files Characters are interpreted from a text input stream using a specified character encoding. This means that if a character within the file occupies several bytes, it will converted into a single character when read. This is done automatically as long as you specify the 'text' flag to nsIScriptableIO.newInputStream(). The default character encoding is UTF-8 which means that characters below value 128 will occupy a single byte whereas characters above value 128 will occupy multiple bytes, depending on their value. However, a number of other character encodings are available; see Reading Other Character Encodings below for ...
Uploading and Downloading Files - Archive of obsolete content
ng the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. The IO object and stream objects can be used to upload files to servers in various ways. The exact method depends on the type of upload that you wish to perform. HTTP File Upload Some web sites allow one to upload a file. This is done by using an HTML <input> element using the file type from within a form. When the user selects a file, it can be uploaded to a server. This operation can also be performed via a script using the XMLHttpRequest object. This is a common technique for uploading files as it is compatible with existing servers and FormData interface makes that task fairly simple. A FormData object will automatically ...
Writing to Files - Archive of obsolete content
putStream method. In this example, the nocreate flag is used to prevent the creation of new files, and the append flag is used to append to an existing file. Writing Text Files Characters are written to a text input stream using a specified character encoding, which defaults to UTF-8. This means that a single character will occupy several bytes if it has a value greater than 128. This encoding is done automatically as long as you specify the 'text' flag to nsIScriptableIO.newOutputStream(). Other character encodings are available; see Writing Other Character Encodings below for details about writing text in other encodings. There are several methods available to write to a stream. For text files, you will usually use the writeString method. var file = IO.getFile("Desktop", "myinfo.txt"); var s...
How to implement a custom XUL query processor component - Archive of obsolete content
// eventually we should read the <query> to create filters return this._data; }, generateResults: function(aDatasource, aRef, aQuery) { // preform any query and pass the data to the result set ...
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
XUL Reference The id should match an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing items: 525 insertItemAt XUL Methods, XUL Reference No summary! 526 invertSelection XUL Methods, XUL Reference No summary! 527 loadGroup XUL Methods, XUL Reference No summary! 528 loadOneTab Method, Mozilla, Reference, XUL, XUL Methods, XUL Reference No summary! 529 loadTabs XUL Methods, XUL Reference No summary! 530 loadURI XUL Methods, XUL Reference NOTE: This is the XUL method on <browser> / <tabbrowser>, not the global function in chrome://browser/content/browser.js. Please check which one you're documenting! (This one has no...
International characters in XUL JavaScript - Archive of obsolete content
and earlier versions, you must limit yourself to ASCII. However, you can use unicode escapes - the earlier example rewritten using them would be: var text = "Ein sch\u00F6nes Beispiel eines mehrsprachigen Textes: \u65E5\u672C\u8A9E"; An alternative might be to use property files via nsIStringBundle or the XUL <stringbundle> element; this would allow for localization of the XUL. This can not be done in XUL files loaded from the web, only in privileged code, e.g. in extensions. ...
Introduction to XUL - Archive of obsolete content
term Mozilla-the-organization is using to describe Mozilla-the-browser's Cross Platform Front End, because X and C look similar if you beat them long and hard with a hammer. The intention is to build cross-platform applications like browsers and mail clients from a set of tools designed for that purpose. The intention is not to implement a generic cross-platform application framework. That's been done, and is a great deal of work. We intend to provide a subset of cross-platform functionality suitable for building network applications like browsers, leveraging the cross-platform functionality already built into Gecko, Mozilla's HTML layout engine. The term "cross-platform UI" is somewhat misleading. UI designers will be able to create UI descriptions which will work on multiple platforms. But ...
Methods - Archive of obsolete content
getResultAt getResultCount getResultValueAt getRowCount getSearchAt getSelectedItem getSession getSessionByName getSessionResultAt getSessionStatusAt getSessionValueAt getString goBack goBackGroup goDown goForward goForwardGroup goHome goTo gotoIndex goUp hidePopup increase increasePage insertItem insertItemAt invertSelection loadGroup loadOneTab loadTabs loadURI loadURIWithFlags makeEditable moveByOffset moveTo moveToAlertPosition onSearchComplete onTextEntered onTextReverted openPopup openPopupAtScreen openSubDialog openWindow preferenceForElement reload reloadAllTabs reloadTab reloadWithFlags removeAllItems removeAllNotifications removeAllTabsBut removeCurrentNotification removeCurrent...
Extensions - Archive of obsolete content
<menuitem label="Mail"/> </menupopup> </menu> </menubar> This menu is added to the main menu bar just before the Tools menu. The insertbefore attribute is set to 'tools-menu' to ensure that the new menu is added at the right place. Note that the menu will not appear until it has a <menupopup>. Adding a new menuitem You might wish to add a new item to one of the menus. This can be done by overlaying the popup to append the item to. For a list of the ids of the menus for Firefox, see Firefox Menus. For example, to add an item to the end of the Tools menu, use the following: <menupopup id="menu_ToolsPopup"> <menuitem label="Thesaurus"/> </menupopup> Note that other extensions may be adding their own items into the same menus. Because of this, the new item might not appear at...
MenuButtons - Archive of obsolete content
he menu provides more specific options pertaining to the operation. We might want to extend this example to insert a list of the unsaved documents to the Save button menu so that each could be saved individually. You might want to set the first item in the example above as the default button, so it indicates to the user that the command is carried out when the main button is pressed. This can be done by setting the default attribute on the item to true. <menuitem label="Save This Document" default="true"/> See Indicating_the_Default_Item for more information about the default attribute. As with the 'menu' type, the 'menu-button' type may be applied to either the button or the toolbarbutton element. ...
Additional Navigation - Archive of obsolete content
e is only one title available. The second triple is the more interesting one. It is used to look up nodes that have a Country predicate pointing in. It may be difficult to tell whether the builder will look for arcs pointing out from a node or into a node just by looking at the triple element. The template builder doesn't know this either until the triple is evaluated and variable substitution is done. Here, the value of the ?start variable is already known for the potential result, so it will be filled in. However, the value of the ?photo variable is not known. Since the object is known and the subject is not, the builder knows to look for a predicate pointing in to a node. There are two photos in the RDF datasource that point to the node 'http://www.daml.org/2001/09/countries/iso#IT', so the...
Attribute Substitution - Archive of obsolete content
uri attribute since that wouldn't be meaningful. Note that variable names must have a space after them as this is how the end of variable is determined. That is '?name?age' is considered to be a single variable with that name, not two variables together. To use two variables, place a space between them. It is sometimes useful though, to concatenate two values together without a space. This can be done simply by putting two variables next to each other in an attribute value separated by a caret (^). <label value="?name" class="?gender^?nationality"/> The caret is considered a separator between variables, however it will not appear in the output. It can also be used to separate a variable with normal text: <label value="?name" class="?gender^german"/> These last two examples have been setting ...
Bindings - Archive of obsolete content
http://www.xulplanet.com/ndeakin/images/t/palace.jpg, ?title = 'Palace from Above', ?description = 'View from the top of the tower looking east of the Doges Palace') Thus, only one match exists, so only one set of content is generated. Sometimes, it would be useful to have triples that match conditionally; that is, a triple that doesn't cause a result to be removed as a possible match. This is done with a binding element. This tag doesn't go in the query block but instead inside a rule element. The syntax is as follows: <template> <query> ... </query> <rule> <binding subject="?photo" predicate="http://purl.org/dc/elements/1.1/description" object="?description"/> <action> ... </action> </rule> </template> The description triple has bee...
Building Hierarchical Trees - Archive of obsolete content
ht display a node's children as the children in the tree, making the tree display a hierarchy similar to that in the XML document. Or, with more complex XPath expressions, a template could display a tree where the hierarchy wasn't directly like the XML document. If a node is a container, the tree item becomes a container, and the user may open the row by double-clicking it. Note that this test is done on the member value not the reference value. For instance, in the photo example, we have a container 'http://www.xulplanet.com/rdf/myphotos' with three photos. Three results will be generated from a simple rule with no extra conditions. It is the result, or the photo, that will be checked, not the container of photos. Since a photo isn't a container, the tree rows will not become containers, so y...
Filtering - Archive of obsolete content
For instance, to apply a filter, you might add a new <triple> element. To remove the filter, the <triple> should be removed again. ...
Introduction - Archive of obsolete content
> In addition, when using the RDF type for chrome XUL (such as in extensions), the datasource rdf:local-store is always included in the composite. The local store is a datasource which is usually used to hold state information such as window sizes, which columns in a tree are showing, and which tree items are open. You can query for any data in the local store in a template though this is rarely done. Sometimes, you will want to specify the datasource to be used later, possibly determined dynamically by a script. The special URI rdf:null is used to indicate that you intend no datasources, or an empty datasource. This special URI will also work even for non-RDF types, so feel free to use it when needed. It effectively means, use no datasource for this template, which will likely result in no o...
RDF Query Syntax - Archive of obsolete content
ox> This query has two statements, each specified with a different tag. The template won't generate anything yet since we still need to fill in the content to be generated which goes in the missing part inside the rule. However, the template builder will be able to compile the rules and examine them as described earlier. The builder needs to start with a single result as the seed result. This is done with the content tag. It indicates that we are going to use a starting point when navigating the graph. Obviously, since you need to start somewhere, you will have to use a content tag and it should be the first statement. Also, because we can only have one starting point, only one content tag can be used. The seed result will be created like this: (?start = http://www.xulplanet.com/rdf/A) The v...
Result Generation - Archive of obsolete content
yzed, any results which still remain go on to become matches. The matches are the endpoints and will cause content to be generated. So, to summarize: Start out with a one possible result as the seed Iterate over the results determined so far and augment them with additional data Add any new possible results Remove any rejected results Repeat steps 2 to 4 for each query statement Once done, all remaining results become matches Each possible result is made up of a set of variable-value pairs. For instance, a result would look something like the following: (?name = Fred, ?age = 5) This result has two variables, ?name with the value 'Fred' and ?age with the value 5. Variables begin with a question mark, and values are RDF resources or literals. Here we will use strings for the value...
Rule Compilation - Archive of obsolete content
Calling a DOM API which needs to get at the generated content will cause the template builder to generate output. For example, just calling the code like the following on the hidden vbox above will start off the template builder. var length = vbox.childNodes.length; This request to return the number of children of the vbox will make the template builder process the query and output content. Once done, the correct length can be returned. All of this is transparent to the XUL developer. When the template builder decides to start generation is determined automatically, and you don't need to do anything special to get this to happen. However, there are two cases where content is not generated automatically: menus and child tree items. Content inside a menu is not generated until the menu is opene...
Sorting Results - Archive of obsolete content
date. If you are using the simple RDF query syntax, there are no variables, so you need to specify the full predicate including the rdf: prefix in the sort attribute. For instance: <treecol id="name" label="Name" sort="rdf:http://purl.org/dc/elements/1.1/title" flex="1"/> Note that all of this discussion about sorting only applies to tree builders. For other elements or content trees, sorting is done by placing the attributes on the root element. Content Sorting For content builders (templates that do not use flags="dont-build-content"), sorting is done by placing the sort and sortDirection attributes on the root node of the template. The sortActive attribute is not needed. In this example, the list of people is sorted ascending by name. <listbox datasources="people2.xml" ref="*" querytype="x...
Static Content - Archive of obsolete content
bel 'All'. The template generates two results as before, one for each country, and appends a menuitem for each one. One interesting thing about this example is that only one menupopup will be created, even though there are two in the code, one outside the template and another one inside the action body. This demonstrates how the template builder generates content, and the specifics of how this is done become important when dealing with recursive content and multiple rules. What's going on here is that the XUL parser first creates the outer menulist element. The static content outside the template will also be created. The result will be a XUL display that looks just like the code above, except that the template and its content is hidden. At this point, the menulist will have a menupopup as a c...
Template Logging - Archive of obsolete content
help. Logging Template Results There are two main ways in which template errors may be detected. The first debugging method involves logging all new results that apply to the template due to the data changing as well as logging results that are changed or removed. In addition, each result generated when the template is first created and initialized is logged. This logging of result changes is not done by default; it must be enabled with a flag. <vbox datasources="..." flags="logging"/> The flags attribute on the root element of the template should include the logging flag. If other flags are used as well, separate them with spaces. Enabling logging will output details to the error console for each result. The error console can be found on the Firefox Tools menu. This logging of results can be...
textbox (Toolkit autocomplete) - Archive of obsolete content
bute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. disableKeyNavigation Type: boolean If this attribute is not used, the user can navigate to specific items within the element by pressing keys corresponding to letters in the item's label. This is done incrementally, so typing more letters with select more specific items. This feature may be disabled by setting this attribute to true. Note: For SeaMonkey 2.0 and all versions of Thunderbird prior to 3.0 you also need to provide the disablehistory attribute. enablehistory New in Thunderbird 1Requires SeaMonkey 2.0 Type: boolean If true, an arrow button will appear on the...
Custom toolbar button - Archive of obsolete content
ng Explanation: This image is displayed in the application's Extension Manager window. Testing your new button Restart the application. Either get a context menu for the application's toolbar (for example, by right-clicking it) and choose Customize..., or choose View - Toolbars - Customize... from the application's menu bar. Drag your new button to where you want it on the toolbar. Press Done to close the toolbar palette window. Click the button to test it. You should see the pop-up message. Further development This section describes how you can develop your button further. Uninstalling the button If you ever want to uninstall the button, delete the directory that you created in step 2. Alternatively, use the application's Extensions window to uninstall the extension in the norm...
Box Objects - Archive of obsolete content
ordinal value. For example, if one element has an ordinal of 2, it would be placed before an element with ordinal 3 or higher but after one with ordinal 1. The default value if the ordinal is not specified is 1. This means that if you want to change the displayed order of elements, you will often need to adjust the ordinals of several elements. Adjusting the ordinal of an element is not commonly done as you would usually just place the elements in a different order in the source. It might be used to rearrange items later without adjusting the DOM. The following example demonstrates this. Example 4 : Source View <hbox> <button label="One" oncommand="this.ordinal++;"/> <button label="Two" oncommand="this.ordinal++;"/> <button label="Three" oncommand="this.ordinal++;"/> </hbox> If you pre...
Install Scripts - Archive of obsolete content
igned installation directory. addDirectory ( dir ); addFile ( dir ); Example: addDirectory("findfile"); The example above will specify that the findfile directory from the installer archive should be installed. We can call these functions multiple times to install other files. Next, we'll want to register the find files in the chrome system so that it can be used with a chrome URL. This can be done with the registerChrome() function. It takes two arguments, the first is the type of chrome to register (content, skin or locale). The second is the directory containing the contents.rdf file to register. Because the find files dialog contains content, a skin file and a locale file, registerChrome() will need to be called three times. registerChrome(Install.CONTENT | Install.DELAYED_CHROME, getFo...
Introduction - Archive of obsolete content
ilbox, their bookmarks and search results. The contents of menus, trees and other elements can be populated with this data, or with your own data supplied in an RDF file. There are several ways you can use XUL: Firefox extension An extension adds functionality to the browser itself, often in the form of extra toolbars, context menus, or customizations to the browser's user interface. This is done using a feature of XUL called an overlay, which allows the UI provided from one source, in this case, the Firefox browser, to be merged together with the UI from the extension. Extensions may also be applied to other Mozilla based products such as Thunderbird. Standalone XULRunner application XULRunner is a packaged version of the Mozilla platform which allows you to create standalone XUL appli...
Manifest Files - Archive of obsolete content
ed to do is create a manifest file with one of these two lines in it, modified to suit your theme or locale. For more information about Themes, see Themes. For more information about Locales, see Localization. Our example find files dialog Let's create a manifest file for the find files dialog we'll be creating. You can combine all of the three types into a single file if you wish. This may be done when creating an extension such that all of the parts are in one file. We will do this for the find files dialog. Create a file findfile.manifest in the chrome directory. Add the following to the file: content findfile file:///findfile/content/ skin findfile classic/1.0 file:///findfile/skin/ locale findfile en-US file:///findfile/locale/ Create the new directories listed above. It doesn't mat...
Modifying a XUL Interface - Archive of obsolete content
you may call the cloneNode() function. This function makes a copy of an existing node so that you can add it somewhere else. The original node will stay where it is. It takes one boolean argument which indicates whether to copy all of the node's children or not. If false, only the node is copied, such that the copy won't have any children. If true, all of the children are copied as well. This is done recursively, so for large tree structures make sure that this is desired before passing true to the cloneNode() function. Here is an example: Example 2 : Source View <hbox height="400"> <button label="Copy" oncommand="this.parentNode.appendChild(this.nextSibling.cloneNode(true));"/> <vbox> <button label="First"/> <button label="Second"/> </vbox> </hbox> When the Copy but...
Modifying the Default Skin - Archive of obsolete content
L file. By applying a different skin, you can change the look of a window without changing its functionality. Firefox provides a skin by default, and you may download others. The XUL for any skins is the same, however the style sheets and images used are different. For a simple personalized look to a Firefox window, you can easily change the style sheets associated with it. Larger changes can be done by creating an entirely new skin. Firefox has a Theme Manager for changing the default skin. (Although the underlying code for Mozilla calls them skins and the user interface calls them themes, they're both referring to the same thing). A skin is described using CSS, allowing you to define the colors, borders and images used to draw elements. The file classic.jar contains the skin definitions. T...
More Event Handlers - Archive of obsolete content
d y position of the element. In this example code, these coordinates are subtracted from the event coordinates to get the event position relative to the element. Load Events The load event is sent to the document (the window tag) once the XUL file has finished loading and just before the content is displayed. This event is commonly used to initialize fields and perform other tasks that need to be done before the user can use the window. You should use a load event to do these kinds of things as opposed to adding a script at the top level outside of a function. This is because the XUL elements may not have loaded or fully initialized yet, so some things may not work as expected. To use a load event, place an onload attribute on the window tag. Call code within the load handler which will initia...
Open and Save Dialogs - Archive of obsolete content
d filters, call the appendFilters() function to set the file types that you wish to have displayed. fp.appendFilters(nsIFilePicker.filterHTML | nsIFilePicker.filterImages); fp.appendFilters(nsIFilePicker.filterText | nsIFilePicker.filterAll); The first example will add filters for HTML and for image files. The user will only be able to select those types of files. The manner in which this is done is platform specific. On some platforms, each filter will be separate and the user can choose between HTML files and image files. The second example will add filters for text files and for all files. The user therefore has the option to display text files only or all files. You can also use filterXML and filterXUL to filter for XML and XUL files respectively. If you would like to filter for cu...
Scroll Bars - Archive of obsolete content
is a numeric value and does not have a unit. The default value is 100. increment The value here specifies how much the value of curpos changes by when the user clicks on one of the scroll bar arrows. The default value is 1. pageincrement The value here specifies how much the value of curpos changes by when the user clicks pages through the scroll bar, which can be done by clicking on the tray between the box and the arrows. The default value is 10. The example given in the syntax above will create a scroll bar that can range from a value of 0 to 100. The value 100 might be the number of lines in a list, but it could be anything you want. The initial value in this example is 20. When clicking on one of the scroll bar arrows, the value would change by 1 either u...
Skinning XUL Files by Hand - Archive of obsolete content
tools that you can lose sight of what the purpose and impact of these technologies are. The combination of XUL and CSS provides so much flexibility that it can seem daunting. The purpose of this split between XUL and its skins -- and between the global skin and whatever custom styles you might create -- is to enable the dynamic skinning of applications such as the Mozilla browser. What you have done manually in this article will be done dynamically and much more completely by a mechanism called thechrome registry. this needs rewording: , which, like the Windows registry, is a database in which information about a user's software and environment can be recorded and accessed as necessary. Software components and users will be able to update the chrome registry and change the global skin. And w...
Templates - Archive of obsolete content
ther content is built, it is the datasources attribute. When this attribute is present, an object called a Builder is added to the element which is responsible for building the content from the template. In JavaScript you can access the builder object with the builder property, although usually you would only need to do this to have the builder regenerate the content in situations where it is not done automatically. There are two different types of builders. The first is a content builder and is used in most situations, and the other is a tree builder which is used only for trees. Content Builder The content builder takes the content inside the template element and duplicates it for each row. For instance, if the user had ten bookmarks in the example above, ten label elements would be creat...
XPCOM Examples - Archive of obsolete content
org") menu.appendItem(cookie.name,cookie.value); } } } </script> <hbox> <menulist id="cookieMenu" onpopupshowing="getCookies();"/> </hbox> The getCookies() function will be called whenever the menu is opened, as indicated by the onpopupshowing attribute on the menulist. The first two lines of getCookies() get the menulist and remove all of the existing items in the menu. This is done because getCookies() is called every time the menu is opened and we don't want to leave the old items there each time. Next, the cookie manager is retrieved. The cookie manager has an enumerator method which returns an object which implements nsISimpleEnumerator. This can be used to iterate over all of the cookies. An enumerator has a hasMoreElements() method which will return true until we get t...
XPCOM Interfaces - Archive of obsolete content
d, and, if so, we can play sound through it. The process of calling XPCOM from a script is called XPConnect, which is a layer which translates script objects into native objects. Creating XPCOM Objects There are three steps to calling an XPCOM component. Get a component Get the part of the component that implements the interface that we want to use. Call the function we need Once you've done the first two steps, you can repeat the last step as often as necessary. Let's say we want to rename a file. For this we can use the nsILocalFile interface. The first step is getting a file component. Second, we query the file component and get the portion of it that implements the nsILocalFile interface. Finally, we call functions provided by the interface. This interface is used to represent a ...
Using nsIXULAppInfo - Archive of obsolete content
on. Platform version nsIXULAppInfo provides version information about both the XUL application (such as Firefox) and the platform (i.e. Gecko or XULRunner). For example, in Firefox 1.5 beta 2 application version is 1.4.1 and platform version is 1.8b5. Be careful to use the information you need, especially when dealing with XULRunner-based applications. Obtaining platform version information is done like this: var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo); var platformVer = appInfo.platformVersion; var platformBuildID = appInfo.platformBuildID; Getting nsIXULAppInfo in xpcshell tests In Firefox 21, a testing module was added that provides access to app info during the execution of xpcshell tests. S...
Using the Editor from XUL - Archive of obsolete content
You can find the relevant XUL parts in editor.xul, the JavaScript parts in editor.js, and the XBL binding for the editor element in editor.xml. Something, somewhere, tells Mozilla to open the composer window. editor.xul is loaded. In editor.xul, the <window> tag has an onload handler: onload="EditorOnLoad()". That causes the EditorOnLoad() JavaScript function to get executed when the XUL is done loading. The XUL contains an <editor> tag, e.g.: <editor type="content-primary" id="content-frame" src="about:blank" flex="1"/> The attribute type="content-primary" identifies this as the window content element, i.e. that which you get from window._content. Having an id attribute, id="content-frame", allows us to find this element with document.getElementById("content-frame"), and to sty...
Writing Skinnable XUL and CSS - Archive of obsolete content
responds to the name of the package. For example, the skin for the Navigator package should contain a file called navigator.css that determines the default look of all XUL windows posed from this package. If inheriting the global skin, a skin file must import the global skin explicitly. If your skin file wishes to inherit the global skin, then it should import the global skin explicitly. This is done using an @import directive placed at the top of the file. @import url(chrome://global/skin/) ... rest of skin file ... CSS files for a skin fall into two categories: base skin files and derived skin files. CSS files that import another skin file are calledderived skin files. CSS files that don't import another skin file are calledbase skin files. There is one notable exception to this rule.
XUL Questions and Answers - Archive of obsolete content
lite) datasources (bug 321172) When loading an XSLT stylesheet into an XML I get the error: "Error loading stylesheet: An XSLT stylesheet load was blocked for security reasons." That error is from a security check that has been put up to safeguard against cross-site-scripting attacks. A scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn't work on a Mac? Unfortunately, no simple solution to this was posted. A workaround is to open the content in a new window using "window.open" and send titlebar="no" as one of the flags in the 3rd argument. Is it possible to have checkbox support for multi column lists? The current issue is a person exploring if it is possible to have checkbox support for multi co...
XUL accessibility guidelines - Archive of obsolete content
d as their primary input tool. These users require easy, predictable, and well-documented keyboard control. Tab order Provide a logical tab order and ensure that users can navigate all content using a keyboard. By default, the tab order is determined by the order of the elements in the underlying code. It can also be set programmatically with the tabindex attribute if needed, but this should be done sparingly and thoroughly tested whenever it is used. The navigation order should be logical, generally left to right, top to bottom. Navigation order may vary depending on the nature of the application or the reading direction of the language. Ensure that tab order is logical and all interactive elements can be accessed simply without the use of a mouse. You should be able to perform all functio...
XUL accessibility tool - Archive of obsolete content
g tools. Merge with other XUL checking tools -- this doesn't need to be a11y-specific. One problem is that Mark Finkle's XUL Validator tool uses a different engine. Add the tool into the addons.mozilla.org review process Go through the most useful/popular extensions with tool and fix a11y issues Add checker to tinderbox so that bugs are caught at checkin time Some or all of this work could be done through grants, and a likely person to oversee the grant deliverables and milestones would be Mark Finkle. He has volunteered to take that on. ...
The Implementation of the Application Object Model - Archive of obsolete content
, it will still CONTAIN NO DRAWING CODE. Individual widgets, even complex widgets like the trees and toolbars need little to no drawing code (above and beyond what NGLayout already has) in order to work. Native widgets vs. NGLayout's form element widgets. This is really another issue of code bloat. It is a given that NGLayout will ship with its own non-native form element widgets. This has to be done in order to get features like transparency into those widgets. If XUL is dropped from the picture, then dialogs would have to be described using native widgetry (unless you're willing to design an HTML dialog system, which still wouldn't cut it without extending HTML), and Communicator would have to ship with both widget sets. The native widgets would also be an issue for something like a gfx-too...
listbox - Archive of obsolete content
ibute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. disableKeyNavigation Type: boolean If this attribute is not used, the user can navigate to specific items within the element by pressing keys corresponding to letters in the item's label. This is done incrementally, so typing more letters with select more specific items. This feature may be disabled by setting this attribute to true. preference Type: id Connects the element to a corresponding preference. This attribute only has any effect when used inside a prefwindow. More information is available in the Preferences System article. rows Type: integer The numbe...
richlistbox - Archive of obsolete content
bute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. disableKeyNavigation Type: boolean If this attribute is not used, the user can navigate to specific items within the element by pressing keys corresponding to letters in the item's label. This is done incrementally, so typing more letters with select more specific items. This feature may be disabled by setting this attribute to true. preference Type: id Connects the element to a corresponding preference. This attribute only has any effect when used inside a prefwindow. More information is available in the Preferences System article. seltype Type: one of the values below Used...
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
ibute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. disableKeyNavigation Type: boolean If this attribute is not used, the user can navigate to specific items within the element by pressing keys corresponding to letters in the item's label. This is done incrementally, so typing more letters with select more specific items. This feature may be disabled by setting this attribute to true. editable Type: boolean Indicates that the cells of the tree may be edited. enableColumnDrag Type: boolean When set to true, the user may drag the column headers around to change the order in which they are displayed. flags Type: space-separa...
window - Archive of obsolete content
e window is maximized, and occupies the full size of the screen. normal The window appears in a normal state at the desired size. This attribute is used to save and restore the state of a window (together with the persist attribute) and for CSS styles (e.g. to hide the resizer grippy on maximized windows). Note: When a window is minimized, the sizemode attribute is not updated. This is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. Setting this attribute does not change the window state. Use window.maximize(), window.restore(), or window.minimize() to change the window state. To get the window state from JavaScript code, use window.windowState. Listen to the sizemodechange event dispatched to the DOM window to get notifi...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
lter substitution in the manifest for the variable to be expanded). You will also need to include a branding/ subdirectory. Follow the example in McCoy carefully since XULRunner is sensitive about having exactly the right files in exactly the right packages. The components/ subdirectory If you are reading this guide, you probably need to include C++ components in your application. If you've never done this before, you should consult Creating XPCOM Components or another XPCOM reference. The public/ and src/ directories that you put in the components/ directory will look the same as for an extension that includes C++ components, so you can use the relevant sections of Creating Custom Firefox Extensions with the Mozilla Build System as a reference. The makefiles, however, will be difference since...
How to enable locale switching in a XULRunner application - Archive of obsolete content
fr-FR locale/fr-FR/ How are you going to populate the XUL listbox? You can hardwire the choices into the XUL code using fixed list items, or could take the elegant approach and construct the list dynamically. The dynamic list population requires an XPCOM to query the currently selected locale as well as all locales available in the application package. ...
Opening a Link in the Default Browser - Archive of obsolete content
XULRunner applications may have situation where they wish to open a URI in the default browser. This will often be an HTTP or HTTPS URI, but can use any scheme for which an external handler exists. ...
XULRunner tips - Archive of obsolete content
pref("browser.download.useDownloadDir", true); pref("browser.download.folderList", 0); pref("browser.download.manager.showAlertOnComplete", true); pref("browser.download.manager.showAlertInterval", 2000); pref("browser.download.manager.retention", 2); pref("browser.download.manager.showWhenStarting", true); pref("browser.download.manager.useWindow", true); pref("browser.download.manager.closeWhenDone", true); pref("browser.download.manager.openDelay", 0); pref("browser.download.manager.focusWhenStarting", false); pref("browser.download.manager.flashCount", 2); // pref("alerts.slideIncrement", 1); pref("alerts.slideIncrementTime", 10); pref("alerts.totalOpenTime", 4000); pref("alerts.height", 50); If you are missing preferences that a dialog requires, you will get the following errors: Comp...
Windows and menus in XULRunner - Archive of obsolete content
re.is.only.xul"> <script src="main.js"/> ... </window> Notice the references to CSS and DTD files. The CSS is used to apply formatting to elements, just as it would in HTML. The DTD is used to create entity references so strings for titles and labels are not stored directly in the XUL file; this makes updating the text -- and localization of the application -- much easier. The window title is done this way in the above example. Also notice the <script> element which is used to include the window's JavaScript into the XUL file. Keeping CSS, DTD and Javascript out of the XUL file is considered a best practice. When you launch your XUL application, you'll notice that XULRunner gives your windows a default icon (top left corner on Windows). You'll most likely want to specify your own icons. Y...
Archived Mozilla and build documentation - Archive of obsolete content
instead, or else try the gcc python plugin: https://fedorahosted.org/gcc-python-plugin/. Developing New Mozilla Features Tips For Contributing New Features To Mozilla. Devmo 1.0 Launch Roadmap Comments, ideas, questions and other discussion should be added on the Devmo talk:1.0 Launch Roadmap page. Further details on smaller tasks being done are available at User:Dria:TODO page. See also Current Events. Download Manager improvements in Firefox 3 Firefox 3 offers improvements to the Download Manager that allow multiple progress listeners, use of the Storage API for data management, download resuming, and more. In addition, you can augment or replace the Download Manager's user inter...
Mozilla release FAQ - Archive of obsolete content
s with 2.8.1 are ironed out) Where can I get the sources to Netscape 4.x or lower? These sources are not available. Much of the old code cannot be released due to legal concerns, and at the time of Mozilla's initial release, that code was removed from the tree. The 'Classic' branch of the current CVS tree is as close to the 4.x source as the public will ever see, although that branch has been abandoned in the move to the modern codebase. How do I tweak the interface (replace the logo, etc)? The XPToolkit docs might help in writing the needed XUL. You can find replacement themes in Preferences, under Appearance->Themes, using the 'get new themes' link there. Where can I get patches? There is not currently a central repository of patches. However, via CVS, you can keep up with the latest source ...
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
A wiki and IRC channel have been created to track their progress. Discussions Firefox trunk and rc1 slowdown using tabs Discussion regarding certain theme components (specifically alpha-transparency) creating a high CPU load on OS/2. Title case capitalization rules in Firefox Discussion regarding rules for capitalizing the first letter of Firefox menu items in the FF UI. ...
2006-10-06 - Archive of obsolete content
A wiki and IRC channel have been created to track their progress. Discussions Firefox trunk and rc1 slowdown using tabs Discussion regarding certain theme components (specifically alpha-transparency) creating a high CPU load on OS/2. Title case capitalization rules in Firefox Discussion regarding rules for capitalizing the first letter of Firefox menu items in the FF UI. ...
2006-10-13 - Archive of obsolete content
Xft and has tried looking at related postings by Benjamin Smedberg gcc-40-workarounds and gcc-and-visibility-one-step-forward-hit-a-brick-wall Announcements Please help us test the new Tinderbox and Bonsai server installations Paul Reed announced that they are setting up a new installation of the Tinderbox and Bonsai servers onto new, supported hardware. Some testing and validation has been done, but they would like other people to look at the installations and complete the setup before they switch over. New Tinderbox Installation New Bonsai Installation If any inconsistencies are found please use Bugzilla to let them know Discussions There were no discussions this week. Meetings There were no meetings this week. ...
2006-10-06 - Archive of obsolete content
and Lightning to Outlook. Extension Compatibility for Firefox 2 Chris Hofmann reminds about the push to have extensions work with FF2. Also invites people to file bugs about extensions that don't work. Also invites people to help extension developers test for compatibility (link to a bunch of extension compatability bugs) Discussions Reining in the release process A discussion of what can be done to speed up the release process. The new roadmap - will there be something sometime? Simon Paquet asked for an update of the road map and either update or removal of the planning blog. Adam Gutherie replied that cbeard's blog post from Nov 2005 is as close to a roadmap as exists right now and agrees that needs to be done about this. Re: Plan to hold trunk closed for lack of talkback Dbaron me...
2006-10-20 - Archive of obsolete content
Discussions Sparky AND comet going away on Friday Preed wants to get rid of Sparky and comet (both older desktop class linux boxes). Robert Kaiser gave some background on the boxes. ...
2006-11-10 - Archive of obsolete content
er important notes are contained in the link above Firefox and Thunderbird 1.5.0.8 were released Firefox and Thunderbird 1.5.0.8 were released on November 7, 2006 Blocker nomination and code freeze for 1.5.0.9/2.0.0.1 Blocker nomination is due on November 10. Code freeze for these versions is on November 26 Version numbering changes Paul Reed announced changes to the way version numbers are done for pre-releases. Discussion Version numbering changes Some discussion about Paul's announcement of version number changes Meetings November 6 Project Status Meeting (notes) November 7 Bon Echoe Status Meeting (notes) November 8 Gecko 1.9/Gran Paradiso status meeting: (agenda) ...
2006-11-10 - Archive of obsolete content
Meetings No meetings this week ...
2006-11-03 - Archive of obsolete content
la.dev.security - October 28, 2006 to November 3, 2006 Return to mozilla-dev-security Announcements None during this week. Discussions Extended Validation Certificates Major discussion this week started by Gervase Markham about security certificates, more specifically Extended Validation Certificates. The aim of the group is to develop a new, higher standard for the validation which is done before certificate issuance, called Extended Validation. The idea was that such certs would be presented differently in the UI, to give the CAs a reason to go to the extra effort, and to give customers a reason to buy them. In IE 7 at least, the use of an EV certificate is tied to the green background in the URL bar. A decision has to be made as to the usefulness of Extended Validation Certific...
Logging Multi-Process Plugins - Archive of obsolete content
Run Firefox in a custom environment to enable this special logging mode. Make sure you have write permissions to wherever you wish to save the log. Your safest bet is your home directory (C:\Users\username on Windows Vista and above, C:\Documents and Settings\username on Windows XP, and ~ (home directory) on Mac OS X and Linux). Windows Make sure Firefox is not running. ...
Monitoring plugins - Archive of obsolete content
The topic contains the notification's topic - experimental-notify-plugin-call in this case, the data is the runtime in milliseconds and the subject is always null and should not be used. Here is an example that shows the runtime in an alert box to the user if the runtime exceeds ...
NPAnyCallbackStruct - Archive of obsolete content
ure during embedded mode printing. During printing in embedded mode, the platformPrint field of the NPEmbedPrint structure points to an NPAnyCallbackStruct. This structure contains the file pointer to which the plug-in should write its PostScript data. At the time the plug-in is called, the browser has already opened the file and written PostScript for other parts of the page. When the plug-in is done, it should leave the file open, as the browser can continue to write additional PostScript data to the file. See also NPP_Print() NPEmbedPrint NPSetWindowCallbackStruct NPPrintCallbackStruct ...
NPN_DestroyStream - Archive of obsolete content
NPStream* stream, NPError reason); Parameters The function has the following parameters: instance Pointer to current plug-in instance. stream Pointer to current stream, initiated by either the browser or the plug-in. reason Reason the stream was stopped so the application can give the user appropriate feedback. Values: NPRES_DONE (most common): Stream completed normally; all data was sent by the plug-in to the browser. NPRES_USER_BREAK: Plug-in is terminating the stream due to a user request. NPRES_NETWORK_ERR: Stream failed due to network problems. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible valu...
NPN_SetValue - Archive of obsolete content
tes away from the page containing the plugin, all plugin instances get an NPP_Destroy call, and if there are no more instances of the plugin active, the plugin calls its NP_Shutdown method and the plugin dll gets unloaded from memory. If this is not desired, the plugin can instruct the browser not to unload the dll and not to call NP_Shutdown when the page is left. In such a case all this will be done on the browser shutdown. The plugin calls NPN_SetValue any time with NPPVpluginKeepLibraryInMemory as variable parameter and value set to TRUE. By default, the dll will be unloaded from memory preceded by an NP_Shutdown call. Remarks All four variable values are boolean. Although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boole...
NPN_UTF8FromIdentifier - Archive of obsolete content
tifier. Syntax #include <npruntime.h> NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier); Parameters The function has the following parameter: <tt>identifier</tt> The string identifier whose corresponding string should be returned. Returns A UTF-8 string as a sequence of NPUTF8 bytes, or NULL if the specified <tt>identifier</tt> isn't a string identifier. Description Once the caller is done with the returned string, the caller is responsible for deallocating the memory used by the string by calling NPN_MemFree(). ...
NPP_DestroyStream - Archive of obsolete content
be closed or destroyed. Syntax #include <npapi.h> NPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason); Parameters The function has the following parameters: instance Pointer to current plug-in instance. stream Pointer to current stream. reason Reason the stream was destroyed. Values: NPRES_DONE (Most common): Completed normally; all data was sent to the instance. NPRES_USER_BREAK: User canceled stream directly by clicking the Stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. NPRES_NETWORK_ERR: Stream failed due to problems with network, disk I/O, lack of memory, or other problems. Returns If successful, ...
NPPrintCallbackStruct - Archive of obsolete content
cific information. The NPPrintCallbackStruct structure contains the file pointer to which the plug-in should write its PostScript data. This information is required by the platformPrint field of the NPEmbedPrint structure during embedded mode printing. At the time the plug-in is called, the browser has already opened the file and written PostScript for other parts of the page. When the plug-in is done, it should leave the file open, so the browser can continue to write additional PostScript data to the file. See Also NPP_Print, NPEmbedPrint, NPSetWindowCallbackStruct, NPAnyCallbackStruct ...
Writing a plugin for Mac OS X - Archive of obsolete content
this article, you may wish to grab the sample code located here, as it will be referenced during this tutorial. The sample is posted under a BSD-style license that means you can use it for anything, even if you don't plan to release your source code. Getting started If you check out the Mozilla source code in Mac OS X, you can simply open BasicPlugin.xcodeproj in Xcode, click Build, and you're done. Xcode will create a "build" directory next to the project file, and if you built it in release mode, that folder in turn contains a "Release" directory with the plugin inside it. To install the plugin, just copy it into one of these two locations: /Library/Internet Plugins/ ~/Library/Internet Plugins/ From this point, you can simply modify the sample plugin to do whatever you want. Note...
Syndicating content with RSS - Archive of obsolete content
not required, support of this is recommended, especially for web sites and applications with high performance needs. The HTTP protocol, one of the core technologies behind the web, provides a way of prioritizing the content type that an HTTP client prefers to receive. This technique takes advantage by having the client prefer RSS (over HTML or other formats). ...
What is RSS - Archive of obsolete content
o get the latest ones all the time.". Note: If you provide a non-password-protected RSS feed, you are implicitly giving everyone permission to use the contents in you RSS feed in almost any way they see fit. They can read it. They can make local copies of it. They can share that local copy. They can put it on their website. They can even re-syndicate it. And more. If you don't want any of that done, then don't put it in a non-password-protected RSS feed, and, of course, don't make the password public. News web sites use RSS to provide everyone with a list of their newest articles. For example: <?xml version="1.0"?> <rss version="2.0"> <channel> <title>Example News Site</title> <description>This is an Example News Site.</description> <lastBuildDate>Wed, 27 Jul ...
Building a Theme - Archive of obsolete content
package it for deployment and installation. Zip up the contents of your theme's folder (not the theme folder itself), and rename the zip file to have a .xpi extension. In Windows, you can do this easily by selecting all the files and subfolders in your extension folder, right click and choose "Send To -> Compressed (Zipped) Folder". A .zip file will be created for you. ...
Create Your Own Firefox Background Theme - Archive of obsolete content
JPG or PNG format! Select text and tab colors -- you can choose the tab ("background") color and foreground text color that work best with your header image. Preview your theme -- you're ready to preview your theme! Simply mouse over the image above the Submit Theme button, and see how it looks instantly. Submit your theme -- if everything looks right, click the Submit Theme button, and you're done! You can see all the themes you've authored on your profile page. Tip: to ensure that your theme is approved for the gallery, be sure it complies with the content guidelines and terms of service! Submit Your Theme Now More Tutorials Mozilla Themes Focal Point on Sizing - A tutorial on theming with a focus on sizing, by VanillaOrchids. ...
Theme changes in Firefox 2 - Archive of obsolete content
feeds/subscribe.css This is a new file in Firefox 2. It skins the window displayed to subscribe to an RSS feed, which is at browser/feeds/subscribe.xhtml. ...
Theme changes in Firefox 3 - Archive of obsolete content
rowser/tabDragIndicator.png Removed superfluous blank pixels from the edges, so that the image is smaller. May or may not affect other Mac themes that use it. browser/themes/pinstripe/browser/browser.css .tabbrowser-tab[first-tab="true"] > .tab-image-left no longer has a margin-left. Instead .tabs-left now displayed and given the same width as the former margin-left. It was already done this way in Winstripe. Changes in browser --- Changes in global All platforms The yellow background for the location bar has been deprecated; instead, themes should style the new #identity-box element depending on its verifiedDomain/verifiedIdentity class. The Go button is now located inside the location bar, so the image for it (chrome://browser/skin/Go-arrow.png) needs to be smaller...
Scratchpad - Archive of obsolete content
's "load" event fires. This is useful for running the code in a pristine environment. Running Scratchpad in the browser context You can run Scratchpad in the context of the browser as a whole rather than a specific web page. This is useful if you are working on Firefox itself or developing add-ons. To do this check "Enable chrome and add-on debugging" in the Developer Tool Settings. Once you've done this, the Environment menu has a Browser option; once that's selected, your scope is the entire browser rather than just the page content, as you will see from examining some globals: window /* [object ChromeWindow] */ gBrowser /* [object XULElement] */ The Scratchpad execution context is set to browser when a snippet file has // -sp-context: browser on the first line. Keyboard shortcuts ...
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
ences 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. Download the sample Updating the install manifest The first step is to revise the extension's install manifest to indicate that it can be installed in Thunderbird and Sunbird. ...
Using SSH to connect to CVS - Archive of obsolete content
to the bug. 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 already in your path. Replace pserver with ext in your CVSROOT environment variable. If you wish to keep your previous pserver trees, you'll need to update the Root files in each CVS subdirectory in your tree. This can be done using a unix-style find and perl: find . -name Root -exec perl -p -i -e "s/pserver/ext/" {} \; Dealing with firewalls Do not attempt to perform the steps in this section unless you have first verified that you can access cvs.mozilla.org from outside of the firewall. Only proceed with these steps once you are certain you can access cvs.mozilla.org from the open Internet. If you are behind a f...
Using workers in extensions - Archive of obsolete content
means 'refresh'. this.worker.postMessage(""); }, The onworkermessage() method This method is called when the worker posts a message back to the main thread. Its job is to update the ticker information that's currently displayed in the status bar, as well as to update the tooltip that appears while the mouse cursor is hovering over the ticker. This code is essentially identical to what's done in the previous version, except that it's done in response to an event instead of within the refreshInformation() method. A note about ChromeWorkers Requires Gecko 2.0(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Gecko 2.0 added the new ChromeWorker object, which provides a special chrome-only worker that can be used by applications and extensions. This worker object has access to js-...
Introduction - Archive of obsolete content
/>; var element2 = <bar/>; element1.appendChild(element2); which produces exactly the XML document you'd expect <foo> <bar/> </foo> Javascript Variables The true power of E4X only begins to come to light, however, when the XML document can interact closely with other JavaScript. With special syntax, we can assign the value of a JavaScript variable to be the value of an E4X element. This is done with brace ({}) notation. var a = 2; var b = <foo>{a}</foo>; creates an XML document that reads <foo>2</foo>. You can also use brace notation on attributes of elements (their names or values). For example, var a = 2; var b = 'bar'; var c = <foo {b}={a}>"hi"</foo>; creates a slightly different XML document: <foo bar="2">"hi"</foo>. Note, however, that XML elements can only have text as thei...
Array.observe() - Archive of obsolete content
hange. index: Only for the "splice" type. The index at which the change occurred. removed: Only for the "splice" type. An array of the removed elements. addedCount: Only for the "splice" type. The number of elements added. Description The callback function is called each time a change is made to arr, with an array of all changes in the order in which they occurred. Changes done via Array methods, such as Array.prototype.pop() will be reported as "splice" changes. Index assignment changes which do not change the length of the array may be reported as "update" changes. Examples Logging different change types var arr = ['a', 'b', 'c']; Array.observe(arr, function(changes) { console.log(changes); }); arr[1] = 'B'; // [{type: 'update', object: <arr>, name: '1', oldVa...
VBArray - Archive of obsolete content
he VBArray object provides access to Visual Basic safe arrays. Syntax varName = new VBArray(safeArray) Parameters varName The variable name to which the VBArray is assigned. safeArray A VBArray value. Remarks VBArrays are read-only, and cannot be created directly. The safeArray argument must have obtained a VBArray value before being passed to the VBArray constructor. This can only be done by retrieving the value from an existing ActiveX or other object. VBArrays can have multiple dimensions. The indices of each dimension can be different. The dimensions method retrieves the number of dimensions in the array; the lbound and ubound methods retrieve the range of indices used by each dimension. Example The following example consists of three parts. The first part is VBScript code t...
Examples - Archive of obsolete content
SS and JavaScript in XHTML Documents" article. Please refer to the article to learn more about these examples. If you wish to test these examples by yourself, please read the Important Notes. Important Notes If you plan to test these examples by yourself, you must use the right filename extension (it is written at the beginning of the code). Ideally, upload the file to a web server and you're done. Please note that the examples 4, 5 and 6 require a file named style.css to exist in the same directory as the example. You can get the contents of style.css at the bottom of this page. Examples for "Problems with Inline style and script" Problem 1 <!-- This file should have a .xhtml extension and will generate an error when parsed. --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Stric...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
ing E4X objects is actually quite natural and certainly easier than most methods. JavaScript engines such as Rhino and SpiderMonkey on their own have proven to be a useful and powerful tool to the developer. 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 already been done for you. All you need to do is implement the JavaScript. Let's take a closer look on the SpiderMonkey side with Jaxer. As stated earlier, Aptana Jaxer is built using the Mozilla Browser Engine engine that powers Mozilla Firefox, which includes SpiderMonkey as its JavaScript interpreter, but lots more features beyond SSJS alone such as DOM, DB, File IO, CSS, server session...
Standards-Compliant Authoring Tools - Archive of obsolete content
Creating cross-browser code upfront will save you lots of time quality testing your web content. The following authoring tools adhere to the W3 standards. If you're using older versions of tools that rely on old browser bugs or generate browser-specific code, it may be time to upgrade: NVu is a standalone editor created from the remains of Mozilla Composer. Currently the work done on NVu is being ported back to mozilla source code. HTML-Kit is a full-featured, low priced editor designed to help HTML, XHTML and XML authors to edit, format, lookup help, validate, preview and publish web pages. Validation is done with HTML Tidy, so you can verify standards compliance. Macromedia(TM) Dreamweaver(TM) CS6 Style Master and Layout Master by Western Civilisation Some caveats: It appears...
Building Mozilla XForms - Archive of obsolete content
During CVS times, the Mozilla repository contained both extensions. Since the switch to Mercurial, the extensions live in separate repositories. Before you can start building the xforms extension, you should check your Mozilla build environment by doing a regular Firefox build. Have a look at the Build Instructions for detailed information for your platform. ...
XForms - Archive of obsolete content
ication. XForms Tutorial and Cookbook XForms in Wikibook Format - Over 50 examples tested with Firefox. XForms support can be added to Firefox and SeaMonkey by installing the Mozilla XForms extension. This extension, while supporting a significant subset of the XForms 1.0 and 1.1 candidate recommendations, is not actively maintained any more since about 2010. The last official release has been done for Firefox 3.6 and is available for download on addons.mozilla.org. For more details about the future of the Mozilla XForms extension see this blog post. Documentation Implementation status Implementation status of the Mozilla XForms extension Building Get started with building your own XForms extensions from source. Troubleshooting tips for XForms...
Styling Abbreviations and Acronyms - Archive of obsolete content
The underline tells readers that the word in question has extra information associated with it. In Mozilla, placing the mouse pointer over the element and leaving it for a moment will cause the contents of the title attribute ...
The Business Benefits of Web Standards - Archive of obsolete content
slightly differently). Using valid, standards-compliant markup ensures that data will still be re-usable for a long time, as specifications on how to parse the standard formats are well documented and here to stay. Contrary to popular belief, coding to standards does not mean producing less compelling content. As a matter of fact, almost anything taking advantage of proprietary extensions can be done in a standards-compliant way, with the added benefit of being cross-platform and future-proof. By ensuring that all of the digital content owned by the operator is marked up in a consistent and standards compliant way, the content base becomes a perennially reusable asset without any additional costs in the future. Extensibility Using strict HTML and separating structure from content paves the...
Web Standards - Archive of obsolete content
unity View Mozilla forums... Mailing list Newsgroup RSS feed The Web Standards Project WebDev FeedHouse Other community links... Tools Firebug extension Web Developer extension Markup validation service (W3C) CSS validation service (W3C) Examples Mozilla 1.0 Demos - showing off what can be done with Web standards. Gecko Demos css Zen Garden Eric Meyers's css/edge W3C DOM Demos Related Topics CSS, DHTML, HTML, Web Development, XHTML, XML The Web Standards Project ...
Windows Media in Netscape - Archive of obsolete content
JavaScript will dynamically write out what browser you are running, and what kind of Windows Media Player technology you may have. Example 1: Client-side Detection Scripts Browser architecture supports: NetscapePlugin Windows Media Player Installed: true Windows Media Scriptable: false Windows Media Version: PluginVersion A complete source code listing showing how that detection was done can be found here (devedge-temp). Below, some of the salient points are illustrated in a code snippet: if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1) { // IE for Windows object instantiation -- use of ActiveXObject } else if(window.GeckoActiveXObject) { // Netscape 7.1 object instantiation --use of GeckoActiveXObject } else if(navigator.mimeTypes) { // Plugin arch...
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
leverage some of these ideas to help you make your Netscape Communicator 4.x plugins exposed to JavaScript in Mozilla based browsers. In order to make it still possible to script plugins, some changes have been made to the Mozilla code. The changes allow to make existing 4.x plugins scriptable with only minor modifications in their code. The present document describes the steps of what should be done to the plugin code to turn it scriptable again. What's in the Mozilla code? A couple of lines have been added to the DOM code asking a plugin to return a scriptable iid and a pointer to a scriptable instance object. The old Plugin API call NPP_GetValue is used to retrieve this information from the plugin. So the plugin project should be aware of two new additions to NPPVariable enumeration type w...
XUL Parser in Python - Archive of obsolete content
code for the XUL parser is available. It only runs as a hard-coded script right now, so if you want to use it you have to go in and changes some of the stuff like CHROME_DIR and which information you want out. It also, I'm afraid, only works on the win32 platform, where the <tt>dir</tt> command it depends on gets you your XUL files. Again, you can easily use <tt>ls</tt> instead, as I should have done, and pick up some extra support. I will make these adjustments and change it into a real module when I get a second, so that someone can instantiate the parser from their own scripts and use it more flexibly: >>> import XULTool >>> myXP = XULParser() >>> CHROME_DIR = 'D:\src\mozilla\xpfe' >>> res = myXP.parseXUL(CHROME_DIR, 'window', 'id') Where something like the above would write out all the...
Examples - Game development
The first two sections list playable games, while the second is a catch-all area to list demos that aren't necessarily interactive/games. Free/demo games Beloola WebVR platform to connect passionate people. Experience both available on 2D screens and on VR HMDs (Settings / Switch to VR mode). Tanx A multiplayer tank battle game, created with PlayCanvas. Hyper Vanguard Force A neat vertically scrolling space shooter. ...
Introduction to game development for the Web - Game development
creating stunning, high quality games, but also for distributing those games. The range of games that can be created is on par with desktop and native OS counterparts. With modern Web technologies and a recent browser, it's entirely possible to make stunning, top-notch games for the Web. And we're not talking about simple card games or multi-player social games that have in the olden days been done using Flash(R). We're talking about kick-ass 3D action shooters, RPGs, and more. Thanks to massive performance improvements in JavaScript just-in-time compiler technology and new APIs, you can build games that run in the browser (or on HTML5-powered devices) without making compromises. The HTML5 game platform You can truly think of the Web as a better target platform for your game. As we like t...
Bounding volume collision detection with THREE.js - Game development
rotation, scale, etc. we need to call the update() method so the BoxHelper instance matches its linked Mesh. We also need to call setFromObject again in order to make the Box3 follow the Mesh. knot.position.set(-3, 2, 1); knot.rotation.x = -Math.PI / 4; // update the bounding box so it stills wraps the knot knotBoxHelper.update(); box3.setFromObject(knotBoxHelper); Performing collision tests is done in the same way as explained in the above section -- we use our Box3 object in the same way as described above. // box vs box box3.intersectsBox(otherBox3); // box vs point box3.containsPoint(point.position); Demos There are two demos you can take a look at on our live demos page. The first one showcases point vs. box collisions using BoxHelper. The second one performs box vs. box tests. ...
Building up a basic demo with A-Frame - Game development
l to the scene to make them visible on the screen. In A-Frame, the scene is reperesented by a Scene entity. Note: An Entity is any element -- it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. Let's create the scene by adding an <a-scene> element inside the <body> element: <a-scene> </a-scene> Adding a cube Adding the cube to the scene is done by adding a simple <a-box> element inside the <a-scene> element. Add it now: <a-box color="#0095DD" position="0 1 0" rotation="20 40 0"> </a-box> It contains a few parameters already 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. Note: The distance values (e.g. for...
Building up a basic demo with Babylon.js - Game development
can be seen better. Now let's add a material: var torusMaterial = new BABYLON.StandardMaterial("material", scene); torusMaterial.emissiveColor = new BABYLON.Color3(0.4, 0.4, 0.4); torus.material = torusMaterial; It looks similar to the box element -- we're creating the standard material, giving it a grayish color and assigning it to the torus. Cylinder Creating a cylinder and its material is done in almost exacly the same way as we did for the torus. Add the following code, again at the bottom of your script: var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", 2, 2, 2, 12, 1, scene); cylinder.position.x = 5; cylinder.rotation.x = -0.2; var cylinderMaterial = new BABYLON.StandardMaterial("material", scene); cylinderMaterial.emissiveColor = new BABYLON.Color3(1, 0.58, 0); cylinder.mater...
Building up a basic demo with the PlayCanvas engine - Game development
he x axis to show it's actually a 3D shape. To make the cylinder have a color, let's say yellow, we need to create the material for it, as before. Add the following lines: var cylinderMaterial = new pc.PhongMaterial(); cylinderMaterial.diffuse.set(1, 0.58, 0); cylinderMaterial.update(); cylinder.model.model.meshInstances[0].material = cylinderMaterial; Cone Creating a cone and its material is done in almost exacly the same way as we did for the cylinder. Add the following code, again, at the bottom of your script: var cone = new pc.Entity(); cone.addComponent("model", { type: "cone" }); app.root.addChild(cone); cone.translate(2, 0, 0); var coneMaterial = new pc.PhongMaterial(); coneMaterial.diffuse.set(0.9, 0.9, 0.9); coneMaterial.update(); cone.model.model.meshInstances[0].material = co...
WebVR — Virtual Reality for the Web - Game development
For example: function setCustomFOV(up,right,down,left) { var testFOV = new VRFieldOfView(up,right,down,left); gHMD.setFieldOfView(testFOV,testFOV,0.01,10000.0); } The gPositionSensor variable holds the PositionSensorVRDevice -- usin...
Desktop gamepad controls - Game development
else if(GamepadAPI.axes.status[1] < -0.5) { // move player right } } They can now move the ship on the screen by using the DPad buttons, or the left stick axes. Have you noticed that the current value of the axes is evaluated against 0.5? It's because axes are having floating point values while buttons are booleans. After a certain threshold is reached we can assume the input is done deliberately by the user and can act accordingly. For the shooting controls, we used the A button -- when it is held down, a new bullet is spawned, and everything else is handled by the game: if(GamepadAPI.buttons.pressed('A','hold')) { this.spawnBullet(); } Showing the screen with all the controls looks exactly the same as in the main menu: if(GamepadAPI.buttons.pressed('Y','hold')) { ...
Mobile touch controls - Game development
ch in their game development process -- in the modern world, this generally also involves implementing touch controls. In this tutorial, we will see how easy it is to implement mobile controls in an HTML5 game, and enjoy playing on a mobile touch-enabled device. Note: The game Captain Rogers: Battle at Andromeda is built with Phaser and managing the controls is Phaser-based, but it could also be done in pure JavaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's entirely up to you which approach you to choose. Pure JavaScript approach We could implement touch events on our own -- setting up event listeners and assigning relevant functions to them would be quite straightforward: var el = document.getElements...
Unconventional controls - Game development
trol mechanisms in your game helps reach broader audiences. Implementing mobile and desktop controls is recommended is a must, and gamepad controls add that extra experience. But imagine going even further -- in this article we will explore various unconventional ways to control your web game, some more unconventional than others. TV remote Playing games on a TV screen doesn't always have to be done through consoles. There's already a Gamepad API working on the desktop computers, so we can imitate the experience, but we can go even further. Modern smart TVs can handle HTML5 games, because they have a built-in browser that can be used as a gaming platform. Smart TVs are shipped with remote controls, which can be used to control your games if you know how. The earliest demo of Captain Rogers:...
Square tilemaps implementation: Scrolling maps - Game development
the Canvas API. Note: When writing this article, we assumed previous reader knowledge of canvas basics such as how get a 2D canvas context, load images, etc., which is all explained in the Canvas API tutorial, as well as the basic information included in our Tilemaps introduction article. This article also builds upon implementing static square tilemaps -- you should read that too if you've not done so already. The camera The camera is an object that holds information about which section of the game world or level is currently being shown. Cameras can either be free-form, controlled by the player (such as in strategy games) or follow an object (such as the main character in platform games.) Regardless of the type of camera, we would always need information regarding its current position,...
Create the Canvas and draw on it - Game development
<< PreviousNext >> This is the 1st step out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson1.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML and the <canvas> element. The game's HTML The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element. Using your favourite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Gamedev Canvas Workshop</title> <style> * { padding: 0; margin: ...
Buttons - Game development
the same way we loaded the ball's wobble animation. Add the following to the bottom of the preload() function: game.load.spritesheet('button', 'img/button.png', 120, 40); A single button frame is 120 pixels wide and 40 pixels high. You also need to grab the button spritesheet from Github, and save it in your /img directory. Adding the button to the game Adding the new button to the game is done by using the add.button method. Add the following lines to the bottom of your create() function: startButton = game.add.button(game.world.width*0.5, game.world.height*0.5, 'button', startGame, this, 1, 0, 2); startButton.anchor.set(0.5); The button() method's parameters are as follows: The button's x and y coordinates The name of the graphic asset to be displayed for the button A callback...
Initialize the framework - Game development
<< PreviousNext >> This is the first of 16 tutorials to learn how to use Gamedev Phaser. After completing this tutorial you can find the source code for this section at Gamedev-Phaser-Content-Kit/demos/lesson01.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML -- the Phaser framework will generate the required <canvas> element. The game's HTML The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element generated by the framework. Using your favourite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it: <!DOCTYPE html> <html> <head> <meta charset="utf-8"...
Player paddle and controls - Game development
cordingly to the input's x position, however when we start the game, the position of the paddle is not in the middle. It's because the input position is not yet defined. To fix that we can set the default position (if an input position is not yet defined) to be the middle of the screen. Update the previous line as follows: paddle.x = game.input.x || game.world.width*0.5; If you haven't already done so, reload your index.html and try it out! Position the ball We have the paddle working as expected, so let's position the ball on it. It's very similar to positioning the paddle -- we need to have it placed in the middle of the screen horizontally and at the bottom vertically with a little offset from the bottom. To place it exactly as we want it we will set the anchor to the exact middle of t...
The score - Game development
tual text that will be rendered. The font style to render the text with. The last parameter looks very similar to CSS styling. In our case the score text will be blue, sized at 18 pixels, and use the Arial font. Updating the score when bricks are destroyed We will increase the number of points every time the ball hits a brick and update the scoreText to display the current score. This can be done using the setText() method -- add the two new lines seen below to the ballHitBrick() function: function ballHitBrick(ball, brick) { brick.kill(); score += 10; scoreText.setText('Points: '+score); } That's it for now -- reload your index.html and check that the score updates on every brick hit. Compare your code You can check the finished code for this lesson in the live demo belo...
Visual-js game engine - Game development
This is JavaScript game engine (server part node.js / client part js) Js framework with windows GUI editor and game instance creator. ( + server engine tools + server part of web apps ) -3D PART : webgl based on three.js engine -3D PART : webGL2 based on glmatrix 2.0 -2D PART (new): This is TypeScript based game engine (client part ts). With strong connection with webpack Physics done with (matter.js) matter ts This part is removed from this project. New link is : https://github.com/zlatnaspirala/visual-ts-game-engine Basic licence rules : 1) Each file in this project has its own license , be careful , do not violate the basic rules. 2) You are free to use any version of Visual JS library in any other project (even commercial projects) as long as the copyright heade...
Visual JS GE - Game development
use. If you use editor.js to visually create game objects, you must start the build_from_editor_to_visual_js_file.js when you have finished. This tool will create visual.js in the starter/ directory along with all your game objects. It takes data from the system folder lib/visual_scripts/ and generates your code. RESOURCE JS objects Used for adding images for animation purposes. This is done using server_instance/res.js. You need to put your images in a folder, for example TEST_RES/ , inside project_instance/res/. Next, run the command server_instance/node res.js. After this has finished processing, restart the web page by entering the following in the console: RESOURCE.TEST_RES. RESOURCE objects contain the path data for all your images. The actual image objects will be created...
Plug-in Development Overview - Gecko Plugin API Reference
nderbird 10.0 / SeaMonkey 2.7), you can get the origin of the document in a secure, convenient way by calling NPN_GetValue() to retrieve the value of the variable NPNVdocumentOrigin. The returned value is the Unicode serialization of the document's origin converted to NFKC-encoded (that is, normalized) UTF-8. Your plug-in must free the returned string's memory by calling NPN_MemFree() when you're done with it. Getting Version and UI Information The Netscape group of Plug-in API methods provides some basic services to the plug-in. You can use these Netscape methods: To identify the browser in which your plug-in is displayed: Use the NPN_UserAgent method to read this information. To determine whether plug-in and the browser versions are compatible and possibly provide alternative processin...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
amic webpages using a technology known as XMLHttpRequest. Ajax allows you to update parts of the DOM of an HTML page instead without the need for a full page refresh. Ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). With interactive websites and modern web standards, Ajax is gradually being replaced by functions within JavaScript frameworks and the official Fetch API Standard. ...
Accessibility tree (AOM) - MDN Web Docs Glossary: Definitions of Web-related terms
...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
vailable rather than immediately. Software design Asynchronous software design expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to complete. When the secondary task is completed, the original task is notified using an agreed-upon mechanism so that it knows the work is done, and that the result, if any, is available. There are a number of programming techniques for implementing asynchronous software. See the article Asynchronous JavaScript for an introduction to them. Learn more Technical reference Fetching data from the server (Learning Area) Synchronous ...
Breadcrumb - MDN Web Docs Glossary: Definitions of Web-related terms
rchy of the current page in relation to the the site's structure, from top level to current page, or a list of the links the user followed to get to the current page, in the order visited. A location breadcrumb for this document might look something like this: MDN > Glossary > Breadcrumb Breadcrumb trails enable users to be aware of their location within a website. This type of navigation, if done correctly, helps users know where they are in a site and how they got there. They can also help a user get back to where they were before and can reduce the number of clicks needed to get to a higher-level page. ...
CSRF - MDN Web Docs Glossary: Definitions of Web-related terms
CSRF (Cross-Site Request Forgery) is an attack that impersonates a trusted user and sends a website unwanted commands. This can be done, for example, by including malicious parameters in a URL behind a link that purports to go somewhere else: <img src="https://www.example.com/index.php?action=delete&id=123"> For users who have modification permissions on https://www.example.com, the <img> element executes action on https://www.example.com without their noticing, even if the element is not at https://www.example.com. There are many ways to prevent CSRF, such as implementing RESTful API, adding secure tokens, etc. Learn more General knowledge Cross-site request forgery on Wikipedia Prevention measures ...
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
packaging it in a binary format. ...
Dynamic programming language - MDN Web Docs Glossary: Definitions of Web-related terms
For example, in JavaScript it is possible to change the type of a variable or add new properties or methods to an object while the program is running. This is opposed to so-called static programming languages, in which such changes are normally not possible. Note that while there is indeed a connection between this dynamic/static property of programming languages and dynamic/static-typing, the two are far from synonymous. ...
HTML - MDN Web Docs Glossary: Definitions of Web-related terms
ear through a markup mainly based on SGML. The IETF began formally specifying HTML in 1993, and after several drafts released version 2.0 in 1995. In 1994 Berners-Lee founded the W3C to develop the Web. In 1996, the W3C took over the HTML work and published the HTML 3.2 recommendation a year later. HTML 4.0 was released in 1999 and became an ISO standard in 2000. At that time, the W3C nearly abandoned HTML in favor of XHTML, prompting the founding of an independent group called WHATWG in 2004. Thanks to WHATWG, work on HTML5 continued: the two organizations released the first draft in 2008 and the final standard in 2014. Concept and syntax An HTML document is a plaintext document structured with elements. Elements are surrounded by matching opening and closing tags. Each tag begins and ends...
HTTP - MDN Web Docs Glossary: Definitions of Web-related terms
d HTTP/2. As part of a URI, the "http" within "http://example.com/" is called a "scheme". Resources using the "http" schema are typically transported over unencrypted connections using the HTTP protocol. The "https" scheme (as in "https://developer.mozilla.org") indicates that a resource is transported using the HTTP protocol, but over a secure TLS channel. HTTP is textual (all communication is done in plain text) and stateless (no communication is aware of previous communications). This property makes it ideal for humans to read documents (web sites) on the world wide web. However, HTTP can also be used as a basis for REST web services from server to server or AJAX requests within web sites to make them more dynamic. Learn more HTTP on MDN HTTP on Wikipedia ...
Hotlink - MDN Web Docs Glossary: Definitions of Web-related terms
...
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
locks rendering, and pauses parsing of HTML. When the browser encounters CSS styles, it parses the text into the CSS Object Model (or CSSOM), a data structure it then uses for styling layouts and painting. The browser then creates a render tree from both these structures to be able to paint the content to the screen. JavaScript is also downloaded, parsed, and then execute. JavaScript parsing is done during compile time or whenever the parser is invoked, such as during a call to a method. Learn more General knowledge Parse on Wikipedia ...
Perceived performance - MDN Web Docs Glossary: Definitions of Web-related terms
es on human perception, not an objective metric like time to interactive. In terms of web performance, perceived performance is how fast a user interaction feels rather than how fast an interaction actually is, be that a button press or a page load. Perceived performance is not how fast your site is; it's how fast your users think it is. Perceived performance is not measured by when your site is done loading but when it has loaded enough for users to believe it has loaded and is interactive. In terms of conversion rates, perceived performance is more important than the actual load and response times. Speed Index is a common metric for measuring perceived performance, though it's not perfect. Other features, such as good UX design, including animations, and lazy loading, can make your site ap...
Public-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
One key (the private key) is kept secret while the other is made public. When used for digital signatures, the private key is used to sign and the public key to verify. This means that anyone can verify a signature, but only the owner of the corresponding private key could have generated it. When used for encryption, the public key is used to encrypt and the private key is used to decrypt. ...
Screen reader - MDN Web Docs Glossary: Definitions of Web-related terms
is to do the same. ...
Texel - MDN Web Docs Glossary: Definitions of Web-related terms
one of the main differences between Texel's and pixels, pixels are image data. Texel components are made up of subjective data, therefore they can be an image as well as a depth map. The process of mapping the appropriate Texel's to their corresponding points on a polygon is called texture mapping, which is a stage of the process of rendering a 3D image for display. Texture mapping is typically done prior to lighting the scene; however, in WebGL, lighting is performed as part of the texture mapping process. Textures are characterised by collections of Texel's, as how images are characterised by collections of pixels. When texture mapping occurs the renderer maps Texel's to the appropriate pixels. Learn more General knowledge Texel (graphics) on Wikipedia Learn about it Using textu...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite loop, the entire browser will hang. This results in a frustrating, sluggish (or worse) user experience. However, modern JavaScript offers ways to create additional threads, each executing independently while possibly communicating between one another. This is done using technologies such as web workers, which can be used to spin off a sub-program which runs concurrently with the main thread in a thread of its own. This allows slow, complex, or long-running tasks to be executed independently of the main thread, preserving the overall performance of the site or app--as well as that of the browser overall. This also allows individuals to take advantage of mod...
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
d responses on the same URI. For example, a PUT to pageX.html will invalidate all cached GET or HEAD requests to the same URI. ...
HTML: A good basis for accessibility - Learn web development
</tr> <tr> <td>Elva</td> <td>8</td> <td>Female</td> </tr> <tr> <td>Freida</td> <td>5</td> <td>Female</td> </tr> </table> But this has problems -- there is no way for a screen reader user to associate rows or columns together as groupings of data. To do this, you need to know what the header rows are and if they are heading up rows, columns, etc. This can only be done visually for the above table (see bad-table.html and try the example out yourself). Now have a look at our punk bands table example -- you can see a few accessibility aids at work here: Table headers are defined using <th> elements -- you can also specify if they are headers for rows or columns using the scope attribute. This gives you complete groups of data that can be consumed by screen re...
HTML: A good basis for accessibility - Learn web development
</tr> <tr> <td>Elva</td> <td>8</td> <td>Female</td> </tr> <tr> <td>Freida</td> <td>5</td> <td>Female</td> </tr> </table> But this has problems -- there is no way for a screen reader user to associate rows or columns together as groupings of data. To do this, you need to know what the header rows are and if they are heading up rows, columns, etc. This can only be done visually for the above table (see bad-table.html and try the example out yourself). Now have a look at our punk bands table example -- you can see a few accessibility aids at work here: Table headers are defined using <th> elements -- you can also specify if they are headers for rows or columns using the scope attribute. This gives you complete groups of data that can be consumed by screen re...
Advanced styling effects - Learn web development
Other box shadow features Unlike text-shadow, box-shadow has an inset keyword available -- putting this at the start of a shadow declaration causes it to become an inner shadow, rather than ...
Cascade and inheritance - Learn web development
styles, as mentioned above -- this can be achieved by using !important in their rules. Test your skills! We have covered a lot in this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on -- see Test your skills: the Cascade. What's next If you understood most of this article, then well done -- you've started getting familiar with the fundamental mechanics of CSS. Next up, we'll look at selectors in detail. If you didn't fully understand the cascade, specificity, and inheritance, then don't worry! This is definitely the most complicated thing we've covered so far in the course, and is something that even professional web developers sometimes find tricky. We'd advise that you return ...
Debugging CSS - Learn web development
the person helping you what you have already tried. This may well give you enough information to be able to search for likely sounding problems and workarounds. If you are still struggling to fix the problem then having a reduced test case gives you something to ask for help with, by posting to a forum, or showing to a co-worker. You are much more likely to get help if you can show that you have done the work of reducing the problem and identifying exactly where it happens, before asking for help. A more experienced developer might be able to quickly spot the problem and point you in the right direction, and even if not, your reduced test case will enable them to have a quick look and hopefully be able to offer at least some help. In the instance that your problem is actually a bug in a brow...
Attribute selectors - Learn web development
ause the other two list items start with an uppercase A. The second selector uses the case-insensitive flag and so matches all of the list items. Note: There is also a newer value s, which will force case-sensitive matching in contexts where matching is normally case-insensitive, however this is less well supported in browsers and isn't very useful in an HTML context. Next steps Now we are done with attribute selectors, you can continue on to the next article and read about pseudo-class and pseudo-element selectors. Previous Overview: Building blocks Next In this module Cascade and inheritance CSS selectors Type, class, and ID selectors Attribute selectors Pseudo-classes and pseudo-elements Combinators The box model Backgrounds and borders Handling d...
Flexbox - Learn web development
the moment you'll see a horizontal menu bar, with some buttons jammed into the top left hand corner. First, take a local copy of this example. Now, add the following to the bottom of the example's CSS: div { display: flex; align-items: center; justify-content: space-around; } Refresh the page and you'll see that the buttons are now nicely centered, horizontally and vertically. We've done this via two new properties. align-items controls where the flex items sit on the cross axis. By default, the value is stretch, which stretches all flex items to fill the parent in the direction of the cross axis. If the parent hasn't got a fixed width in the cross axis direction, then all flex items will become as long as the longest flex items. This is how our first example got equal height...
Practical positioning examples - Learn web development
</li> </ul> <div class="panels"> <article class="active-panel"> <h2>The first tab</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque turpis nibh, porttitor nec venenatis eu, pulvinar in augue. Vestibulum et orci scelerisque, vulputate tellus quis, lobortis dui. Vivamus varius libero at ipsum mattis efficitur ut nec nisl. Nullam eget tincidunt metus. Donec ultrices, urna maximus consequat aliquet, dui neque eleifend lorem, a auctor libero turpis at sem. Aliquam ut porttitor urna. Nulla facilisi.</p> </article> <article> <h2>The second tab</h2> <p>This tab hasn't got any Lorem Ipsum in it. But the content isn't very exciting all the same.</p> </article> <article> <h2>The third tab</h2> <p>Lorem ipsum dolor ...
Getting started with CSS - Learn web development
because browsers have internal stylesheets containing default styles, which they apply to all pages by default; without them all of the text would run together in a clump and we would have to style everything from scratch. All modern browsers display HTML content by default in pretty much the same way. However, you will often want something other than the choice the browser has made. This can be done by simply choosing the HTML element that you want to change, and using a CSS rule to change the way it looks. A good example is our <ul>, an unordered list. It has list bullets, and if I decide I don't want those bullets I can remove them like so: li { list-style-type: none; } Try adding this to your CSS now. The list-style-type property is a good property to look at on MDN to see which val...
create fancy boxes - Learn web development
o the practical side of it, make sure you are familiar with the CSS box model. It's also a good idea, but not a prerequisite, to be familiar with some CSS layout basics. On the technical side, Creating fancy boxes are all about mastering CSS border and background properties and how to apply them to a given box. But beyond the technics its also all about unleashing your creativity. It will not be done in one day, and some web developers spend their whole life having fun with it. We are about to see many examples, but we will always work on the most simple piece of HTML possible, a simple element: <div class="fancy">Hi! I want to be fancy.</div> Ok, that's a very small bit of HTML, what can we tweak on that element? All of the following: Its box model properties: width, height, padding, b...
Styling lists - Learn web development
Backgrounds and borders article. For now, here's a taster! In our finished example, we have styled the unordered list like so (on top of what you've already 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. This is so that overall the list items are still lined up with the order list items and the description list descriptions, but the list items have some padding for the background images to sit inside. If we didn't do this, the background images would overlap with the ...
Typesetting a community school homepage - Learn web development
rther help section at the bottom of this page. Project brief You have been provided with some raw HTML for the homepage of an imaginary community college, plus some CSS that styles the page into a three column layout and provides some other rudimentary styling. You are to write your CSS additions below the comment at the bottom of the CSS file, to make sure it is easy to mark the bits you have done. Don't worry if some of the selectors are repetitious; we'll let you off in this instance. Fonts: First of all, download a couple of free-to-use fonts. Because this is a college, the fonts should be chosen to give the page a fairly serious, formal, trustworthy feel -- a serif site-wide font for the general text body, coupled with sans-serif or slab serif for the headings might be nice. Use a...
Learn to style HTML using CSS - Learn web development
ou'll primarily apply colors to HTML elements and their backgrounds; change the size, shape, and position of elements; and add and define borders on elements. But there's not much you can't do once you have a solid understanding of even the basics of CSS. One of the best things about learning CSS is that once you know the fundamentals, usually you have a pretty good feel for what can and can't be done, even if you don't actually know how to do it yet! "CSS is weird" CSS works a bit differently to most programming languages and design tools you'll come across. Why does it work the way it does? In the following video, Miriam Suzanne provides a useful explanation of why CSS works like it does, and why it has evolved like it has: ...
What text editors are available? - Learn web development
more useful to your purposes. Dig deeper Choice criteria So, in more detail, what should you be thinking about when you choose a text editor? Which OS (operating system) do I want to work with? Of course it's your choice. However, some editors are only available for certain OSs, so if you like switching back and forth, that would narrow down the possibilities. Any text editor can get the job done, if it runs on your system, but a cross-platform editor eases migration from OS to OS. So first find out which OS you're using, and then check if a given editor supports your OS. Most editors specify on their website whether they support Windows or Mac, though some editors only support certain versions (say, only Windows 7 or later and not Vista). If you're running Ubuntu, your best bet is to se...
How can we design for all types of users? - Learn web development
t cases this will render as 16 pixels */ h1 { font-size:2em; } /* twice the size of the body, thus 32 pixels */ span.subheading { font-size:0.5em; } /* half the size of the h1, thus 16 pixels to come back to the original size */ As you can see, the math quickly gets daunting when you have to keep track of the parent, the parent's parent, the parent's parent's parent, and so on. (Most designs are done in pixel-based software, so the math has to be done by the person coding the CSS). Enter rem. This unit is relative to the root element's size and not to any other parent. The CSS can be rewritten thus: body { font-size:1em; } /* 1em = 100% of the browser's base font size, so in most cases this will render as 16 pixels */ h1 { font-size:2rem; } /* twice the size of the body, thus 32 pixels */ s...
How do you set up a local testing server? - Learn web development
local testing server on your machine, and the basics of how to use it. Prerequisites: You need to first know how the Internet works, and what a Web server is. Objective: You will learn how to set up a local testing server. Local files vs. remote files Throughout most of the learning area, we tell you to just open your examples directly in a browser -- this can be done by double clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open... and navigating to the HTML file. There are many ways to achieve this. If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some o...
The HTML5 input types - Learn web development
s type attribute set to the value range. The slider-thumb can be moved via mouse or touch, or with the arrows of the keypad. It's important to properly configure your slider. To that end, it's highly recommended that you set the min, max, and step attributes which set the minimum, maximum and increment values, respectively. Let's look at the code behind the above example, so you can see how its done. First of all, the basic HTML: <label for="price">Choose a maximum house price: </label> <input type="range" name="price" id="price" min="50000" max="500000" step="100" value="250000"> <output class="price-output" for="price"></output> This example creates a slider whose value may range between 50000 and 500000, which increments/decrements by 100 at a time. We've given it default value of 25000...
HTML forms in legacy browsers - Learn web development
Unobtrusive JavaScript One of the biggest problems is the availability of APIs. For that reason, it's considered best practice to work with "unobtrusive" JavaScript. It's a development pattern that defines two requirements: A strict separation between structure and behaviors. If the code breaks, the content and the basic ...
How to structure a web form - Learn web development
ould nest a widget and its labels inside a single <label> element. ...
CSS property compatibility table for form controls - Learn web development
How to read the tables Values For each property, there are four possible values: Yes There's reasonably consistent support for the property across browsers. You may still face strange side effects in certain edge cases. ...
Sending form data - Learn web development
ction set to {{ url_for('hello') }}. This is a Jinja2 template, which is basically HTML but can contain calls to the Python code that is running the web server contained in curly braces. url_for('hello') is basically saying "redirect to /hello when the form is submitted". greeting.html: This template just contains a line that renders the two bits of data passed to it when it is rendered. This is done via the hello() function seen above, which runs when the /hello URL is navigated to. Note: Again, this code won't work if you just try to load it into a browser directly. Python works a bit differently to PHP -- to run this code locally you'll need to install Python/PIP, then install Flask using pip3 install flask. At this point you should be able to run the example using python3 python-exampl...
Styling web forms - Learn web development
icle Advanced form styling. The ugly Some elements can't be styled thoroughly using CSS. These include: <input type="color"> Date-related controls such as <input type="datetime-local"> <input type="range"> <input type="file"> Elements involved in creating dropdown widgets, including <select>, <option>, <optgroup> and <datalist>. <progress> and <meter> Again, we'll describe what can be done in terms of styling these elements in Advanced form styling. The real problem with all these controls is that they have a very complex structure, and beyond some basic styling (such as changing the width or margin of the control) you generally don't have the ability to style the controls' internal components (such as the date picker calendar, or the button on the <select> that causes the options...
UI pseudo-classes - Learn web development
e will explore in detail the different UI pseudo-classes available to us in modern browsers for styling forms in different states. Prerequisites: Basic computer literacy, and a basic understanding of HTML and CSS, including general knowledge of pseudo-classes and pseudo-elements. Objective: To understand what parts of forms are hard to style, and why; to learn what can be done to customize them. What pseudo-classes do we have available? The original pseudo-classes available to us (as of CSS 2.1) that are relevant to forms are: :hover: Selects an element only when it is being hovered over by a mouse pointer. :focus: Selects an element only when it is focused (i.e. by being tabbed to via the keyboard). :active: selects an element only when it is being activa...
Your first form - Learn web development
want to define a default value for a <textarea>, you put it between the opening and closing tags of the <textarea> element, like this: <textarea> by default this element is filled with this text </textarea> The <button> element The markup for our form is almost complete; we just need to add a button to allow the user to send, or "submit", their data once they have filled out the form. This is done by using the <button> element; add the following just above the closing </ul> tag: <li class="button"> <button type="submit">Send your message</button> </li> The <button> element also accepts a type attribute -- this accepts one of three values: submit, reset, or button. A click on a submit button (the default value) sends the form's data to the web page defined by the action attribute of ...
Dealing with files - Learn web development
an combine these as much as you like, for example ../subdirectory/another-subdirectory/my-image.jpg. For now, this is about all you need to know. Note: The Windows file system tends to use backslashes, not forward slashes, e.g. C:\windows. This doesn't matter in HTML -- even if you are developing your website on Windows, you should still use forward slashes in your code. What else should be done? That is about it for now. Your folder structure should look something like this: Previous Overview: Getting started with the web Next In this module Installing basic software What will your website look like? Dealing with files HTML basics CSS basics JavaScript basics Publishing your website How the web works ...
HTML basics - Learn web development
the https:// or http:// part, called the protocol, at the beginning of the web address. After making a link, click it to make sure it is sending you where you wanted it to. href might appear like a rather obscure choice for an attribute name at first. If you are having trouble remembering it, remember that it stands for hypertext reference. Add a link to your page now, if you haven't already done so. Conclusion If you have followed all the instructions in this article, you should end up with a page that looks like the one below (you can also view it here): If you get stuck, you can always compare your work with our finished example code on GitHub. Here, we have only really scratched the surface of HTML. To find out more, go to our Learning HTML topic. Previous Overview: Gett...
Add a hitmap on top of an image - Learn web development
ible link text. You may write alt="" if the href attribute is blank and the entire image already has an alt attribute. <map name="example-map-1"> <area shape="circle" coords="200,250,25" href="page-2.html" alt="circle example" /> <area shape="rect" coords="10, 5, 20, 15" href="page-3.html" alt="rectangle example" /> </map> Step 3: Make sure it works for everybody You aren't done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off. If your image map is wider than about 240px, you'll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image. If you must use im...
Tips for authoring fast-loading HTML pages - Learn web development
er. It allows for efficient page caching; by means of this header, information is conveyed to the user agent about the file it wants to load, such as when it was last modified. Most web servers automatically append the Last-Modified header to static pages (e.g. .html, .css), based on the last-modified date stored in the file system. With dynamic pages (e.g. .php, .aspx), this, of course, can't be done, and the header is not sent. So, in particular, for pages which are generated dynamically, a little research on this subject is beneficial. It can be somewhat involved, but it will save a lot in page requests on pages which would normally not be cacheable. More information: HTTP Conditional Get for RSS Hackers HTTP 304: Not Modified HTTP ETag on Wikipedia Caching in HTTP Optimally order...
Use JavaScript within a webpage - Learn web development
-party scripts (ads, tracking scripts, browser extensions) might break your scripts. At a minimum, leave a short message with <noscript> like this: <noscript>To use this site, please enable JavaScript.</noscript> Ideally, replicate the JavaScript functionality with HTML and server-side scripting when possible. If you're only looking for simple visual effects, CSS can often get the job done even more intuitively. Since almost everybody does have JavaScript enabled, <noscript> is no excuse for writing inaccessible scripts. Learn more <script> <noscript> James Edwards' introduction to using JavaScript accessibly Accessibility guidelines from W3C ...
Debugging HTML - Learn web development
rs in HTML. Prerequisites: HTML familiarity, as covered in, for example, Getting started with HTML, HTML text fundamentals, and Creating hyperlinks. Objective: Learn the basics of using debugging tools to find problems in HTML. Debugging isn't scary When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs -- you've done something wrong, so your code doesn't work -- either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to compile a simple program written in the Rust language. Here, the error message is relatively easy to understand -- "unterminated double quote string". If you look at the listing, you can probably see how println!(Hello, world!"); mi...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
10.7 1433.5 -140 62 Ice giants Uranus 86.8 51,118 1271 8.7 17.2 2872.5 -195 27 Neptune 102 49,528 1638 11.0 16.1 4495.1 -200 14 Dwarf planets Pluto 0.0146 2,370 2095 0.7 153.3 5906.4 -225 5 Declassified as a planet in 2006, but this remains controversial. When done correctly, even blind people can interpret tabular data in an HTML table -- a successful HTML table should enhance the experience of sighted and visually impaired users alike. Table styling You can also have a look at the live example on GitHub! One thing you'll notice is that the table does look a bit more readable there -- this is because the table you see above on this page has minimal styli...
Making asynchronous programming easier with async and await - Learn web development
look at some examples that prove the concept. We've got two examples available -- slow-async-await.html (see source code) and fast-async-await.html (see source code). Both of them start off with a custom promise function that fakes an async process with a setTimeout() call: function timeoutPromise(interval) { return new Promise((resolve, reject) => { setTimeout(function(){ resolve("done"); }, interval); }); }; Then each one includes a timeTest() async function that awaits three timeoutPromise() calls: async function timeTest() { ... } Each one ends by recording a start time, seeing how long the timeTest() promise takes to fulfill, then recording an end time and reporting how long the operation took in total: let startTime = Date.now(); timeTest().then(() => { let f...
General asynchronous programming concepts - Learn web development
p, and it's taking so long that I was worried you'd wonder what was going on." This is a frustrating experience and isn't a good use of computer processing power -- especially in an era in which computers have multiple processor cores available. There's no sense sitting there waiting for something when you could let the other task chug along on another processor core and let you know when it's done. This lets you get other work done in the meantime, which is the basis of asynchronous programming. It is up to the programming environment you are using (web browsers, in the case of web development) to provide you with APIs that allow you to run such tasks asynchronously. Blocking code Asynchronous techniques are very useful, particularly in web programming. When a web app runs in a browser a...
Introduction to events - Learn web development
Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example. First, a simple HTML form that requires you to enter your first and last name: <form> <div> <label for="fname">First name: </label> <input id="fname" type="text"> </div...
JavaScript building blocks - Learn web development
ecisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article we'll explore how conditional structures work in JavaScript. Looping code Sometimes you need a task done more than once in a row. For example, looking through a list of names. In programming, loops perform this job very well. Here we will look at loop structures in JavaScript. Functions -- reusable blocks of code Another essential concept in coding is functions. Functions allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it...
Client-side web APIs - Learn web development
looking at APIs from a high level -- what are they, how do they work, how do you use them in your code, and how are they structured? We'll also take a look at what the different main classes of APIs are, and what kind of uses they have. Manipulating documents When writing web pages and apps, one of the most common things you'll want to do is manipulate web documents in some way. This is usually done by using the Document Object Model (DOM), a set of APIs for controlling HTML and styling information that makes heavy use of the Document object. In this article, we'll look at how to use the DOM in detail, along with some other interesting APIs that can alter your environment in interesting ways. Fetching data from the server Another very common task in modern websites and applications is retr...
Handling text — strings in JavaScript - Learn web development
u want to include a variable or expression inside the string, you include it inside a ${ } construct, which is called a placeholder. You can include complex expressions inside template literals, for example: let examScore = 45; let examHighestScore = 70; examReport = `You scored ${ examScore }/${ examHighestScore } (${ Math.round((examScore/examHighestScore*100)) }%). ${ examScore >= 49 ? 'Well done, you passed!' : 'Bad luck, you didn\'t pass this time.' }`; The first two placeholders here are pretty simple, only including a simple value in the string. The third one calculates a percentage result and rounds it to the nearest integer. The fourth one includes uses a ternary operator to check whether the score is above a certain mark and print a pass or fail message depending on the result...
JavaScript object basics - Learn web development
ializing a variable. Try entering the following line below the JavaScript code that's already in your file, then saving and refreshing: const person = {}; Now open your browser's JavaScript console, enter person into it, and press Enter/Return. You should get a result similar to one of the below lines: [object Object] Object { } { } Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the JavaScript object in our file to look like this: const person = { name: ['Bob', 'Smith'], age: 32, gender: 'male', interests: ['music', 'skiing'], bio: function() { alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] ...
CSS performance optimization - Learn web development
main thread and onto the GPU. Properties that will lead to compositing include 3D transforms (transform: translateZ(), rotate3d(), etc.), animating transform and opacity, position: fixed, will-change, and filter. Some elements, including <video>, <canvas> and <iframe>, are also on their own layer. When an element is promoted as a layer, also known as composited, animating transform properties is done in the GPU, resulting in improved performance, especially on mobile. will-change property The CSS will-change property tells browsers which properties of an element are expected to change enabling browsers to set up optimizations before the element is actually changed, improving performance by doing potentially expensive work before it is required. will-change: opacity, transform; The font-di...
Multimedia: Images - Learn web development
add support for even more advanced formats like High Efficiency Image File Format (HEIF) or AV1 Still Image File Format (AVIF). Given the narrow support for JPEG-XR and JPEG2000, and also taking decode costs into the equation, the only serious contender for JPEG today is WebP. Which is why you could consider offering your images in that flavor, too, for the browsers that support it. This can be done via the <picture> element with the help of a <source> element equipped with a type attribute. If all of this sounds a bit complicated or feels like too much work for your team then there is also online services that you can use as image CDNs that will automate the serving of the correct image format on-the-fly, according to the type of device or browser requesting the image. The biggest ones are...
JavaScript performance - Learn web development
framework, or multiple, with several additional dependencies. Often times third party scripts and APIs are added, including A/B testing, tracking pixels, and features like maps and support features. All of this JavaScript must be downloaded. Eventually. Performance optimizatins should include: Reducing the amount of JavaScript that is needed. Some features requiring complex JavaScript can be done with a few lines of JavaScript. Requiring a library for other features may improve developer experience, but is all that JavaScript required? Is there a lighter weight or home spun solutions? Some features may not be necessary, and though they may add some bling, is the cost of the feature in terms of performance worth it? Remove unused code Split the JavaScript into smaller files Code-split...
Client-Server Overview - Learn web development
e data from the database, and then constructs the HTML page for the response by inserting the data into an HTML template. This has major advantages over a static site: Using a database allows the product information to be stored efficiently in an easily extensible, modifiable, and searchable way. Using HTML templates makes it very easy to change the HTML structure, because this only needs to be done in one place, in a single template, and not across potentially thousands of static pages. Anatomy of a dynamic request This section provides a step-by-step overview of the "dynamic" HTTP request and response cycle, building on what we looked at in the last article with much more detail. In order to "keep things real" we'll use the context of a sports-team manager website where a coach can selec...
Ember interactivity: Events, classes and state - Learn web development
knows what we typed in, and we can save our todo and pass that text along to the todo list component to display. We can capture the keydown event via the on modifier, which is just Ember syntactic sugar around addEventListener and removeEventListener (see this explanation if needed). Add the new line shown below to your header.hbs file: <input class='new-todo' aria-label='What needs to be done?' placeholder='What needs to be done?' autofocus {{on 'keydown' this.onKeyDown}} > This new attribute is inside double curly braces, which tells you it is part of Ember's dynamic templating syntax. The first argument passed to on is the type of event to respond to (keydown), and the last argument is the event handler -- the code that will run in response to the keydown event firing. As you...
Framework main features - Learn web development
site, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components. For example, our AuthorCredit React component might be utilized inside an Article component. That means that Article would need to import AuthorCredit. import AuthorCredit from "./components/AuthorCredit"; Once that's done, AuthorCredit could be used inside the Article component like this: ... <AuthorCredit /> ... Dependency injection Real-world applications can often involve component structures with multiple levels of nesting. An AuthorCredit component nested many levels deep might, for some reason, need data from the very root level of our application. Let's say that the magazine site we're building is...
Accessibility in React - Learn web development
ngRef = useRef(null); Prepare the heading Heading elements like our <h2> are not usually focusable. This isn't a problem -- we can make any element programmatically focusable by adding the attribute tabindex="-1" to it. This means only focusable with JavaScript. You can't press Tab to focus on an element with a tabindex of -1 the same way you could do with a <button> or <a> element (this can be done using tabindex="0", but that's not really appropriate in this case). Let's add the tabindex attribute -- written as tabIndex in JSX -- to the heading above our list of tasks, along with our headingRef: <h2 id="list-heading" tabIndex="-1" ref={listHeadingRef}> {headingText} </h2> Note: The tabindex attribute is great for accessibility edge-cases, but you should take great care to not overuse...
Getting started with React - Learn web development
t set doesn't make great use of React's features. That's where props come in. Component props A prop is any data passed into a React component. Props are written inside component calls, and use the same syntax as HTML attributes -- prop="value". Let's open index.js and give our <App/> call its first prop. Add a prop of subject to the <App/> component call, with a value of Clarice. ...
React interactivity: Editing, filtering, conditional rendering - Learn web development
same way as we did earlier with our <Todo /> component, we now have to update FilterButton.js to utilize the props we have given it. Do each of the following, and remember to use curly braces to read these variables! Replace all with {props.name}. Set the value of aria-pressed to {props.isPressed}. Add an onClick handler that calls props.setFilter() with the filter's name. ...
TypeScript support in Svelte - Learn web development
not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at different options for deploying our Svelte applications, further resources, and more. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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. REPL Unfortunately, TypeScript support is not ye...
Componentizing our Svelte app - Learn web development
mmended that you are familiar with the core HTML, CSS, and JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: To learn how to break our app into components and share information among them. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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. REPL To code along with us using the REP...
Getting started with Svelte - Learn web development
the moment the REPL can't handle folder names properly. If you are following the tutorial on the REPL, just create all your components inside the root folder. Then when you see a path in the code, for example import Todos from './components/Todos.svelte', just replace it with a flat URL, e.g. import Todos from './Todos.svelte'. The code so far Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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. REPL To code along with us using the REPL, start at h...
Dynamic behavior in Svelte: working with variables and props - Learn web development
You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn and put into practice some basic Svelte concepts, like creating components, passing data using props, render JavaScript expressions into our markup, modify the components state and iterating over lists. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to 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. REPL To code along with us using the R...
Understanding client-side JavaScript frameworks - Learn web development
t we're still missing -- the ability to edit existing todo items. To do this, we will take advantage of Vue's conditional rendering capabilities -- namely v-if and v-else -- to allow us to toggle between the existing todo item view and an edit view where you can update todo item labels. We'll also look at adding functionality to delete todo items. 8. Focus management with Vue refs We are nearly done with Vue. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using Vue refs to handle this -- an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component. 9. Vue re...
Handling common accessibility problems - Learn web development
text labels. Finally, a quick word about data tables. A basic data table can be written with very simple markup (see bad-table.html live, and source), but this has problems -- there is no way for a screen reader user to associate rows or columns together as groupings of data -- to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table. If you instead look at our punk-bands-complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers (<th> and scope attributes), <caption> element, etc. Note: For more information about accessible tables, read Accessible data tables. CSS CSS tends to provide a lot fewer fundamental accessibility features than HTML, ...
Git and GitHub - Learn web development
de_v2.js, myCode_v3.js, myCode_final.js, myCode_really_really_final.js, etc., but this is really error-prone and unreliable. Different team members will commonly want to create their own separate versions of the code (called branches in Git), work on a new feature in that version, and then get it merged in a controlled manner (in GitHub we use pull requests) with the master version when they are done with it. VCSes provide tools to meet the above needs. Git is an example of a VCS, and GitHub is a web site + infrastructure that provides a Git server plus a number of really useful tools for working with git repositories individually or in teams, such as reporting issues with the code, reviewing tools, project management features such as assigning tasks and task statuses, and more. Note: Git...
Deploying our app - Learn web development
step in the toolchain is to connect GitHub to Netlify so our project can be deployed live on the web! Using Netlify for deployment Deploying from GitHub to Netlify is surprisingly simple once you know the steps, particularly with "static websites" such as this project. Note: There are also a lot of guides and tutorials on Netlify to help you improve your development workflow. Let's get this done: Go to https://app.netlify.com/start. Press the Github button underneath the Continuous Deployment heading. "Continuous Deployment" means that whenever the code repository changes, Netlify will (try) to deploy the code, thus it being "continuous". Depending on whether you authorized Netlify before, you might need to authorize Netlify with GitHub, and choose what account you ...
Chrome Worker Modules
r global value exports, as follows: /* File myModule.js */ let secretKey = "this is a secret"; let publicKey = "this is public"; exports.key = publicKey; // secretKey is not exported // publicKey is exported with name "key" Alternatively, if you prefer that style, you may write // variable |module| is a special global introduced by require() module.exports = { key: publicKey }; Once this is done, we may load the module and use the values that have been exported // Assuming that myModule.js is installed to resource://gre/modules/myModule.js let Module = require("resource://gre/modules/myModule.js") foo(Module.key); // Module.key == "this is public"; // However, secretKey is not exported and cannot be used For the installation of resources, please see the documentation on moz.build (i...
Accessibility API cross-reference
sible object states, such as focused, read-only, checked, etc. An interesting problem is that Mozilla, Safari/KHTML, Opera, StarOffice and other apps are cross-platform, but there is currently no cross-platform Accessibility API. The IPC mechanisms used by current generation API's are also not cross-platform, although communication for some cross-platform accessibility API of the future could be done through sockets. These tables describe how various accessibility APIs define possible roles of an object, and states. All accessibility APIs to date define a list of possible object roles, or general types, such as button, menu item, text, etc. They also define a list of possible object states, such as focused, read-only, checked, etc. This table is the start of a cross-reference, so we can spot...
Mozilla accessibility architecture
orking with any major screen reader, screen magnifier or voice dictation product on the market. We hope to change that soon, and are working with the major vendors (and Gnopernicus on Linux/UNIX) to achieve this. In any case, for the moment the only plans on Windows are for minor bug fixes based on feedback from assistive technology vendors. On Linux and UNIX, there probably needs to be more work done on folding in with the new architecture (such as more use of the "Wrap" classes). Something that could create more work would be a decision to support the Macintosh accessibility API, a new API being developed by Microsoft for future versions of Windows or some other new API developed for cross platform or small device use. Hopefully our general accessibility architecture will be able to support ...
Accessibility information for UI designers and developers
This page describes a number of design-related aspects to look out for, in no particular order. Color Enough contrast Ensure there is enough contrast between foreground and background colors. Your content can then be better consumed by users with low vision and people with color deficiencies. The ratio should be 4.5:1 for regular text and 3:1 for large text. Calculating this ratio is easiest done with a tool, for example Lea Verou's Contrast Ratio. There are also plug-ins available for design software, like Stark for Sketch. Don't rely on color alone When your interface uses color to distinguish between things, make sure the distinction is also made in other ways. For example, add text labels or texture in addition to color differences. For example, in this chart, it helps to add labe...
Gecko info for Windows accessibility vendors
browser available on the Windows platform XUL-Based Clients (support MSAA) XUL-based clients make full use of the Gecko architecture, not only for HTML content, as well as for menus, dialogs and the entire user interface via an XML language called XUL (eXtensible User-interface Language). None of the user interface contains standard Windows controls -- not even the menus! This is done to ensure a common look and feel across all supported platforms, and to allow for different skins (appearances). Firefox (please use version 1.1 alpha builds or later) Thunderbird (please use version 1.1 alpha builds or later) Mozilla Seamonkey (please use 1.8 alpha builds or later) How to Find the Content Window and Load the Document Screen readers need to find...
Information for External Developers Dealing with Accessibility
o make it accessible with 3rd party assistive technologies, containing practical tips and the details of Mozilla's implementation. Accessibility API cross reference Should be helpful at anyone looking at implementing accessibility API support for a product on multiple platforms. Contains info on accessible roles, states and events. Accessible Toolkit Checklist A list of what needs to be done for accessibility when building new toolkits, widget by widget. In addition, here is a list of official keyboard UI guidelines for each desktop: Windows keys: Guidelines on keyboard UI design and on implementing keyboard shortcuts: An excellent resource from Microsoft. Mac keys: Keyboard Shortcuts Quick Reference for Mac OS X Complete reference on keyboard for Mac OS X...
Lightweight themes
Important: Please be sure you have the rights to use the image in your theme! Upload your image -- make sure it is under 300 KB in size and JPG or PNG format! Select text and tab colors -- you can choose the tab ("background") color and foreground text color that work best with your header image. Submit your theme -- if everything looks right, click the Submit Theme button and you're done! You can see all the themes you've authored on your profile page. Tip: to ensure that your theme is approved for the gallery, be sure it complies with the content guidelines and terms of service! Submit Your Theme Now Frequently asked questions For more information about Lightweight themes, including content guidelines, please see these Frequently Asked Questions. More tutorials ...
Application cache implementation overview
es made (i.e. all files downloaded are deleted and the new cache version is discarded.) An MD5 hash is then calculated from the manifest content we download from the server to be compared to existing MD5 (in case of an "update"). During the load, manifest is parsed according the "parsing the cache manifest" HTML5 spec, and lists of entries and namespaces are collected. After the manifest fetch is done, nsOfflineCacheUpdate::LoadCompleted() is called. nsOfflineCacheUpdate::LoadCompleted() is called for each finished entry load, including the manifest and is the main place handling each update state as following: On CHECKING state, a state the update is at after manifest parsing has been done, LoadCompleted checks whether the new hash, i.e. the manifest content, differs or this is just "...
What to do and what not to do in Bugzilla
Getting/Upgrading Bugzilla privileges If you want to get Bugzilla privileges (as described below), please see this page. It lists the requirements and the email to contact. If you need faster access to get canconfirm or editbugs, especially in order to triage bugs or to participate in a bug day, then you can ask in #bmo on irc, or you may create a bug requesting permissions. Include a link to your Bugzilla activity page in the bug description. ...
Creating a Login Manager storage module
to fully employ the KDE wallet manager, rather than any secondary replacements of KDEwallet. If you just want to use the Login Manager in your extensions, refer to the article Using nsILoginManager. Overriding the built-in Login Manager storage consists of two tasks: Implement the nsILoginManagerStorage interface. Register that interface in a specific category. Some work has already been done to integrate the Login Manager with the Mac OS X keychain (bug 106400) and Gnome Keyring Manager (bug 309807). You should start with the existing code if you want to implement that in your extension. To see some debugging output in the console set signon.debug to true using about:config. Sample JavaScript implementation The following code snippet is a JavaScript component that implements a dum...
Creating reftest-based unit tests
as fired. 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. The reason for using the 'MozReftestInvalidate' event is because a document's initial painting is not typically finished when the 'load' event fires. It would be possible to try and wait for the initial rendering to be done using a setTimeout, but that would be unreliable, and just as bad, it can increase the time it takes to run a test many times over (which when you're running thousands of tests can really slow things down). The 'MozReftestInvalidate' event is designed to fire as soon after the initial rendering of the document is finished as possible, but never before. The reftest framework fires one MozReftestIn...
Creating Sandboxed HTTP Connections
It would be better to have the entire implementation inside a class and storing the channel as a member: function myClass() { this.mChannel = null; // ... var listener = new this.StreamListener(callbackFunc); // ... } myClass.prototype.StreamListener = function (aCallbackFunc) { return ({ mData: "", // ... }) } Handling cookies When sending...
HTTP logging
is because Firefox now uses multiple processes, and each process gets its own log file. For many bugs, the "log.txt-main" file is the only thing you need to upload as a file attachment to your Bugzilla bug (this is assuming you're logging to help a mozilla developer). Other bugs may require all the logs to be uploaded--ask the developer if you're not sure. Pat yourself on the back--a job well done! Thanks for helping us debug Firefox. Logging HTTP activity by manually setting environment variables Sometimes the about:networking approach won't work, for instance if your bug occurs during startup, or you're running on mobile, etc. In that case you can set environment variables *before* you launch Firefox. Note that this approach winds up logging the whole browser history, so files can ...
Obsolete Build Caveats and Tips
s in releases/mozilla-1.9.1. To get this code, do the following: # Pull the Mozilla source to the folder 191src/ - may take a while # as hundreds of megabytes of history is downloaded to .hg hg clone https://hg.mozilla.org/releases/mozilla-1.9.1/ 191src cd 191src Note: Starting with Gecko 5.0, you can actually build Firefox without a .mozconfig file. By default, a similar-to-release build is done. From Windows_SDK_versions Visual C++ 9 (VS2008) Professional/Express Download and install the Windows 7 SDK. Note that you need Service Pack 1--for the Express edition it is a separate download. Visual C++ 8 (VS2005) Professional Download and install the Windows 7 SDK. Install this Microsoft hotfix to allow linking to work correctly. Visual C++ 7.1 or Visual C++ 8 (VS2005) Express ...
Reviewer Checklist
In C++, cycle-collect as needed. If JavaScript can see your object, it probably needs to be cycle-collected. [Fennec: If your custom view does animations, it's better to clean up runnables in onDetachFromWindow().] Ensure all file handles and other closeable resources are closed appropriately. [Fennec: When writing tests that use PaintedSurface, ensure the PaintedSurface is closed when you're done with it.] Performance impact Check for main-thread IO [Fennec: Android may warn about this with strictmode]. Remove debug logging that is not needed in production. Threading issues Enormous: correct use of locking and volatility; livelock and deadlock; ownership. [Fennec: All view methods should be touched only on UI thread.] [Fennec: Activity lifecycle awareness (works with "never k...
SVG Guidelines
flexibility depends on doing computations for SVG images at the time they're displayed, rather than at the time the author creates them. Consider an image that involves some complex gradients and filters. If saved as a raster image then the work to rasterize the gradients and filters takes place on the authors computer before the result is stored in the raster file. This work doesn't need to be redone when the image is displayed on someone else's computer. On the other hand, if the image is saved as an SVG image then all this work needs to be done each time the SVG is displayed on someone else's computer. This isn't to say that SVG images are always slower than raster equivalents. In fact it can be faster to send vector information from an SVG to a user's GPU than it is to extract raster data ...
Limitations of frame scripts
nd Workers will work. However, some APIs that work in the chrome process will not work in a frame script. This article lists the most important of these APIs. File I/O You should not write to or read from the disk from a frame script, in particular, the profile directory. Even if this is possible, you should not do it and may expect that it could stop working at any time. File I/O should all be done in the chrome process. For example: nsIFileInputStream nsIFileOutputStream Constructing a File from a string or nsIFile (but File objects can be sent via message manager) HTMLInputElement.mozSetFileNameArray (alternative: mozSetFileArray) file: URIs, see bug 1187099 <...> XUL and browser UI Anything that tries to touch the browser UI or anything to do with XUL is likely not to work in ...
Firefox and the "about" protocol
user enabled the crash reporter) about:credits Lists all contributors to the Firefox project about:debugging Switches to the Developer Tools debugging page, which allows you to debug add-ons, tabs and Service Workers about:devtools Summarizes the developer tools and provides links to documentation for each tool about:downloads Displays all downloads done within Firefox about:home Start page of Firefox when opening a new window about:license Displays licensing information about:logo Firefox logo about:memory Provides a way to display memory usage, save it as report and run the GC and CC about:mozilla Special page showing a message from "The Book of Mozilla" about:networking Di...
Browser API
HTMLIFrameElement.zoom() Changes the zoom factor of the browser <iframe>'s content. This is particularly useful for zooming in/out on non-touch-enabled devices. Events In order to allow an application to manage the browser <iframe>, the application can listen for new events about what's happening within the browser <iframe>. The following new events can be listened for: mozbrowseractivitydone Sent when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. mozbrowserasyncscroll Sent when the browser <iframe> content scrolls (the APCZ version.) See also mozbrowserscroll. Note that this is obsolete. mozbrowseraudioplaybackchange Sent when audio starts or stops playing within the browser <iframe> content. moz...
Embedding Tips
ust also implement nsIAuthPrompt if you want to be able to upload to a password protected location (e.g. an ftp site). The nsIAuthPrompt interface allows the networking layer to pose a user / password prompt to obtain the values needed for authentication. Your own implementation should pose this dialog, or fill in the values that are needed for the upload to succeed. How do I know when saving is done, monitor progress etc.? Register your ownnsIWebProgressListener object to listen for progress and state notifications. Here is a simple example which demonstrates the principle. The SimplePersist() function takes a string URL and a string file path. In response it creates a persist object, creates a listener and starts the operation. As the operation progresses, methods on the listener such as ...
How to add a build-time test
have various automation tools that help make this possible. The first link, though, is the "check" target in a Makefile. If a test is added, that test or its directory needs to be mentioned in a Makefile.in file somewhere so that the build system knows about it. Standalone executables To add a test that is written in C or C++ and which is called as a standalone executable, a few things must be done. For standalone executables, if one sets up the right variables, then the rules.mk file will do lots of magic and most of the heavy lifting. A simple example of adding a test is in . Note that the following variables are supplied by the rules.mk file: CPPSRCS, SIMPLE_PROGRAMS, RUN_TEST_PROGRAM. XPCShell tests Here are the simple guidelines for adding an xpcshell test to the build system. ...
How to implement a custom autocomplete search component
he nsIAutoCompleteSearch interface. Make sure the contract ID of your XPCOM component follows the following form: "@mozilla.org/autocomplete/search;1?name=xxx", where "xxx" is the name of your autocomplete source. Implement the list of matched strings using the nsIAutoCompleteResult interface. The simplest way to make an XPCOM component is to build an XPCOM JavaScript Component (this cannot be done with a JavaScript module). How to Build an XPCOM Component in Javascript will step you through the process. Because creating an XPCOM component in order to build a custom autocomplete source can be enough to discourage some developers, below is an example JavaScript XPCOM component called "simple-autocomplete" that implements the necessary interfaces. Note: When copying the examples below, chan...
IPDL Tutorial
n protocol destruction in lieu of using the DeallocPProtocol function. ...
JavaScript Tips
te instead. Prefer to loop through childNodes rather than using first/lastChild with next/previousSibling. But prefer hasChildNodes() to childNodes.length > 0. Similarly prefer document.getElementsByTagName(aTag).item(0) != null to document.getElementsByTagName(aTag).length > 0. Prefer to use localName rather than tagName. XUL elements have many of the attributes mapped to properties. This was done for a reason, so use them! The properties are: align allowEvents contextMenu datasources dir flex height id left maxHeight maxWidth minHeight minWidth observes orient pack persist ref statusText top tooltip tooltipText width XUL also maps the ordinal attribute but this defaults to "1" if it is not present. XUL also m...
AsyncShutdown.jsm
t some point during shutdown, the Add-On Manager needs to ensure that all add-ons have safely written their data to disk, before writing its own data. Since the data is saved to the profile, this must be completed during phase profileBeforeChange. AsyncShutdown.profileBeforeChange.addBlocker( "Add-on manager: shutting down", function condition() { let promise = ... // Do whatever must be done before the end of phase profileBeforeChange return promise; }, function info() { let status = ... // Collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); In this example, at some point during phase profileBeforeChange, function condition will be called. Phase profileBeforeChange is guaranteed to not terminate until ...
CustomizableUI.jsm
ose instance is being destroyed, aDocument the document in which this is happening. Only fired for API-based widgets. onWidgetDrag(aWidgetId, aArea) Fired both when and after customize mode drag handling system tries to determine the width and height of widget aWidgetId when dragged to a different area. aArea will be the area the item is dragged to, or undefined after the measurements have been done and the node has been moved back to its 'regular' area. onCustomizeStart(aWindow) Fired when opening customize mode in aWindow. onCustomizeEnd(aWindow) Fired when exiting customize mode in aWindow. onWidgetOverflow(aNode, aContainer) Fired when a widget's DOM node is overflowing its container, a toolbar, and will be displayed in the overflow panel. onWidgetUnderflow(aNode, aContainer) Fir...
Download
e, and may not be known before the download is started. To have any effect, this property must be set before starting the download. Resetting this property to false after the download has already started will not remove any partial data. Note: If this property is set to true, care should be taken that partial data is removed before the reference to the download is discarded. This can be done using the removePartialData() or the finalize() methods. Methods start() Starts the download for the first time, or restarts a download that failed or has been canceled. Calling this method when the download has been completed successfully has no effect, and the method returns a resolved promise. If the download is in progress, the method returns the same promise as the previous cal...
Downloads.jsm
version 26, the nsIDownloadManager and nsIDownload interfaces are not available anymore. The new module works differently from the old component. In general, you should be aware of the following highlights: There is no difference between active downloads and finished downloads. The Download object can be used without requiring direct database access. Observer notifications (for example, "dl-done") and download listeners are replaced by views on the DownloadList object returned by the getList() method. Object identity replaces the use of numeric identifiers. You can use Download objects as keys in a Set or Map to associate your own state to them for the session. There is no separate count of active downloads. If a count is needed, it should be maintained using a view on a DownloadList. ...
Interfacing with the Add-on Repository
of add-ons and even install new add-ons. This article provides some sample code that queries the recommended add-ons list on AMO and lets the user click a button to install an add-on from the list. Importing the repository code module Before you can use the Add-on Repository API, you need to import the code module: Components.utils.import("resource://gre/modules/AddonRepository.jsm"); Having done this, you can then access the API through the resulting AddonRepository object. Enabling the recommendation feature In current builds of Firefox 4, the recommendation API doesn't work because the preference for the URL to query to get recommended add-ons is not included by default; see bug 628785. To make the service work for the time being, you can use code like this when your extension starts...
JNI.jsm
Val); Parameters aIndex The position in the array to change. aVal A value to set it to. Return value This function has no return value, if you try to store the return value in a variable, it will be undefined. .setElements() Sets a section of a typed array to specified values. This function starts on the position of aStart in the array and sets it to the values in aValsArray. This is done by calling .set for each element with the respective value in the aValsArray. void setElements(Number aStart, [array, size_is(arr.length > Number anyNumber > 0)] in CData aValsArray); Parameters aStart The position to start setting elements of the array in. aValsArray A Javascript array holding the values to set. Return value This function has no return value, if you try to store the ...
OS.File for the main thread
ts.libc.O_WRONLY; } // For Gecko >= 27, it is enough, but crucial, to set the correct append flag. var outfile = yield OS.File.open("file.tmp", {write: true, append: false}, options); try { // ... do something with that file } finally { yield outfile.close(); } }); Example of opening file and keeping it locked This uses Tasks.jsm to open a file and keep it open. When you are done with it, like in shutdown of restartless add-on, you should close the file so it becomes editable again. let options = { winShare: 0 // Exclusive lock on Windows }; if (OS.Constants.libc.O_EXLOCK) { // Exclusive lock on *nix options.unixFlags = OS.Constants.libc.O_EXLOCK; } let file = yield OS.File.open(..., options); Then when you want to unlock the file so it can be edited from other pl...
PromiseWorker.jsm
cle titled Transferring special data from main thread to worker. Returns A Promise object. Transferring special data from main thread to worker The regular rules of workers apply; special data of MessagePort and ArrayBuffer objects can be transferred as of Firefox 40. There are two ways to transfer data. The first is with aTransferList argument and other with BasePromiseWorker.Meta. Both are done by the post function described above. aTransferList To transfer an ArrayBuffer object, pass an array containing it as aTransferList argument. myWorker.post('func', [buffer], null, [buffer]); This is simpler if the you know what to transfer at the callsite. BasePromiseWorker.Meta Above code can also be done with the Meta object. Each special data argument that you want to transfer, you can w...
Index
you don't have a lot of experience with code, you might even be concerned that you've broken something (oops!). Now we'll walk you through performing some quality assurance testing on your work to make sure you're on the right track. 15 Release phase Localization You've made it! You've setup up your local and remote environments, you've selected your L10n tools and projects, done some localization and even some testing! Now you're ready for the final phase: becoming an official L10n release. Here, we'll continue to stay true to the original intent of this guide and only present you with the technical information you need to become an official release. We'll primarily focus on getting your release repository setup and the Mercurial commands you'll need to know to use that ...
Localizing extension metadata on addons.mozilla.org
untry where the language is spoken. The Reward is up to you, but $5-10 per translation seems to work well. Localization codes AMO offers 33 localizations, including English. Here is a list of the codes: Arabic (ar), Catalan (ca), Czech (cs), Danish (da), German (de), Greek (el), Basque (eu), Spanish (es-ES), Farsi (fa), Finnish (fi), French (fr), Gaeilge (ga-IE), Hebrew (he), Hungarian (hu), Indonesian (id), Italian (it), Japanese (ja), Korean (ko), Mongolian (mn), Dutch (nl), Polish (pl), Brazilian Portuguese (pt-BR), European Portuguese (pt-PT), Romanian (ro), Russian (ru), Slovakian (sk), Albanian (sq), Swedish (sv-SE), Ukrainian (uk), Vietnamese (vi), Chinese (zh-CN) and Taiwanese (zh-TW). ...
Localizing with Mozilla Translator
ew product... or more. With good oldie CVS, you could checkout just the locale content and, even more, you could checkout just ''the locale directories'' you were interested in. With Mercurial, partial checkouts are not possible, so you have your own Mozilla repository full copy (there are alternate solutions; read on). A bit of history on MT MT has been evolving from long ago, when L10n were done always on shipped en-US JARs and when Mozilla Suite had five L10n JARs: ab-CD.jar, ab-win.jar, ab-mac.jar, ab-unix.jar, and CD.jar. MT thus referred to ab-CD.jar contents as ''Platform neutral'' platform, CD.jar as '''region''' platform (or regional files), and the other three as ''Windows platform'', ''Mac platform'' and ''Unix platform''. This JAR structure is now used just by SeaMonkey 1.1.x. ...
QA phase
s at hg.mozilla.org. Before a team becomes official, we like to get the localizers comfortable with the Hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository. We use a web service called Bit Bucket to start the learning process. Note: You must have Mercurial configured before you begin. That step is back on the initial setup page. If you haven't done that yet, don't worry, we'll wait for you! Pushing to your repository There are a couple of things you should take note of before you push to your repository: Make sure that your files have been encoded in Unicode without BOM (byte order mark). Remember that here you are pushing an entire directory, not a .zip archive file or an .xpi lang pack. The instructions below will help you learn h...
Uplifting a localization from Central to Aurora
repo. Let's pretend it's at releases/l10n-mozilla-aurora/ab-CD Here's how we do it: # set up a new local clone of your central repo hg clone l10n-central/ab-CD workrepo cd workrepo # pull in the changesets you have on aurora hg pull -r default ../releases/l10n/mozilla-aurora/ab-CD Now, there are two routes forward: 1) things are pretty silent. Good luck, you're basically done. All you need to do is to push from your l10n-central clone to your aurora repo. 2) new heads, you need to merge. this looks something like searching for changes adding changesets adding manifests adding file changes added 22 changesets with 23 changes to 46 files (+1 heads) (run 'hg heads' to see heads, 'hg merge' to merge) OK, let's make sure we're not talking relbranch...
MathML In Action
( ? g ) s ) 1 / s For more examples, refer to links on the MathML Project page, and if you are building your own Mozilla binary, see the directory mozilla/layout/mathml/tests. Now, what next? As you try out MathML in Mozilla, what to do with those few things that appear to you not to work as per the MathML spec? Or what about those things that just seem itchy, and that you wish could be done just a little better? Or what about those things that were working before and are not working anymore (a.k.a. regressions)? In either case, head over to Bugzilla to report the discrepancies. Bugzilla has a big memory for these things, and besides, how would your problems be fixed if they are not reported?! Getting involved is part of your contribution towards enriching Gecko with an elegant stand...
Using the viewport meta tag to control layout on mobile browsers
er pages in a virtual window or viewport, which is usually wider than the screen, and then shrink the rendered result down so it can all be seen at once. Users can then pan and zoom to see different areas of the page. For example, if a mobile screen has a width of 640px, pages might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 640px space. This is done because many pages are not mobile optimized, and break (or at least look bad) when rendered at a small viewport width. This virtual viewport is a way to make non-mobile-optimized sites in general look better on narrow screen devices. Enter viewport meta tag However, this mechanism is not so good for pages that are optimized for narrow screens using media queries -- if the virtual viewport is 98...
Mozilla Web Developer FAQ
e using the usual HTML features (no MathML or SVG) and are serving your content as text/html to other browsers, there is no need to serve application/xhtml+xml to Mozilla. Serving valid HTML as text/html ensures the widest browser and search engine support. There is a fad of serving text/html to IE but serving the same markup with no added value as application/xhtml+xml to Gecko. This is usually done without a mechanism that would ensure the well-formedness of the served documents. Mechanisms that ensure well-formed output include serializing from a document tree object model (eg. DOM) and XSLT transformations that do not disable output escaping. When XHTML output has been retrofitted to a content management system that was not designed for XML from the ground up, the system usually ends up d...
Mozilla Web Services Security Model
cation headers soapv SOAP requests with verification headers The from attribute The from attribute on the allow element says which calling sites the allow element applies to. If there is no from attribute then the allow element applies to all sites. The from attribute otherwise gives a URL to match, which may contain up to two asterisks (*) that match any characters in the URL. The match is done against a URL from which the directory and file have been removed, so trying to match a specific page will cause the entire match to fail. (Is this correct?) web-scripts-access.xml Examples These examples are untested! Somebody should test them to make sure they do what is claimed. Allow all services on a site to be accessed from any Web page Note that this is only a sensible thing to do if n...
Mozilla Development Strategies
attention (a new crasher, a blocker, or problem in your area, for example). Use this same tree for small, quick bugs or recent regressions or crashers. For your other tree, don't update as often. Update when you know that the tree is in good shape. Do your primary development in this tree. You'll need to update, rebuild, re-test and make a diff against the current trunk once you feel your fix is done. But, daily regressions won't block your primary development. As far as keeping trees up to date goes, the longer you go without updating your tree, the more likely you are to have CVS conflicts. If you update every day for a week, you might not have any conflicts, but if you update once a week and you've changed a lot of code, you'll most likely have conflicts. See mozilla\config\fast-update.p...
BloatView
} MyType::~MyType() { MOZ_COUNT_DTOR(MyType); ... } ...
Investigating CSS Performance
http://people.mozilla.org/~jmuizelaar/css-perf.patch This patch instruments a bunch of key places and should give an estimate of the order of magnitude of the different parents. Two counts are collected which allow for an estimation of the amount of work being done during restyle: resolveStyleForCount this is incremented everytime that we do style resolution on an element ContentEnumFuncCount this is incremented roughly for every rule that we test against Time during restyle can be spent in a bunch of places. For example, HasStateDependentStyle will compute a hint that determines how many elements we'll restyle. If we get a eRestyle_Subtree we will restyle more elements. This was developed while investigating Bug 1110625 ...
Memory reporting
ith memory reporters. It identifies places in the code that allocate memory but do not have memory reporters for that memory. This helps drive about:memory's heap-unclassified number down. It detects certain defects in existing heap memory reporters: if non-heap memory is reported, or if a heap block is partially reported or double-reported. DMD is absolutely crucial; these things cannot be done without it. That's why the integration of DMD and memory reporters is so important and thus mentioned multiple times above. See the instructions on how to run DMD. ...
Power profiling overview
xt wakeup measurements: dtrace (on Mac) and perf (on Linux.) Source-level instrumentation, such as TimerFirings logging, can identify which timers are firing frequently. Power profiling how-to This section aims to put together all the above information and provide a set of strategies for finding, diagnosing and fixing cases of high power consumption. First of all, all measurements are best done on a quiet machine that is running little other than the program of interest. Global measurements in particular can be completely skewed and unreliable if this is not the case. Find or confirm a test case where Firefox's power consumption is high. "High" can most easily be gauged by comparing against other browsers. Use power measurements or estimates (e.g. via tools/power/rapl, or mach power on...
Profiling with Instruments
at you want to profile Click the stop button Command line tools There is instruments and iprofiler. How do we monitor performance counters (cache miss etc.)? Instruments has a "Counters" instrument that can do this. Memory profiling Instruments will record a call stack at each allocation point. The call tree view can be quite helpful here. Switch from "Statistics". This malloc profiling is done using the malloc_logger infrastructure (similar to MallocStackLogging). Currently this means you need to build with jemalloc disabled (ac_add_options --disable-jemalloc). You also need the fix to Bug 719427 The DTPerformanceSession api can be used to control profiling from applications like the old CHUD API we use in Shark builds. Bug 667036 System Trace might be useful. ...
Profiling with Xperf
rder of weight, regardless of what module they're in. Dragging the columns around will change grouping in various ways; experiment to get the data that you're looking for. Also experiment with turning columns on and off; removing a column will allow data to be aggregated without considering that column's contributions. Disabling all but one core will make the numbers add up to 100%. This can be done by running 'msconfig' and going to Advance Options from the "Boot" tab. Building Firefox To get good data from a Firefox build, it is important to build with the following options in your mozconfig: export CFLAGS="-Oy-" export CXXFLAGS="-Oy-" This disables frame-pointer optimization which lets xperf do a much better job unwinding the stack. Traces can be captured fine without this option (for e...
Profiling with the Firefox Profiler
bel stack The label stack (formerly called "Pseudo stack") uses function entry/exit tags added by hand to important points in the code base. The stacks you see in the UI are chains of these tags. This is good for highlighting particularly interesting parts of the code, but they miss out on un-annotated areas of the code base, and give no visibility into system libraries or drivers. Tagging is done by adding macros of the form AUTO_PROFILER_LABEL("NAMESPACE", "NAME"). These add RAII helpers, which are used by the profiler to track entries/exits of the annotated functions. For this to be effective, you need to liberally use AUTO_PROFILER_LABEL throughout the code. See GeckoProfiler.h for more variations like AUTO_PROFILER_LABEL_DYNAMIC. Because of the non-zero overhead of the instrumentati...
Reporting a Performance Problem
g a performance problem using the built-in Gecko Profiler tool. Enabling the Profiler toolbar button These steps only work in Firefox 75+. Visit https://profiler.firefox.com/ Click on "Enable Profiler Menu Button" The profiler toolbar button will show up in the top right of the URL bar as a small stopwatch icon You can right-click on the button and remove it from the toolbar when you're done with it. Using the Profiler When enabled, the profiler toolbar button is not recording by default. Recording can be done by clicking on the toolbar icon to open its panel. Make sure to choose an appropriate setting for the recording (if you're not sure, choose Firefox Platform), and then choosing "Start Recording". The toolbar icon turns blue when it is recording. The profiler uses a fixed si...
Scroll-linked effects
performance, related tools, and possible mitigation techniques. Scrolling effects explained Often scrolling effects are implemented by listening for the scroll event and then updating elements on the page in some way (usually the CSS position or transform property.) You can find a sampling of such effects at CSS Scroll API: Use Cases. These effects work well in browsers where the scrolling is done synchronously on the browser's main thread. However, most browsers now support some sort of asynchronous scrolling in order to provide a consistent 60 frames per second experience to the user. In the asynchronous scrolling model, the visual scroll position is updated in the compositor thread and is visible to the user before the scroll event is updated in the DOM and fired on the main thread. Thi...
TimerFirings logging
The ??? indicates that the function timer lacks an explicit name, and the comment within the square brackets explains why the fallback mechanism wasn't used. If an unannotated timer function appears frequently it is worth explicitly annotating it so that it will be usefully identified on other platforms. (Running on Mac or Linux is obviously necessary to learn the timer function's name.) This is done by initializing it with initWithNamedFuncCallback or initWithNameableFuncCallback instead of initWithNameCallback. Post-processing TimerFirings logging quickly produces thousands of lines of output. This output needs post-processing for it to be useful. If the output is redirected to a file called out, then the following command will pull out the timer-related lines, count how many times each u...
TraceMalloc
if (filename) TraceMallocDumpAllocations(filename); </script> One can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak. If there are significant differences, it might be worth examining the call stacks for the destructors of the objects in question to see what is extending their lifetime. (This can be done by examining the unprocessed output of an XPCOM_MEM_REFCNT_LOG, one of the nsTraceRefcnt logs.) You should use the --use-address argument to diffbloatdump.pl, and then the diff tree can be run through fix_linux_stack.py or fix_macosx_stack.py as needed. Leaksoup Leaksoup is a trace-malloc tool that analyzes the shutdown log. Because this log includes the contents of heap blocks, leaksoup can anal...
Performance
hin C++ code in Firefox. Profiling with Instruments How to use Apple's Instruments tool to profile Mozilla code. Profiling with Xperf How to use Microsoft's Xperf tool to profile Mozilla code. Profiling with Concurrency Visualizer How to use Visual Studio's Concurrency Visualizer tool to profile Mozilla code. Profiling with Zoom Zoom is a profiler for Linux done by the people who made Shark Measuring performance using the PerfMeasurement.jsm code module Using PerfMeasurement.jsm to measure performance data in your JavaScript code. Adding a new Telemetry probe Information on how to add a new measurement to the Telemetry performance-reporting system Profiling JavaScript with Shark (obsolete - replaced by Instruments) How to u...
Emscripten
f introduction to what Emscripten is. To get started with Emscripten, go to the official Emscripten Wiki. Using Emscripten, you can Compile C and C++ code into JavaScript Compile any other code that can be translated into LLVM bytecode into JavaScript. Compile the C/C++ runtimes of other languages into JavaScript, and then run code in those other languages in an indirect way (this has been done for Python and Lua)! Emscripten makes native code immediately available on the Web: a platform that is standards-based, has numerous independent compatible implementations, and runs everywhere from PCs to iPads. With Emscripten, C/C++ developers don't have the high cost of porting code manually to JavaScript -- or having to learn JavaScript at all. Web developers also benefit, as they can use ...
Midas editor module security preferences
xt Editing demo page will not work. To enable these functions, you must modify your browser preferences. Warning: Changing these preferences can leave your browser insecure, especially if you grant permission to untrusted sites. Only change these settings as needed to try the demo above and to test your own add-on or Firefox-internal code, and be sure to restore the default settings when you're done! Changing the preferences in Firefox Quit Firefox. If you have Quick Launch running (on Windows, this is an icon in the toolbar), quit that too. Find your Firefox profile directory. Open the user.js file from that directory in a text editor. If there's no user.js file, create one. Add these lines to user.js: user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capabi...
Midas
an IFRAME and do the bulk of the scripting in the parent document. According to standards, The IFRAME element has the contentDocument property that refers to the document in the inline frame. It also has a property called contentWindow that refers to the window object inside the inline frame. This also avoids problems with bug 198155. In addition to the built-in commands, advanced editing can be done by manipulating the Selection and range objects. It is beneficial to be familiar with these objects when working with an editable document. Examples This example shows the basic structure described in the Notes section : <html> <head> <title>Simple Edit Box</title> </head> <body> <iframe id="MidasForm" src="about:blank" onload="this.contentDocument.designMode='on';" ></iframe...
NSPR's Position On Abrupt Thread Termination
. To make this solution work requires that a function that encounters an error be designed such that it first repairs its immediate state, and then reports that error to its caller. If the caller cannot deal with the failure, it must do the same. This process continues until the thread either recovers from the malady or returns from the root function. This is not all that difficult (though having done it a number of times to already existing code, I will admit it isn't much fun either). The implementation of either strategy within the NSPR runtime is not difficult. That is not what this memo is about. This is about providing an API that coaxes people to do the right thing in as many ways as possible. The existence of exit() in the UNIX/C environment is a perfect example of how programmers will...
Optimizing Applications For NSPR
n in the <tt>PR_EXTERN()</tt> declarations in NSPR's header files. NSPR functions returning floating point types and structs by value, including the derived types PRInt64, are declared <tt>__PASCAL</tt>. These different declarations are to accommodate restrictions in Watcom's C/C++ version 11.0 and 11.0a compiler. Windows 3.1 does not provide a non-blocking file I/O interface. NSPR's file I/O is done using Windows 3.1's synchronous file I/O API. The NSPR file I/O APIs may cause a thread switch even though the I/O is fully synchronous. Do not depend on File I/O being synchronous. Command line applications using the LIBC printf() and related APIs behave funny on Windows 3.1. Read the fine print in the Windows SDK for the grizzly details. Watch out for PRIntn overflow on Win16. Make sure all p...
Anonymous Shared Memory
ocesses using an anonymous shared memory terminate, the backing file is deleted. ... If you are not paranoid, you're not paying attention. The file-mapped shared memory requires a protocol for the parent process and child process to share the memory. NSPR provides two protocols. Use one or the other; don't mix and match. In the first protocol, the job of passing the inheritable shared memory is done via helper-functions with PR_CreateProcess. In the second protocol, the parent process is responsible for creating the child process; the parent and child are mutually responsible for passing a FileMap string. NSPR provides helper functions for extracting data from the PRFileMap object. ... See the examples below. Both sides should adhere strictly to the protocol for proper operation. The pseudo...
Dynamic Library Linking
; funcPtr = PR_FindSymbolAndLibrary("FunctionName", &lib); When PR_FindSymbolAndLibrary returns, funcPtr is the value of the function pointer you want to look up, and the variable lib references the main executable program. You can then call PR_FindSymbol on lib to look up other symbols defined in the main program. Remember to call PR_UnloadLibrary(lib) to close the library handle when you are done. Platform Notes To use the dynamic library loading functions on some platforms, certain environment variables must be set at run time, and you may need to link your executable programs using special linker options. This section summarizes these platform idiosyncrasies. For more information, consult the man pages for ld and dlopen (or shl_load on HP-UX) for Unix, and the LoadLibrary documentati...
PR_AttachThread
...
PR_DetachThread
...
PR_Wait
ntrol of the monitor's lock with the same entry count it had before the wait began. A thread waiting on the monitor resumes when the monitor is notified or when the timeout specified by the ticks parameter elapses. The resumption from the wait is merely a hint that a change of state has occurred. It is the responsibility of the programmer to evaluate the data and act accordingly. This is usually done by evaluating a Boolean expression involving the monitored data. While the Boolean expression is false, the thread should wait. The thread should act on the data only when the expression is true. The boolean expression must be evaluated while in the monitor and within a loop. In pseudo-code, the sequence is as follows: PR_EnterMonitor(&ml); while (!expression) wait; ... act on the state chang...
JSS 4.4.0 Release Notes
es Netswork Security Services (NSS) 3.29.1 and Netscape Portable Runtime (NSPR) 4.13.1 or newer. JSS 4.4.0 source distributions are available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/JSS_4_4_0_RTM/src/ New in JSS 4.40 New Functionality New Functions New Macros Notable Changes in JSS 4.40 Picks up work done downstream for Fedora and RHEL and used by various Linux distributions with includes:. Support for IPv6. Support for TLS v1.1 and TLS v1.2 via NSS though JSS. Bugs fixed in JSS 4.4.0 This Bugzilla query returns all the bugs fixed in NSS 4.4.0: https://bugzilla.mozilla.org/buglist.cgi?product=JSS&target_milestone=4.4&target_milestone=4.4&bug_status=RESOLVED&resolution=FIXED Documentation B...
NSS Key Log Format
ng is enabled by setting the environment variable SSLKEYLOGFILE to point to a file. Note: starting with NSS 3.24 (used by Firefox 48 and 49 only), the SSLKEYLOGFILE approach is disabled by default for optimized builds using the Makefile (those using gyp via build.sh are not affected). Distributors can re-enable it at compile time though (using the NSS_ALLOW_SSLKEYLOGFILE=1 make variable) which is done for the official Firefox binaries. (See bug 1188657.) Notably, Debian does not have this option enabled, see Debian bug 842292. This key log file is a series of lines. Comment lines begin with a sharp character ('#') and are ignored. Secrets follow the format <Label> <space> <ClientRandom> <space> <Secret> where: <Label> describes the following secret. <ClientRandom> is 32 bytes Random value...
NSS Memory allocation
o solve that problem, it is generally necessary to disable the arena free list, so that arenas are actually freed back to the heap each time they are freed, and are allocated afresh from the heap each time they are allocated. This makes NSS slower, but produces accurate leak allocation stacks. To accomplish that, set an environment variable prior to the initialization of NSS and NSPR. This can be done outside the program entirely, or can be done by the program itself, in the main() function. Set the environment variable NSS_DISABLE_ARENA_FREE_LIST to have any non-empty value, e.g. NSS_DISABLE_ARENA_FREE_LIST=1. ...
NSS 3.19.2 release notes
New in NSS 3.19.2 New Functionality No new functionality is introduced in this release. Notable Changes in NSS 3.19.2 Bug 1172128 - In NSS 3.19.1, the minimum key sizes that the freebl cryptographic implementation (part of the softoken cryptographic module used by default by NSS) was willing to generate or use was increased - for RSA keys, to 512 bits, and for DH keys, 1023 bits. This was done as part of a security fix for Bug 1138554 / CVE-2015-4000. Applications that requested or attempted to use keys smaller then the minimum size would fail. However, this change in behaviour unintentionally broke existing NSS applications that need to generate or use such keys, via APIs such as SECKEY_CreateRSAPrivateKey or SECKEY_CreateDHPrivateKey. In NSS 3.19.2, this change in freebl behavio...
NSS 3.21 release notes
The returned strings must be freed by the caller. The difference with NSS_ArgParseModuleSpec is the new function handles NSS configuration parameter strings. NSSUTIL_MkModuleSpecEx - take a shared library string, module name string, module parameters string, NSS specific parameters string, and NSS configuration parameter string and returns a module string which the caller must free when it is done. The difference with NSS_MkModuleSpec is the new function handles NSS configuration parameter strings. New Types in pkcs11t.h CK_TLS12_MASTER_KEY_DERIVE_PARAMS{_PTR} - parameters {or pointer} for CKM_TLS12_MASTER_KEY_DERIVE CK_TLS12_KEY_MAT_PARAMS{_PTR} - parameters {or pointer} for CKM_TLS12_KEY_AND_MAC_DERIVE CK_TLS_KDF_PARAMS{_PTR} - parameters {or pointer} for CKM_TLS_K...
Release notes for recent versions of NSS
...
NSS sources building testing
tly for private use within NSS, and applications and test tools are not allowed to call them. For any functions that are listed in the .def files, NSS promises that the binary function interface (ABI) will remain stable. Building NSS NSS is built using gyp and ninja, or with make on systems that don't have those tools. The complete build instructions include more information. Once the build is done, you can find the build output below directory dist/?, where ? will be a name dynamically derived from your system's architecture. Exported header files for NSS applications can be found in directory "include", library files in directory "lib", and the tools in directory "bin". In order to run the tools, you should set your system environment to use the libraries of your build from the "lib" dire...
nss tech note7
ME, plus a few enhancements over the years to support JSS.) When using the PK11_ interfaces, the same principal applies: use the highest available function. If you are really trying to send a key, you should use PK11_PubWrapSymKey(). For a low level signature, use PK11_Sign(). Both of these functions do the PKCS #1 wrapping of the data. PK11_Sign does not do the BER encoding of the hash (as is done in SGN_ functions). If you are trying to just send data, use PK11_PubEncryptPKCS1. PK11_PubEncryptRaw is the lowest level function. It takes a modulus size data and does a raw RSA operation on the data. It's used to support SSL2, which modifies the key encoding to include the SSL version number. PKCS #1 v1.5 Block Formatting Question: In PKCS #1 v1.5 (Section 8.1 Encryption-block formatt...
NSS Tools sslstrength
rs'. For example, ciphers=bfi will turn on these cipher preferences and turn off all others. policy=export or policy=domestic will set your policies appropriately. policy will default to domestic if not specified. Step-up Step up is a mode where the connection starts out with 40-bit encryption, but due to a 'change-cipher-spec' handshake, changes to 128-bit encryption. This is only done in 'export mode', with servers with a special certificate. You can tell if you stepped-up, because the output will says 'using export policy', and you'll find the secret key size was 128-bits. Prerequisites You should have a cert7.db in the directory in which you run sslstrength. Other For references, here is a table of well-known SSL port numbers: HTTPS 443 IMAPS 993 NNTPS 563 ...
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
ference the same key for different sessions? No. This is never necessary. The PKCS #11 specification explicitly requires that symmetric keys must be visible to all sessions of the same application. NSS explicitly depends on this semantic without the use of C_CopyObject. If your module does not support this semantic, it will not work with NSS. QUESTIONS ABOUT PINS Will a password change ever be done on the token? Yes, NSS attempts to change the password in user mode only. (It goes to SSO mode only if your token identifies itself as CKF_LOGIN_REQUIRED, but not CKF_USER_INITIALIZED). It's perfectly valid to reject the password change request with a return value such as CKR_FUNCTION_NOT_SUPPORTED. If you do this, NSS applications display an appropriate error message for the user. If I have m...
PKCS11 module installation
n your local computer Open the Firefox preferences dialog. Choose "Advanced" > "Encryption" > "Security Devices" Choose "Load" Enter a name for the security module, such as "My Client Database". NOTE: there is currently a bug in Firefox where international characters may cause problems. Choose "Browse..." to find the location of the PKCS #11 module on your local computer, and choose "OK" when done. Provisioning PKCS #11 modules using the pkcs11 API Starting with Firefox 58, extensions can use the pkcs11 browser extension API to enumerate PKCS #11 modules and make them accessible to the browser as sources of keys and certificates. ...
Python binding for NSS
PYNSS_RELEASE_0_14_0 Source Download https://ftp.mozilla.org/pub/mozilla.org/security/python-nss/releases/PYNSS_RELEASE_0_14_0/src/ Change Log The primary enhancements in this version is support of certifcate validation, OCSP support, and support for the certificate "Authority Information Access" extension. Enhanced certifcate validation including CA certs can be done via Certificate.verify() or Certificate.is_ca_cert(). When cert validation fails you can now obtain diagnostic information as to why the cert failed to validate. This is encapsulated in the CertVerifyLog class which is a iterable collection of CertVerifyLogNode objects. Most people will probablby just print the string representation of the returned CertVerifyLog object. Cert validation logging is...
Build instructions
t-shell-msvc2010.bat from MozillaBuild to get a bash shell with the PATH already configured, and execute these instructions from within that bash shell. For RHEL-5, you need to use the new assembler. You can install the new assembler as root as follows: yum install binutils220 You can then use the new assembler by adding /usr/libexec/binutils220 to the beginning of your build path. This can be done in sh or bash as follows: export PATH=/usr/libexec/binutils220:$PATH The following build instructions should work for all platforms (with some platform-specific changes as noted). Build Instructions for Recent Versions (Mercurial) Clone the NSPR and NSS repositories. hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss If you want to build a relea...
Installation guide
. So right now you need to manually install the headers, libraries, and programs in the directories you want. If you install the libraries in a directory other than /usr/lib, you usually need to set the LD_LIBRARY_PATH environment variable. You can avoid that by installing the libraries in a directory that is $ORIGIN/../lib, where $ORIGIN is the directory where the programs are installed. ...
Sample manual installation
After building NSS with "gmake nss_build_all", the resulting build can be found in the NSS source tree as follows: NSS header files: mozilla/dist/public/nss NSPR header files: mozilla/dist/<OBJ-DIR>/include NSPR/NSS shared libs: mozilla/dist/<OBJ-DIR>/lib NSS binary executables: mozilla/dist/<OBJ-DIR>/bin. where <OBJ-DIR> would vary according to the type of build and the platform. ...
FC_Finalize
Syntax CK_RV FC_Finalize (CK_VOID_PTR pReserved); Parameters FC_Finalize has one parameter: pReserved must be NULL Description FC_Finalize shuts down the NSS cryptographic module in the FIPS mode of operation. If the library is not initialized, it does nothing. The pReserved argument is not used and must be NULL. Return value FC_Finalize always returns CKR_OK. FC_Finalize should check the pReserved argument and return CKR_ARGUMENTS_BAD if pReserved is not NULL. FC_Finalize should return CKR_CRYPTOKI_NOT_INITIALIZED if the library is not initialized. ...
NSS tools : certutil
uIFNtaXRoMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMVUpDOZ KmHnOx7reP8Cc0Lk+fFWEuYIDX9W5K/BioQOKvEjXyQZhit9aThzBVMoSf1Y1S8J CzdUbCg1+IbnXaECAwEAAaAAMA0GCSqGSIb3DQEBBQUAA0EAryqZvpYrUtQ486Ny qmtyQNjIi1F8c1Z+TL4uFYlMg8z6LG/J/u1E5t1QqB5e9Q4+BhRbrQjRR1JZx3tB 1hP9Gg== -----END NEW CERTIFICATE REQUEST----- Creating a Certificate A valid certificate must be issued by a trusted CA. This can be done by specifying a CA certificate (-c) that is stored in the certificate database. If a CA key pair is not available, you can create a self-signed certificate using the -x argument with the -S command option. $ certutil -S -k rsa|dsa|ec -n certname -s subject [-c issuer |-x] -t tr ustargs -d [sql:]directory [-m serial-number] [-v valid-months] [-w offs et-months] [-p phone] [-1] [-2] ...
NSS tools : modutil
y databases available. modutil can be used to create these files. The only required argument is the database that where the databases will be located. modutil -create -dbdir [sql:]directory Adding a Cryptographic Module Adding a PKCS #11 module means submitting a supporting library file, enabling its ciphers, and setting default provider status for various security mechanisms. This can be done by supplying all of the information through modutil directly or by running a JAR file and install script. For the most basic case, simply upload the library: modutil -add modulename -libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] For example: modutil -dbdir sql:/home/my/sharednssdb -add "Example PKCS #11 Module" -libfile "/tmp/crypto.so" -mechanisms RSA:DSA:R...
gtstd.html
trusted for issuing certificates for SSL client and server authentication. >certutil -A -d server_db -n "MyCo's Root CA" -t "TC,," -a -i CA_db/rootca.crt Create the server certificate request, specifying the subject name for the server certificate. We make the common name (CN) be identical to the hostname of the server. Note that this step generates the server's private key, so it must be done in the server's database directory. >certutil -R -d server_db -s "CN=myco.mcom.org,O=MyCo,ST=California,C=US" -a -o server_db/server.req Enter Password or Pin for "Communicator Certificate DB": This step simulates the CA signing and issuing a new server certificate based on the server's certificate request. The new cert is signed with the CA's private key, so this operation uses the C...
NSS Tools modutil
Module Database Tool displays a warning: WARNING: Performing this operation while Communicator is running couldcause corruption of your security databases. If Communicator iscurrently running, you should exit Communicator before continuing thisoperation. Type 'q <enter>' to abort, or <enter> to continue: After you press Enter, the tool displays the following: Creating "c:\databases\key3.db"...done.Creating "c:\databases\cert8.db"...done.Creating "c:\databases\secmod.db"...done. Displaying Module Information This example gives detailed information about the specified module: modutil -list "Netscape Internal PKCS #11 Module" -dbdir c:\databases The Security Module Database Tool displays information similar to this: Using database directory c:\databases...---------------------------...
NSS Tools sslstrength
s'. For example, ciphers=bfi will turn on these cipher preferences and turn off all others. policy=export or policy=domestic will set your policies appropriately. policy will default to domestic if not specified. Step-up Step up is a mode where the connection starts out with 40-bit encryption, but due to a 'change-cipher-spec' handshake, changes to 128-bit encryption. This is only done in 'export mode', with servers with a special certificate. You can tell if you stepped-up, because the output will says 'using export policy', and you'll find the secret key size was 128-bits. Prerequisites You should have a cert7.db in the directory in which you run sslstrength. Other For references, here is a table of well-known SSL port numbers: HTTPS 443 ...
certutil
DEwpKb2huIFNtaXRoMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMVUpDOZ KmHnOx7reP8Cc0Lk+fFWEuYIDX9W5K/BioQOKvEjXyQZhit9aThzBVMoSf1Y1S8J CzdUbCg1+IbnXaECAwEAAaAAMA0GCSqGSIb3DQEBBQUAA0EAryqZvpYrUtQ486Ny qmtyQNjIi1F8c1Z+TL4uFYlMg8z6LG/J/u1E5t1QqB5e9Q4+BhRbrQjRR1JZx3tB 1hP9Gg== -----END NEW CERTIFICATE REQUEST----- Creating a Certificate A valid certificate must be issued by a trusted CA. This can be done by specifying a CA certificate (-c) that is stored in the certificate database. If a CA key pair is not available, you can create a self-signed certificate using the -x argument with the -S command option. $ certutil -S -k rsa|dsa|ec -n certname -s subject [-c issuer |-x] -t trustargs -d [sql:]directory [-m serial-number] [-v valid-months] [-w offset-months] [-p phone] [-1] [-2] [-3] [...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
ailable. modutil can be used to create these files. The only required argument is the database that where the databases will be located. modutil -create -dbdir [sql:]directory Adding a Cryptographic Module Adding a PKCS #11 module means submitting a supporting library file, enabling its ciphers, and setting default provider status for various security mechanisms. This can be done by supplying all of the information through modutil directly or by running a JAR file and install script. For the most basic case, simply upload the library: modutil -add modulename -libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] For example: modutil -dbdir sql:/home/my/sharednssdb -add "Example PKCS #11 Module" -libfile "/tmp/crypto.so" -mechanisms ...
Necko Architecture
ocol handler creates HTTP channels for HTTP URLs. Once you have a channel you can read or write data from or to your URI. nsIIOService The nsIIOService does the protocol handler lookup for you. However, you can certainly ask the nsIIOService for the protocol handler for the URI you have, then ask the protocol handler for a channel on that URI. In fact, most of what the nsIIOService does can be done independently of the nsIIOService, by hand. The nsIIOService acts as a convenience interface, consolidating several steps for the user. To summarize, the nsIIOService creates URL instances. It does this by looking up the protocol handler for the scheme of the URL, then asking the protocol handler to create the URL. The nsIIOService can also create channels. It does this by looking up the protocol...
Necko walkthrough
of OnSocketWritable: nsIAsyncInputStream::AsyncWait (i.e. mSocketIn) sets the callback and waits. The HTTP request is now written to the socket, which has a callback to the nsHttpConnection... Note: from what I can tell, there are some cases where the transaction is queued up to be written to the socket later if it's not writable now, or in the case of pipelining or SPDY where it's done in batches. But I'm not an expert in either of these things. Once the socket is readable (more async behavior), nsHttpConnection::OnInputStreamReady is called on the socket thread. nsHttpConnection::OnInputStreamReady nsHttpConnection::OnSocketReadable nsHttpTransaction::WriteSegments nsHttpConnection::OnWriteSegment passes bytes from mSocketIn->Read to the transaction's pipe nsP...
Rhino FAQ
ction. For instance, to create an array of java.lang.String of length five, do var stringArray = java.lang.reflect.Array.newInstance(java.lang.String, 5); Then if you wish to assign the string "hi" to the first element, simply execute stringArray[0] = "hi". Creating arrays of primitive types is slightly different: you must use the TYPE field. For example, creating an array of seven ints can be done with the code var intArray = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE, 7); When I try to execute a script I get the exception Required security context missing. What's going on? You've likely missed placing the Security.properties file in your class path at org.mozilla.javascript.resources. Can I use Rhino in a web browser? Rhino is a library for Java use, and not for gene...
Rhino overview
However, Rhino is an implementation of the core language only and doesn't contain objects or methods for manipulating HTML documents. Rhino contains All the features of JavaScript 1.7 Allows direct scripting of Java A JavaScript shell for executing JavaScript scripts A JavaScript compiler to transform JavaScript source files into Java class files A JavaScript debugger for scripts executed with Rhino Language The JavaScript language itself is standardized by Standard ECMA-262 ECMAScript: A general purpose, cross-platform programming language. ...
Scripting Java
output f(int) f(String) f(Object) Because Rhino selects an overloaded method at runtime, it calls the more specific type that matches the argument. Meanwhile Java selects the overloaded method purely on the type of the argument at compile time. Although this has the benefit of selecting a method that may be a better match for each call, it does have an impact on performance since more work is done at each call. In practice this performance cost hasn't been noticeable in real applications. Because overload resolution occurs at runtime, it can fail at runtime. For example, if we call Overload's method g with two integers we get an error because neither form of the method is closer to the argument types than the other: js> o.g(3,4) js:"<stdin>", line 2: The choice of Java method Overload.g ...
Rhino serialization
} js> f() 3 js> Here we see a simple case of a function being serialized to a file and then read into a new instance of Rhino and called. Rhino serialization APIs Two new classes, ScriptableOutputStream and ScriptableInputStream, were introduced to handle serialization of Rhino classes. These classes extend ObjectOutputStream and ObjectInputStream respectively. Writing an object to a file can be done in a few lines of Java code: FileOutputStream fos = new FileOutputStream(filename); ScriptableOutputStream out = new ScriptableOutputStream(fos, scope); out.writeObject(obj); out.close(); Here filename is the file to write to, obj is the object or function to write, and scope is the top-level scope containing obj. Reading the serialized object back into memory is similarly simple: FileInputStrea...
GCIntegration - SpiderMonkey Redirect 1
be traced if the object is native. As much as possible, avoid trace hooks. If objects are structured as described above, there should be no need for them. This should be obvious by now, but never ever allow a GC thing point to a GC thing in a different compartment unless it's a wrapper that's registered in the cross-compartment wrapper map. Now, on to the details... GC/CC interaction <To be done later.> Incremental GC Incremental GC divides GC marking into time slices. In between these slices, non-GC code is allowed to run. Done naively, this technique can lead to reachable object not being marked. Consider the following example. {{ Svg{source: "http://people.mozilla.org/~wmccloskey/incremental1.svg", embedding: "iframe", height:"130"} }} Assume object B is already marked, as in the ...
GC Rooting Guide
tly no convenience typedefs for JS::Heap<T>. For example, instead of this: struct HeapStruct { JSObject* mSomeObject; JS::Value mSomeValue; }; You should write: struct HeapStruct { JS::Heap<JSObject*> mSomeObject; JS::Heap<JS::Value> mSomeValue; }; Tracing js::NativeObject All GC pointers stored on the heap must be traced. For regular js::NativeObjects, this is normally done by storing them in slots, which are automatically traced by the GC. Other JSObjects When defining a JSObject subclass that contains Heap<T> fields, set the trace hook to invoke a function that traces those fields. General Classes/Structures For a regular struct or class, tracing must be triggered manually. The usual way is to define a void trace(JSTracer* trc, const char* name) method on the ...
Statistics API
ase includes the time for the sweep_atoms, sweep_tables, sweep_compartments phases and so on. The times object gives how much time was spent in each phase of the GC, in milliseconds. Additionally, an incremental GC is divided into a series of slices (the division into slices is completely separate from the division into phases; neither one is a refinment of the other). A little bit of GC work is done in each slice. In between slices, other browser code is allowed to run. The slices array describes how long each slice took and what work was done during the slice. Each element of the slices array is an object with these fields: slice: integer - The slice index, starting at 0. pause: number (milliseconds) - The slice duration. when: number (milliseconds) - The time this slice started, relat...
Property cache
. Occasionally, during garbage collection, all shape ids are regenerated (in order to recycle unused shape ids so that we don't run out; see calls to js_RegenerateShapeForGC. This could end up changing the shape of every object, so the property cache and JIT cache are emptied when this happens. Unique shapes. An object may be given a unique shape using JSObject::generateOwnShape. This is usually done in order to bump the shape of one object without affecting other objects that happen to have the same properties. For example, when sealing an object, we must somehow preserve the extensibility guarantee. We do this by giving the sealed object a unique shape. Branded objects. An object may be branded. The interpreter and JIT brand an object whenever they find that enabling the branded object gua...
Tracing JIT
in maintaining the Assembler's high speed and small size. In the SpiderMonkey tracing JIT there is only ever one Assembler active at a time, associated with the currently active Fragmento. nanojit/RegAlloc.* Nanojit's register allocator. This is a local register allocator, meaning that it does not allocate registers across basic blocks. It is correspondingly very simple: register allocation is done immediately, step-by-step as code is being generated. A running tally is kept of assignments between registers and LIR operands, and any time a new LIR operand is required in a register a new one is assigned from the list of free registers. When all registers are in use, the least-often-used register currently in use is spilled. nanojit/Native*.* The files Nativei386.h, Nativei386.cpp, NativeAR...
JSAPI Cookbook
or: v = JS::NullValue(); v.setUndefined(); // or: v = JS::UndefinedValue(); v.setBoolean(false); // or: v = JS::BooleanValue(false); Finding the global object Many of these recipes require finding the current global object first. // JavaScript var global = this; There is a function, JS_GetGlobalForScopeChain(cx), that makes a best guess, and sometimes that is the best that can be done. But in a JSNative the correct way to do this is: /* JSAPI */ bool myNative(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSObject *global = JS_GetGlobalForObject(cx, &args.callee()); ... } Defining a function // JavaScript function justForFun() { return null; } /* JSAPI */ bool justForFun(JSContext *cx, unsigned argc, JS::V...
JSAPI User Guide
t script to use. As the script runs, it can create global functions and variables of its own. All of these functions, classes, and variables are stored as properties of the global object. A minimal example Each of the three key elements described in the previous section requires a few JSAPI calls: The runtime: Use JS_NewRuntime to create it and JS_DestroyRuntime to clean it up when you're done. When your application is done with SpiderMonkey altogether, use JS_ShutDown to free any remaining cached resources. (This is a mere nicety if the process is about to exit anyway. But as that is not always the case, calling JS_Shutdown is a good habit to get into.) The context: Use JS_NewContext and JS_DestroyContext. For maximum ECMAScript standard compliance, applications should also use ...
JS::Value
its job. It's like a robot that goes around picking up everything that isn't nailed down and putting it in the trash. If an application has a JS::Value variable that refers to a JSObject, the garbage collector might not know you're using the JSObject. So it might free it, leaving a dangling pointer. The solution is to tell SpiderMonkey that you're using the object, then tell it again when you're done. In short, every JS::Value must be rooted or your program will randomly crash. In some places, SpiderMonkey provides already-rooted JS::Values which you can use for variables. See SpiderMonkey GC Rooting Guide. The jsval typedef for JS::Value JS::Value was historically known in the JSAPI as jsval. SpiderMonkey 1.8.5 made jsval into a C struct and exposed it in C++ through the full-fledged JS:...
JSPRINCIPALS_HOLD
ALS_HOLD and JSPRINCIPALS_DROP are used to manage memory for JSPrincipals objects. Principals are used by the SpiderMonkey security system. JSPrincipals objects are not JSObjects. They are reference counted, not garbage collected. Application code that stores a pointer to a JSPrincipals object must call JSPRINCIPALS_HOLD(cx, principals) before storing it and JSPRINCIPALS_DROP(cx, principals) when done with it. JSPRINCIPALS_HOLD(cx, principals) increments the reference count of principals by 1. JSPRINCIPALS_DROP(cx, principals) decrements the reference count of principals by 1. If the reference count drops to 0, indicating that no one is using the object anymore, JSPRINCIPALS_DROP also deallocates principals by calling its destroy method. See Also bug 728250 ...
JS_GetGlobalObject
y protected from garbage collection and the application can easily access it. ...
JS_NewContext
SContext, see JSAPI User Guide. The stackchunksize parameter does not control the JavaScript stack size. (The JSAPI does not provide a way to adjust the stack depth limit.) Passing a large number for stackchunksize is a mistake. In a DEBUG build, large chunk sizes can degrade performance dramatically. The usual value of 8192 is recommended. The application must call JS_DestroyContext when it is done using the context. Before a JSRuntime may be destroyed, all the JSContexts associated with it must be destroyed. The new JSContext initially has no global object. The new JSContext is associated with the calling thread. No other thread may use it or destroy it. See Also MXR ID Search for JS_NewContext JS_DestroyContext JS_ContextIterator JS_SetContextCallback ...
JS_NewObject
uires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. clasp const JSClass * Pointer to the class to use for the new object. If this is NULL, an ordinary JavaScript Object is created. The JSClass may be used to override low-level object behavior, including such details as the physical memory layout of the object and how property lookups are done. Added in SpiderMonkey 1.8.1 clasp->flags must not have the JSCLASS_GLOBAL_FLAGS bits set (use JS_NewGlobalObject instead). If clasp is non-null, the caller must ensure that the JSClass remains alive throughout the lifetime of the new object, including the garbage collection cycle that finally frees it. The usual way to do this is to make JSClasses global or static. proto JS:...
JS_PushArguments
the first element of an array of four jsvals: a boolean, a number, an object (or null), and a boolean. On success, JS_PushArguments fills in the supplied markp pointer and returns a pointer to the first element of an array of jsval which are automatically rooted as necessary (protected from the GC temporarily). The application must call JS_PopArguments using the supplied markp stack pointer when done with this stack frame, to free the memory and unroot the jsvals. On error or exception, JS_PushArguments returns NULL. To perform the opposite conversion, converting an array of jsvals to various native C types, use JS_ConvertArguments. See Also JS_PopArguments bug 542091 ...
JS_SetAllNonReservedSlotsToUndefined
Syntax void JS_SetAllNonReservedSlotsToUndefined(JSContext *cx, JSObject *objArg); Name Type Description cx JSContext * The context in which to clear the object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JSObject * Object from which to delete all properties. ...
JS_SetGCCallback
ection does not happen, so the other three callbacks are not called. Sometimes several GC cycles happen in a row, so JSGC_BEGIN is followed by alternating JSGC_MARK_END and JSGC_FINALIZE_END callbacks, followed at last by JSGC_END. The JSGC_BEGIN callback can occur very early when something triggers garbage collection--before the JavaScript engine has even determined whether GC should actually be done at the moment. Some quirky behavior follows from this: The JavaScript engine can call the GC callback reentrantly on a single thread. For example, if the JSGC_MARK_END callback does something that triggers GC, a JSGC_BEGIN callback might happen. But the JavaScript engine will then detect that GC is already happening and will not actually do a nested GC cycle in this case. In a JS_THREADSAFE ...
JS_SetProperty
the new property is added, the JSClass.addProperty hook is called with the arguments (cx, obj, id, &v). This hook may assign to v. If the hook succeeds and the property has a stored value, then the value left in v by the addProperty hook becomes the stored value of the property. Setting the value. Two of the cases above can involve setting the value of a new or existing property of obj. This is done as follows. If the property has a JavaScript setter, it is called; otherwise, if it has a JavaScript getter, then an error is reported; otherwise the property's setter is called, passing the arguments (cx, obj, id, &v). If the setter succeeds and the property has a stored value, then the value left in v becomes the stored value of the property. On success, JS_SetProperty returns true, and the va...
JS_SuspendRequest
ccess objects that the calling thread had locked. The return value is the number of nested requests that were suspended. It may be 0. JS_ResumeRequest resumes the previously suspended requests. The saveDepth argument must be the value returned by the matching JS_SuspendRequest call. If saveDepth is nonzero and garbage collection is underway, JS_ResumeRequest blocks until the garbage collector is done. JSAPI 1.7 and earlier JS_SuspendRequest and JS_ResumeRequest are available only in JS_THREADSAFE builds. In SpiderMonkey 1.8 and later, these functions will be present, but will do nothing, in non-JS_THREADSAFE builds. MXR ID Search for JS_SuspendRequest MXR ID Search for JS_ResumeRequest ...
JSAPI reference
If a variable is a root, then anything it points to will not be freed by the garbage collector. Failure to root objects is a very common cause of mysterious crashes. class JS::Rooted<T> Added in SpiderMonkey 17 class JS::RootedObject Added in SpiderMonkey 17 class JS::RootedFunction Added in SpiderMonkey 17 class JS::RootedScript Added in SpiderMonkey 17 class JS::...
Running Automated JavaScript Tests
'all', 'interp', 'none', etc. See the full list in the -h / --help output. One helpful option specific to jit-tests is -R filename (or --retest filename). The first time this is run, it runs the suite and writes a list of tests that failed to the given filename. The next time it is run, it will run only the tests in the given filename, and then will write the list of tests that failed when it is done. Thus, you can keep retesting as you fix bugs and only the tests that failed the last time will run, speeding things up a bit. Running jit-tests on Treeherder When viewing Treeherder after a push to the Mozilla repositories, jit-tests are run by calling make check, and appear under B. Creating new tests for jit-tests Creating new tests for jit-tests is easy. Just add a new JS file to the test...
Setting up CDT to work on SpiderMonkey
X GCC on Mac) and click "Finish". At this point, the indexer starts running and already produces a pretty decent index of much of SpiderMonkey. Still, there are a quite a few things that CDT does not pick up yet: For everything to be indexed, CDT has to be aware of the project's build details. Step 3 - Index all the code To let CDT know about the build, it has to invoke make itself (or, as is done in the guide for the whole Mozilla codebase on MDN, read a log of the build), which can be setup with these simple steps: Open the project's properties by selecting its root and clicking "Properties" in the "File" menu and select "C/C++ Build". Under the "Builder Settings" group tab, deactivate "Use default build command". Instead, change "Build command" to read make -w (this is required bec...
TPS Tests
first_modify] ]); The effects of this test file will be: Firefox is launched with profile1, the TPS extension adds the two bookmarks specified in the bookmarks_initial array, then they are synced to the Sync server. The SYNC_WIPE_SERVER argument causes TPS to set the firstSync="wipeServer" pref before syncing, in case the Sync account already contains data (this is typically unnecessary, and done largely as an example). Firefox closes. Firefox is launched with profile2, and all data is synced from the Sync server. The TPS extension verifies that all bookmarks in the bookmarks_initial list are present. Then it modifies those bookmarks by applying the "changes" property to each of them. E.g., the title of the first bookmark is changed from "google.com" to "Google". Next, the changes are sy...
Thread Sanitizer
set the variable to $LLVM_HOME/build/bin/llvm-symbolizer. Ignoring known races In some cases, races can be confirmed to be benign and fixing them would cause possible performance issues. TSan offers two possibilities to ignore such known races. Compile-time blacklisting Functions with racy memory access can be flagged, such that the compiler will not instrument them. In our codebase, this is done using the MOZ_TSAN_BLACKLIST macro on the function definition. It will expand to the appropriate attributes if the compiler supports them. Compile-time blacklisting is the preferred way of blacklisting, because it does not have a performance impact. Still, blacklisting should be done very carefully so we won't miss important bugs. Runtime suppressions To prevent races from showing up at runtime...
Mozilla Projects
net Explorer also supports the ability to edit specific elements using the contentEditable attribute; Starting with Firefox 3, Gecko also supports contentEditable. Once Midas is invoked, a few more methods of the document object become available. Mozinfo Throughout mozmill and other Mozilla python code, checking the underlying platform is done in many different ways. The various checks needed lead to a lot of copy+pasting, leaving the reader to wonder....is this specific check necessary for (e.g.) an operating system? Because information is not consolidated, checks are not done consistently, nor is it defined what we are checking for. Necko Necko is a network library that provi...
Redis Tips
"log.bacon" 4) "yes" Pubsub is useful for things like: Chat programs Message passing among application components Log routing from applications in multiple languages It's good stuff. Heartbeats and Time-based Event Logs It's a common pattern to use numerical timestamps for ranking members in a ZSET. I'll show this in the node console, to illustrate how the optional parameters are done. > var r = require('redis').createClient(); // and I'll define these utility functions just for this example > function now() { return (new Date()).getTime() / 1000 } > function print(err, results) { console.log(JSON.stringify(results, null, 2)) } Whenever someone logs into my site, I record them in my 'last-login' zset. I'll simulate some logins like so: > r.zadd('last-login', now(), 'lloy...
Secure Development Guidelines
s Constructor/Destructor Issues Example class foo { private: char *ptr; public: foo() {} ~foo() { if (ptr) free(ptr); } }; Constructor/Destructor Issues: Prevention Initialize the data members of an object in the constructor Writing Secure Code: Miscellaneous File I/O A lot can go wrong because a lot can be done with file input and output Filenames Permissions File handles and descriptors File I/O: Filename Divided in directories, subdirectories, and the file itself '/' is separator; in Windows '\' would work too int openfile(char *file) { HANDLE fh; if (strstr(file, "\")) return -1; fh = CreateFileA(file, ...); WriteFile(fh, data, sizeofdata, NU...
A Web PKI x509 certificate primer
from the site certificate to a trusted certificate of the user agent (ie if you follow the issuer path you will end on a self-signed certificate that is considered trusted by the browser). The attributes of the certificates in the verification path have valid parameters for that verification (for example the validity period of all the certificates are valid for the time the verification is being done) Revocation checks are considered OK for that particular validation. One issue that is not commonly known is that the x509 trust graph is not a forest (a bunch of trees where each root is a trusted root) but a cyclic graph, where the same key/issuer can be a root or an intermediate for another root in the browsers key store (when roots create intermediates for each other it is called cross-sig...
AT APIs Support
latform Camino - web browser for OS X XUL Applications XUL applications make full use of the Gecko architecture, not only for HTML content, but also for the entire user interface. Widgets such as menus, tab panels, tree views and dialogs are provided via an XML language called XUL (eXtensible User-interface Language). None of the user interface contains standard OS controls. This is done to ensure a common look and feel across all supported platforms, and to allow for different skins (appearances). Developing a XUL window is not that different from developing a web page, but the elements available to add widgets are more powerful and designed to be similar to desktop widgets. Examples of XUL applications: Firefox - web-browser Thunderbird - email client Seamonkey - web-brow...
XForms Accessibility
y "trunk" build of Firefox and install the XForms extension which lives in 'xpi' directory of the build. Note, XForms accessibility is implemented only on trunk. Trunk builds are not considered stable and should not be installed on top of the Firefox used for daily browsing. 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. You will find trunk builds of Firefox at ftp.mozilla.org, trunk builds of XForms extension (Windows) at ftp.mozilla.org or trunk builds of XForms extension (Linux) ftp.mozilla.org. Build It Yourself If you would like to build firefox/seamonkey yourself then please ensure your .mozconfig file has the following option: ac_add_options ...
Frecency algorithm
it counts). The total visit count includes embedded, undefined, etc visits (does not exclude invalid or embedded visits). Developer notes There are various development notes you can read about Places that may offer additional insights: Initial algorithm ideas Implementation notes History The initial algorithm design was by Mike Connor and Seth Spitzer. The initial implementation was done by Seth and Dietrich Ayala. Further features and refinement by Ed Lee (implemented adaptive matching and most of the character restrictors), Marco Bonardo and Shawn Wilsher. The latter two later ported all of the code from C++ to JavaScript. ...
History Service Design
es, dynamic containers and so on). See Querying Places for deeper knowledge on the actual implementation. Expiration Expiration is an important part of data management for two reasons: Privacy: expiring data based on user interaction is important, nothing must be left behind on a page removal Database maintenance: having cleaner and smaller tables helps queries performances Expiration is done at certain moments, but in future will most likely be moved to async queries, to be executed on a separate thread. Actually pages and visits are expired: On page added (lazily) On idle On shutdown Expiration of pages happens when a page is no more referenced, so there are no more visits, nor bookmarks associated with it. Visits are expired based on user preferences, there is an hard limit ...
Manipulating bookmarks using Places
g the bookmarks service. Initiating the bookmarks service As is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getService(Components.interfaces.nsINavBookmarksService); Creating a bookmark folder Creating a new bookmark folder is done using the nsINavBookmarksService.createFolder() method. For example, to create a new folder in the Bookmarks menu: var menuFolder = bmsvc.bookmarksMenuFolder; // Bookmarks menu folder var newFolderId = bmsvc.createFolder(menuFolder, "Folder name here", bmsvc.DEFAULT_INDEX); This code locates the Bookmarks menu's folder, then creates a new folder named "Folder name here" in it. Specifying DEFAU...
Places Developer Guide
id) { if (iid.equals(Ci.nsINavBookmarkObserver) || iid.equals(Ci.nsISupports)) { return this; } throw Cr.NS_ERROR_NO_INTERFACE; }, }; // Register the observer with the bookmarks service var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getService(Ci.nsINavBookmarksService); bmsvc.addObserver(observer, false); // Un-register the observer when done. bmsvc.removeObserver(observer); HTML Import/Export The nsIPlacesImportExportService service is used for import and export of bookmarks in the Netscape Bookmarks HTML format. Note that this service is only currently available for Firefox, not other toolkit-based applications. Importing: importHTMLFromFile (nsILocalFile aFile, boolean aIsInitialImport) - This imports all the bookmarks in the ...
Using the Places history service
HistoryService.removeObserver: Removes a previously added observer. nsINavHistoryService.beginUpdateBatch: Call when you will be making many small changes to the history system. Observers generally stop updating UI when they are inside a batch, potentially making the operations faster. If you are just doing a few changes, it is probably better to not use a batch since incremental updates are not done. Be sure to call endUpdateBatch when you are done or the UI will be permanently broken. nsINavHistoryService.endUpdateBatch: Ends a batch operation previously started with beginUpdateBatch. See also Manipulating bookmarks using Places ...
places.sqlite Database Troubleshooting
n places.sqlite database. How to (try to) recover from a corrupt places.sqlite Sometimes after a Firefox/Aurora/Nightly upgrade, history disappears, but bookmarks are at their place. In the profile folder a places.sqlite-corrupt file has been created. In some cases, this procedure may allow you to recover the corrupt file along with all of its contents (history). Close Firefox and ensure it's done closing in your task manager. Before you proceed, make a backup of the Firefox profile folder, in any case. Create a folder to use temporarily for this work, such as my_work_folder. Copy places.sqlite-corrupt from the Firefox profile folder to the work folder. Download the latest precompiled binary Sqlite command-line shell from: https://www.sqlite.org/download.html Extract sqlite3 execut...
Accessing the Windows Registry Using XPCOM
e desired access rights are specified using a named constant from the interface, in this example ACCESS_READ. This can be very important when dealing with non-Administrator accounts with restricted privileges. The value is read using readStringValue(). You have to specify what type of data you expect to read, which we will expand on later. Finally, note that you should close the key when you are done to avoid wasting system resources. Opening Registry Keys Before doing anything with a registry key you must first open the key you are interested in. The example above demonstates this using the open() method. If you want to create a new key, you can use the create() method, which takes the same parameters as open(). Note that it is not an error to call create() on an existing key, and doing so...
Aggregating the In-Memory Datasource
do that. Why? Because if you did, you'd hold a circular reference that would never unwind. Notes Describing all of the vagaries of XPCOM aggregation is beyond the scope of this document. The basic idea is to overload QueryInterface(), allowing it to return adelegate object that supports the interface. There is some trickery involved on the delegate's part to ensure that reference counting is done sanely, and that the reflexive, symmetric, and transitive properties of QueryInterface() are preserved. If you're really interested, I'd recommend reading about it in a COM book. For more information on writing a datasource, see the RDF Datasource How-To document. You could also forward other interfaces to the mInner that youknow it can support; however, this is extremely risky. It's risky beca...
Creating a Python XPCOM component
some details may be missing.) Preparation If a binary of PyXPCOM is not available, you will need to build it - see Building PyXPCOM. Tip: you can achieve a copy of binary of PyXPCOM from PythonExt; simply unpack xpi and take everything you need. If you wish to use PyXPCOM from a normal Python executable, you will need to tell Python where it can find the PyXPCOM library. This is probably best done by setting a PYTHONPATH variable pointing at the 'bin/python' directory in the application. This is not necessary when your components are loaded by Mozilla as the Python loader modifies sys.path. Then you can import xpcom in any Python module (mostly, in your component). Defining the interface Make a file named "nsIPySimple.idl" to define the interface: #include "nsISupports.idl" [scriptable, u...
Generic factory
tance. */ NS_IMETHOD SetConstructor(ConstructorProcPtr constructor) = 0; }; Using nsIGenericFactory is simple. Create a new instance from the repository with a CID of NS_GENERICFACTORY_CID, and and IID of NS_IGENERICFACTORY_IID. Define a constructor function that matches the ConstructorProcPtr prototype, and call nsIGenericFactory::SetConstructor with a pointer to that function. You're done. You now have a fully functional factory object. Examples class nsIComponent : public nsISupports { public: NS_IMETHOD DoSomething() = 0; }; class MyComponent : public nsIComponent { public: MyComponent(); virtual ~MyComponent(); static NS_METHOD Create(nsISupports *aOuter, REFNSIID aIID, void **aResult); NS_IMPL_ISUPPORTS NS_IMETHOD DoSomething(); }; To create a factory for t...
XPCOM glue
Mozilla › Tech › XPCOM › Glue
ne glue was removed in Gecko 6.0. Use this when you have a custom application where you want to embed Gecko to show webpages in your own window. I.e. this linkage strategy is used when an embedder needs to bootstrap XPCOM by finding a compatible GRE on disk and loading it. In order to use XPCOM, the embedding application first needs to find where the XPCOM runtime is located. This is typically done using GRE_GetGREPathWithProperties. Then, the code must call XPCOMGlueStartup, which will dynamically link against the XPCOM runtime. Only then can the embedding application initialize and use XPCOM. Embedding code which wishes to use only frozen symbols and cannot tolerate a load-time dependency on xpcom.dll should #define XPCOM_GLUE 1 while compiling, and link against xpcomglue.lib. It should ...
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
enumerator will free resultArray return NS_NewAdoptingStringEnumerator(aResult, resultArray); } As noted above, these implementations of nsIStringEnumerator can also be QueryInterface'd between nsIStringEnumerator and nsIUTF8StringEnumerator. The implementations will properly convert back and forth between UTF8 and Unicode. To ensure that you get the right implementation and the conversion is done in the right direction, make sure that you call the version of NS_NewStringEnumerator or NS_NewUTF8StringEnumerator that corresponds to the array type, not the enumerator type. For example, if a class has an internal nsTArray<nsCString> of UTF8 strings, but needs to implement an interface which returns an nsIStringEnumerator, it should use NS_NewUTF8StringEnumerator: class nsFoo : nsIFoo { ..
XPCOM changes in Gecko 2.0
tart become a thing of the past. Instead of relying on a potentially stale component cache on startup, we read the application's component registrations out of its manifest file and load those components. This gets enough of XPCOM loaded and running that we can then load the Extension Manager and perform the necessary installing, uninstalling, and updating of any installed extensions. Once that's done, the extensions can then be loaded by simply reading their manifests, loading their components, and continuing the startup process, all without having to restart the browser. Electrolysis content processes can simply read the component registrations during startup. XPCNativeWrapper changes You can't disable XPCNativeWrappers from your manifest Specifying xpcnativewrappers=no in your manifest (tha...
Component Internals
registered at startup and unregistered at shutdown. Component discovery does not currently happen automatically in non-debug builds of Gecko, however. When the registration process begins, XPCOM broadcasts to all registered observers a notification that says XPCOM has begun the registration of new components. After all components are registered, another notification is fired saying that XPCOM is done with the registration step. The nsIObserver interface that handles this notification is discussed in Starting WebLock. Once registration is complete and the notifications have fired, XPCOM is ready to be used by the application. If XPCOM registered your component, then it will be available to other parts of the XPCOM system. The XPCOM Initialization section in this chapter describes registration...
Creating the Component Code
nsIFile *aLocation, const char *aLoaderStr) = 0; RegisterSelf is called when a component is first registered with XPCOM. It is only called once, which gives you a chance to add any one time setup functionality. The RegisterSelf call allows your component to tell XPCOM exactly what it supports. Note that whatever you do in RegisterSelf should be undone in UnregisterSelf. First, the NSGetModule entry point is called in your component library, and it returns an interface pointer to a nsIModule implementation. Then XPCOM calls RegisterSelf, passing parameters that we'll examine here. The RegisterSelf Method The first parameter is the nsIComponentManager, which provides a kind of entry point into managing the registration process. You can QueryI...
Preface
are, and the first chapter - in which you compile the basic code and register it with Mozilla - prompts a discussion of the relationship between components and modules, of XPCOM interfaces, and of the registration process in general. The top of each chapter provides a list of the major topics covered. Sidebar sections are included to highlight technical details. By the end of the book, if we've done our job, you will have learned how to build a component and you will know something about the framework for these components in Gecko, which is XPCOM. Who Should Read This Book No one. It is badly out of date, and much of what it says is either no longer remotely accurate, or is severely deprecated. If you are a historian, though... Creating XPCOM Components is meant for C++ developers. Tho...
Making cross-thread calls using runnables
bad! // But thread->Shutdown must be called from the main thread, not from the thread itself. mWorkerThread->Shutdown(); } private: PiCallback mCallback; nsCString mResult; nsCOMPtr<nsIThread> mWorkerThread; }; class PiCalculateTask : public nsRunnable { public: PiCalculateTask(PiCallback callback, int digits) : mCallback(callback) ...
Detailed XPCOM hashtable guide
nd xpcom/glue/nsHashKeys.h. These classes can be used on the stack, as a class member, or on the heap. Initialize using the Init() function; you can specify whether you need thread-safety at this time. Use the Put(), Get(), and Remove() methods to alter the table. Using nsTHashtable as a hash-set A hash set only tracks the existence of keys: it does not associate data with the keys. This can be done using nsTHashtable<nsSomeHashKey>. The appropriate entries are GetEntry and PutEntry. Future Plans nsISimpleEnumerator support The (obsolete) nsHashtable has a wrapper that exposes an nsISimpleEnumerator on its items. I will add this support to the various nsBaseHashtable classes as well, as needed. Hash Functions All of the above hashtables need a Hash Function. This function converts the k...
Components.returnCode
n XPCOM caller of the JavaScript method that the method is returning a specific nsresult code. Generally, XPConnect does a fine job of making it unnecessary for JavaScript code to worry about nsresult codes. By default the successful completion of the JavaScript method will cause XPConnect to return a result code of NS_OK to the caller. If the JavaScript code needs to signal failure then that is done by throwing an exception. However, there are a very few XPCOM interfaces that specify success code return values. Components.returnCode exists in order to make it possible to implement these rare interfaces in JavaScript. Example var foo = { bar: function(i) { if (yada_yada) Components.returnCode = 5; return i * 2; } }; ...
Monitoring HTTP activity
ION) { switch(aActivitySubtype) { case nsIHttpActivityObserver.ACTIVITY_SUBTYPE_RESPONSE_HEADER: // received response header break; case nsIHttpActivityObserver.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE: // received complete HTTP response break; } } } }; Then you need to install your activity observer. ...
nsAutoRef
nsAutoRef is defined in xpcom/base/nsAutoRef.h. See Also nsAutoRefTraits, nsCountedRef ...
nsCStringEncoding
<< XPCOM API Reference Summary The nsCStringEncoding enumeration describes the set of character encodings understood by the NS_CStringToUTF16 and NS_UTF16ToCString functions. NS_CSTRING_ENCODING_ASCII Conversion between ASCII and UTF-16 assumes that all bytes in the source string are 7-bit ASCII and can be inflated to UTF-16 by inserting null bytes. Reverse conversion is done by truncating every other byte. The conversion may result in loss and/or corruption of information if the strings do not strictly contain ASCII data. NS_CSTRING_ENCODING_UTF8 Conversion between UTF-8 and UTF-16 is non-lossy. NS_CSTRING_ENCODING_NATIVE_FILESYSTEM Conversion from UTF-16 to the native filesystem charset may result in a loss of information. No attempt is made to protect against data loss in this...
nsCountedRef
nce to the resource, and in that nsCountedRef provides copy construction< and assignment operators enabling more than one concurrent reference to the same resource. In order to use nsCountedRef<T> for a class T associated with a particular resource type, the type of the handle to the resource and the methods for referencing and releasing the resource must be provided for class T. This is usually done by providing a specialization of nsAutoRefTraits<T>. nsCountedRef<T> is defined in xpcom/base/nsAutoRef.h. See Also nsAutoRef, nsAutoRefTraits ...
RefPtr
RefPtr (formerly known as nsRefPtr, see bug 1207245) is a general class to implement reference counting pointers for objects. It is similar to nsCOMPtr, but does not require that the type be an XPCOM interface. Like with nsCOMPtr, it is the responsibility of the object itself to implement reference counting. This is done using the functions AddRef() and Release(), which respectively modify a variable of type nsAutoRefCnt, which basically is a wrapper around a count of the number of references refering to the class. When should I use nsCOMPtr versus RefPtr? The rules are simple: use nsCOMPtr to hold pointers to XPCOM interfaces, and use RefPtr to hold pointers to concrete class, even if the concrete class implements one or more XPCOM interfaces. So for XPCOM interfaces: nsCOMPtr<ns...
XPCOM glue classes
nsPromiseFlatCStringClass DeclarationnsPromiseFlatStringClass DeclarationnsRefPtrRefPtr (formerly known as nsRefPtr, see bug 1207245) is a general class to implement reference counting pointers for objects. It is similar to nsCOMPtr, but does not require that the type be an XPCOM interface. Like with nsCOMPtr, it is the responsibility of the object itself to implement reference counting. ...
mozIAsyncFavicons
to reload the favicon only if we do not have it or it has expired from the cache. Setting to true causes us to reload the favicon even if we have a usable copy. aFaviconLoadType Set to nsIFaviconService.FAVICON_LOAD_PRIVATE if the favicon is loaded from a private browsing window. Set to nsIFaviconService.FAVICON_LOAD_NON_PRIVATE otherwise aCallback Optional Once we're done setting and/or fetching the favicon, we invoke this callback. replaceFaviconData() Sets the data for a given favicon URI either by replacing existing data in the database or taking the place of otherwise fetched icon data when calling setAndFetchFaviconForPage later. Favicon data for favicon URIs that are not associated with a page URI via setAndFetchFaviconForPage will be stored in memory, but ...
mozIVisitInfoCallback
be processed. void handleError( in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo ); Parameters aResultCode nsresult indicating the reason why the change failed. aPlaceInfo The information that was unable to be processed. handleResult() Called for each visit added, title change, or GUID change when passed to mozIAsyncHistory.updatePlaces(). If more than one operation is done for a given visit, this method is only called once (for all changes at once). void handleResult( in mozIPlaceInfo aPlaceInfo ); Parameters aPlaceInfo The information that was entered into the database. onComplete() Obsolete since Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) Called for each visit added, title change, or GUID change when passed to...
nsIAppShellService
These windows are generally shown in the Windows taskbar, and the application knows it can ...
nsIAutoCompleteListener
Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onAutoComplete(in nsIAutoCompleteResults result, in AutoCompleteStatus status); void onStatus(in wstring statusText); Attributes Attribute Type Description param nsISupports Private parameter used by the autocomplete widget. Methods onAutoComplete() Called by the autocomplete session when the search is done or over. As of Gecko 1.9.1, can also be called with partial results, in a similar manner to the toolkit autocomplete interface. void onAutoComplete( in nsIAutoCompleteResults result, in nsIAutoCompleteStatus status ); Parameters result An nsIAutoCompleteResults object containing the (partial) results of the autocomplete. status One of the constants defined in the nsIAutoCompleteStatus inter...
nsIChannel
tifications. If this value is null, the channel implementation may use the notification callbacks from its load group. The channel may also query the notification callbacks from its load group if its notification callbacks do not supply the requested interface. Interfaces commonly requested include: nsIProgressEventSink, nsIPrompt, and nsIAuthPrompt / nsIAuthPrompt2. When the channel is done, it must not continue holding references to this object. Note: A channel implementation should take care when "caching" an interface pointer queried from its notification callbacks. If the notification callbacks are changed, then a cached interface pointer may become invalid and may therefore need to be re-queried. originalURI nsIURI The original URI used to construct the ...
nsIChannelEventSink
eived a response of HTTP 200, which includes notifying observers and possibly display or process content attached to the HTTP response. If the sink wants to prevent this loading it must explicitly deal with it, e.g. by calling oldChannel->Cancel() There is a certain freedom in implementing this method: If the return-value indicates success, a callback on callback is required. This callback can be done from within asyncOnChannelRedirect() (effectively making the call synchronous) or at some point later (making the call asynchronous). If the return value indicates that an error occurred, in which case an exception is thrown, the redirect is vetoed and no callback must be done. void asyncOnChannelRedirect( in nsIChannel oldChannel, in nsIChannel newChannel, in unsigned long flags, in nsIA...
nsICharsetResolver
charset The detected charset. closure The closure returned by requestCharset(). requestCharset() Called to resolve the charset that should be used for parsing the document being loaded from aChannel. If the charset cannot be resolved, but the implementation of nsICharsetResolver wants to be notified of the final resolved charset when one is available, it can set aWantCharset to true. If this is done, the caller of requestCharset is responsible for calling notifyResolvedCharset() and passing it the final resolved charset and the closure that requestCharset set. ACString requestCharset( in nsIWebNavigation aWebNavigation, in nsIChannel aChannel, out boolean aWantCharset, out nsISupports aClosure ); Parameters aWebNavigation The nsIWebNavigation the document is being loaded in. May be...
nsICommandLine
ag name to find and remove. aCaseSensitive Whether to do case-sensitive flag search. Return value The value of the specified flag, an empty string if the flag's value is the empty string, or null if the specified parameter wasn't found. Exceptions thrown NS_ERROR_INVALID_ARG The specified flag has no value. removeArguments() Removes a range of arguments from the command line; this is typically done once those arguments have been handled. void removeArguments( in long aStart, in long aEnd ); Parameters aStart The index to the first argument to remove from the command line; this is 0-based, and the name of the application is not included. aEnd The index to the last argument to remove from the command line. resolveFile() Resolves a file-path argument into an nsIFile object. This method ...
nsIConsoleService
sage ); Parameters message The nsIConsoleMessage to log. logStringMessage() A convenient method for logging simple messages. void logStringMessage( in wstring message ); Parameters message The string to log. registerListener() Registers a listener, to notify when an error is logged. Note: To guard against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in JavaScript), we do not call any listeners when another error is already being logged. void registerListener( in nsIConsoleListener listener ); Parameters listener The nsIConsoleListener to add. reset() To clear the message buffer (For example, for privacy reasons): void reset(); Parameters None. Note: Console listeners expect you to ...
nsICookieConsent
the policy for the given URI and channel is also returned. ...
nsICookiePermission
this value unchanged to preserve this attribute of the cookie. aExpiry When canSetCookie is invoked, this is the current expiry time of the cookie. canSetCookie may leave this value unchanged to preserve this attribute of the cookie. Return value true if the cookie can be set. getOriginatingURI() Determines the originating URI for a load given a channel, for third-party cookie blocking. This is done by leveraging the loadgroup of the channel to find the root content docshell, and the URI associated with its principal. If the root content docshell or its principal's URI cannot be obtained, this method will throw. nsIURI getOriginatingURI( in nsIChannel aChannel ); Parameters aChannel The channel for the load trying to get or set cookies. Return value The originating URI. setAccess() Sets...
nsICookieService
Data cookie-changed Broadcast whenever the cookie list changes in some way. There are four possible data strings for this notification; one notification will be broadcast for each change. Depending on the Data value, either an nsICookie2 interface pointer representing the cookie object that changed, or an nsIArray of nsICookie2 objects. A keyword indicating what was done to the affected cookie. deleted A cookie was deleted. The subject is the deleted cookie. added A cookie was added. The subject is the added cookie. changed A cookie was changed. The subject is the changed cookie. batch-deleted A set of cookies were deleted as part of a purge operation. This typically happens because they have either expired or because ...
nsIDNSService
service;1. To access the service, use: var dnsService = Components.classes["@mozilla.org/network/dns-service;1"] .createInstance(Components.interfaces.nsIDNSService); Note: Starting in Gecko 7.0, the "happy eyeballs" strategy is used to reduce lengthy timeouts when attempting backup connections during attempts to connect from clients that have broken IPv6 connectivity. This is done by disabling IPv6 on backup connections. Method overview nsICancelable asyncResolve(in AUTF8String aHostName, in unsigned long aFlags, in nsIDNSListener aListener, in nsIEventTarget aListenerTarget); void init(); Obsolete since Gecko 1.8 nsIDNSRecord resolve(in AUTF8String aHostName, in unsigned long aFlags); void shutdown(); Obsolete since Gecko 1.8 Att...
nsIDOMEvent
x00000200 KEYPRESS 0x00000400 DRAGDROP 0x00000800 FOCUS 0x00001000 BLUR 0x00002000 SELECT 0x00004000 CHANGE 0x00008000 RESET 0x00010000 SUBMIT 0x00020000 SCROLL 0x00040000 LOAD 0x00080000 UNLOAD 0x00100000 XFER_DONE 0x00200000 ABORT 0x00400000 ERROR 0x00800000 LOCATE 0x01000000 MOVE 0x02000000 RESIZE 0x04000000 FORWARD 0x08000000 HELP 0x10000000 BACK 0x20000000 TEXT 0x40000000 ALT_MASK 0x00000001 CONTROL_MASK 0x00000002 ...
nsIDownloadManagerUI
unsigned long aID, [optional] in short aReason); Attributes Attribute Type Description visible boolean true if the Download Manager UI is visible; otherwise false. Read only. Constants Constant Value Description REASON_USER_INTERACTED 0 When opening the Download Manager user interface, this value indicates that it's being done at the user's request. REASON_NEW_DOWNLOAD 1 When opening the Download Manager user interface, this value indicates that the user interface is being displayed because a new download is being started. Methods getAttention() Calls attention to the Download Manager's user interface if it's already open. The UI need not be visible to call this function, nor will the UI be made...
nsIFileInputStream
lose automatically when the end of the file is reached. REOPEN_ON_REWIND 1<<3 If this is set, the file will be reopened whenever Seek(0) occurs. If the file is already open and the seek occurs, it will happen naturally. (The file will only be reopened if it is closed for some reason.) DEFER_OPEN 1<<4 If this is set, the file will be opened (i.e., a call to PR_Open() done) only when we do an actual operation on the stream, or more specifically, when one of the following is called: Seek() Tell() Available() Read() ReadLine() DEFER_OPEN is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. Note: Using this flag results in the file not being opene...
nsIFilePicker
rent, in AString title, in short mode ); Parameters parent The nsIDOMWindow parent. This dialog will be dependent on this parent. Must be non-null. title The file picker dialog title. If this is null, the dialog will have the default title. mode One of the mode constants, indicating the type of picker to create. open() Opens the file dialog asynchrounously. The passed in object's done method will be called upon completion. void open( in nsIFilePickerShownCallback aFilePickerShownCallback ); Parameters aFilePickerShownCallback The nsIFilePickerShownCallback to be called on completion. show() Obsolete since Gecko 57.0 (Firefox 57.0 / Thunderbird 57.0 / SeaMonkey 2.54) Displays the file picker dialog. The dialog is displayed modally. short s...
nsIFocusManager
cus( in nsIDOMWindow aWindow ); Parameters aWindow elementIsFocusable() Check if given element is focusable. boolean elementIsFocusable(in nsIDOMElement aElement, in unsigned long aFlags); Parameters aElement aFlags Return value True if aElement is focusable. moveFocus() Move the focus to another element. If aStartElement is specified, then movement is done relative to aStartElement. If aStartElement is null, then movement is done relative to the currently focused element. If no element is focused, focus the first focusable element within the document (or the last focusable element if aType is MOVEFOCUS_END). This method is equivalent to setting the focusedElement to the new element. Specifying aStartElement and using MOVEFOCUS_LAST is not currently...
nsIHttpHeaderVisitor
, in ACString aValue ); Parameters aHeader A string containing the key for a header such as "Content-Type" aValue The header's value field such as "text/html". Multiple values are separated by a comma. Example This example shows how to detect Flash content. It implements the nsIHttpHeaderVisitor Interface in JavaScript and uses it to evaluate the mime type of a http response. This is done by subscribing to the http-on-examine-response and http-on-examine-cached-response observers. When the observer fires, the visitor interface is used to walk through the response headers and evaluate the MIME type. myNsIHttpHeaderVisitor = function ( ) { this._isFlash = false; }; myNsIHttpHeaderVisitor.prototype.visitHeader = function ( aHeader, aValue ) { if ( aHeader.indexOf( "C...
nsIHttpServer
when * served by this server, in the absence of any file-specific information * about the desired Content-Type. If type is empty, removes any extant * mapping, if one is present. * * @throws NS_ERROR_INVALID_ARG * if the given type is not a valid header field value, i.e. if it doesn't * match the field-value production in RFC 2616 * @note * No syntax checking is done of the given type, beyond ensuring that it is * a valid header field value. Behavior when not given a string matching * the media-type production in RFC 2616 section 3.7 is undefined. * Implementations may choose to define specific behavior for types which do * not match the production, such as for CGI functionality. * @note * Implementations MAY treat type as a trust...
nsIINIParserWriter
indicates the file into which the INI data will be written. Once the writer object is created, you can use the setString() method to set the value of a property within a given section; the section is created if it hasn't been yet. The sections are built in memory before the text of the INI file is generated, so you can add properties to the file in any order, regardless of section. When you're done and ready to write the INI file to disk, call the writeFile() method. Method overview void setString(in AUTF8String aSection, in AUTF8String aKey, in AUTF8String aValue); void writeFile([optional] in nsIFile aINIFile, [optional] in unsigned long aFlags); Constants File writing constants These constants are specified when calling writeFile(), in order to change its beh...
nsIIOService
boolean allowPort( in long aPort, in string aScheme ); Parameters aPort The port to check aScheme The scheme for the protocol handler that could override the IOService's decision. Return value true if the port is allowed, false otherwise. extractScheme() Utility to extract the scheme from a URL string, consistently and according to spec (see RFC 3986). Note: Most URL parsing is done via nsIURI, and in fact the scheme can also be extracted from a URL string via nsIURI. This method is provided purely as an optimization. ACString extractScheme( in AUTF8String urlString ); Parameters urlString The string for the URL to extract the scheme from. Return value A string corresponding to the scheme. Exceptions thrown NS_ERROR_MALFORMED_URI If URL string is not of the...
Using nsILoginManager
orrespond to a login on http://www.example.com when the server sends a reply such as: HTTP/1.0 401 Authorization Required Server: Apache/1.3.27 WWW-Authenticate: Basic realm="ExampleCo Login" Creating a local extension login var extLoginInfo = new nsLoginInfo( 'chrome://firefoo', null, 'User Registration', 'bob', '123sEcReT', "", "" ); From a component creating a new info block is done slightly differently: var nsLoginInfo = new Constructor("@org/manager/Ci.init"); var extLoginInfo = new aFormSubmitURL, aUsername, aUsernameField, ...
nsILoginManagerStorage
oldLogin The login to be modified. newLoginData The login information to replace the oldLogin with. This may be specified as either an nsILoginInfo or an nsIPropertyBag2 object. removeAllLogins() Implement this method to remove all logins from the login store. This is called by the browser sanitization feature when the user asks to clear all stored passwords. The user interface allows this to be done without getting each login first (which might require knowing the master password). No password should be required in order to remove all logins. void removeAllLogins(); Parameters None. removeLogin() Implement this method to remove the specified login from the login store. Gecko 1.9.1 note The values of any nsILoginMetaInfo properties are ignored. void removeLogin( in nsILoginInfo aLogi...
nsIMemoryReporter
n for a single area of the software. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) Any piece of code that wishes to allow its memory use to be monitored may create an nsIMemoryReporter object and then register it by calling nsIMemoryReporterManager.registerReporter(). Once that has been done, the reporter will be found by any client accessing the enumerator returned by nsIMemoryReporterManager.enumerateReporters(). This includes the about:memory page. Note: This interface is undergoing heavy development, and is subject to rapid changes. Attributes Attribute Type Description amount PRInt64 The numeric value reported by the memory reporter, specifie...
nsIMsgCustomColumnHandler
getSortStringForRow(in nsIMsgDBHdr aHdr); unsigned long getSortLongForRow(in nsIMsgDBHdr aHdr); boolean isString(); Methods getSortStringForRow() If the column displays a string, this will return the string that the column should be sorted by. AString getSortStringForRow(in nsIMsgDBHdr aHdr); Parameters aHdr The message's nsIMsgDBHdr. Return value The string value that sorting will be done with. getSortLongForRow() If the column displays a number, this will return the number that the column should be sorted by. unsigned long getSortLongForRow(in nsIMsgDBHdr aHdr); Parameters aHdr The message's nsIMsgDBHdr. Return value The long value that sorting will be done with. isString() boolean isString(); Parameters None. Return value true if the column displays a string value. false o...
nsIMsgDatabase
mpareCollationKeys() [noscript] long compareCollationKeys(in octetPtr key1, in unsigned long len1, in octetPtr key2, in unsigned long len2); getNewList() The list of messages currently in the NEW state. If there are no such messages, null may be returned. The caller should free when done using nsMemory.Free(). void getNewList(out unsigned long count, [array, size_is(count)] out nsMsgKey newKeys); getCachedHits() These are used for caching search hits in a database, to speed up saved search folders. nsISimpleEnumerator getCachedHits(in string aSearchFolderUri); refreshCache() void refreshCache(in string aSearchFolderUri, in unsigned long aN...
nsIMsgFilterCustomAction
*/ readonly attribute boolean isAsync; /// Does this action need the message body? readonly attribute boolean needsBody; }; ...
nsIMsgMessageService
inal url associated with the msg. aMessageUri RDF resource that describes the message aDisplayConsumer MsgWindow nsIMsgWindow for progress and status feedback aUrlListener An nsIUrlListener. SaveMessageToDisk() When you want to spool a message out to a file on disk. This is an async operation of course.Note: You must pass in a url listener in order to figure out when the operation is done. void SaveMessageToDisk(in string aMessageURI, in nsIFileSpec aFile, in boolean aGenerateDummyEnvelope, in nsIUrlListener aUrlListener, out nsIURI aURL, in boolean canonicalLineEnding, in nsIMsgWindow aMsgWindow); Parameters aMessageURI Url repres...
nsIMsgSearchNotify
Defined in comm-central/ mailnews/ base/ search/ public/ nsIMsgSearchNotify.idl [scriptable, uuid(ca37784d-352b-4c39-8ccb-0abc1a93f681)] interface nsIMsgSearchNotify : nsISupports { void onSearchHit(in nsIMsgDBHdr header, in nsIMsgFolder folder); // notification that a search has finished. void onSearchDone(in nsresult status); /* * until we can encode searches with a URI, this will be an * out-of-bound way to connect a set of search terms to a datasource */ /* * called when a new search begins */ void onNewSearch(); }; ...
nsINavBookmarkObserver
the item. aParentGUID The unique ID associated with the item's parent. onBeginUpdateBatch() This method notifies this observer that a batch transaction has started. Other notifications will be sent during the batch change, but the observer is guaranteed that onEndUpdateBatch() will be called at the completion of changes. During a batch the observer should do its best to reduce the work done to handle notifications, since multiple changes are going to happen in a short timeframe. void onBeginUpdateBatch(); Parameters None. onEndUpdateBatch() This method notifies this observer that a batch transaction has ended. void onEndUpdateBatch(); Parameters None. onFolderAdded() Obsolete since Gecko 1.9 (Firefox 3) Notify this observer that a bookmark folder has been...
nsINavBookmarksService
index ); Parameters aParentFolder The ID of the parent folder. name The name of the new folder. index The index to insert at, or DEFAULT_INDEX to append to the end of the list. Return value Returns the ID of the newly-inserted folder. endUpdateBatch() Obsolete since Gecko 1.9 (Firefox 3) Causes observers to be notified of an endUpdateBatch when a batch is done changing. Should match beginUpdateBatch() or bad things will happen. void endUpdateBatch(); Parameters None. exportBookmarksHTML() Obsolete since Gecko 1.9 (Firefox 3) Saves the current bookmarks hierarchy to a bookmarks.html file. void exportBookmarksHTML( in nsIFile file ); Parameters file The nsIFile to export the bookmarks to. getBookmarkedURIFor() ...
nsINavHistoryContainerResultNode
rReadOnly() method has been called to specifically make the folder read-only. It's true for non-folder nodes. If this container is a remote container, this flag may be redefined by the remote container provider. Read-only. containerOpen boolean Set this to true to allow descent into this container. When closed, attempting to call getChild() or access childCount results in an error. When you're done reading the container's children, set this to false. For HOST and DAY groupings, doing this has no performance cost since the children have already been computed. For queries and bookmark folders, however, being open means they must keep themselves up-to-date by listening for updates and re-querying as needed. dynamicContainerType AUTF8String A string representing the dynamic container API ser...
nsINavHistoryQuery
psulates all the query parameters you're likely to need when building up history UI. All parameters are ANDed together. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) The nsINavHistoryQuery is not intended to be a super-general query mechanism. This was designed so that most queries can be done in only one SQL query. This is important because, if the user has their profile on a networked drive, query latency can be non-negligible Method overview nsINavHistoryQuery clone(); void getFolders([optional ]out unsigned long count, [retval,array,size_is(count)] out long long folders); void getTransitions([optional] out unsigned long count, [retval,array,size_is(count)] out unsigned lon...
nsIObserver
Service = 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). observer = new myObserver(); Destruction - this should be fired once you're done observing (for example a window's unload event). Failure to do so may result in memory leaks. observer.unregister(); "Get Everything" - note that "*" is an acceptable value (be careful with this, because it observes many events, and can degrade performance). observer.register("*"); See also nsIObserverService Observer_Notifications ...
nsISHEntry
upports owner, in unsigned long long docshellID, in boolean dynamicCreation ); Parameters URI title inputStream layoutHistoryState cacheKey contentType owner docshellID dynamicCreation Violates the XPCOM interface guidelines forgetEditorData() Gets the owning pointer to the editor data assosicated with this shistory entry. This forgets its pointer, so free it when you're done. nsDocShellEditorDataPtr forgetEditorData(); Parameters None. Return value getAnyContentViewer() Return any content viewer present in or below this node in the nsSHEntry tree. This will differ from contentViewer in the case where a child nsSHEntry has the content viewer for this tree. nsIContentViewer getAnyContentViewer( out nsISHEntry ownerEntry ); Parameters ownerEntry Return value ge...
nsIScriptableIO
mode isn't specified, an exception is thrown if no data is available. deleteonclose: The file is automatically deleted when the stream is closed. This can be useful for temporary files. closeoneof: The file is automatically closed when the end of the file is reached. reopenonrewind: Used in conjunction with the seek mode, the file will be reopened when a seek to the beginning of the file is done. multi: The resulting stream is one which is used to concatenate the input from multiple streams as if they were one long, continuous stream. The returned stream implements the nsIMultiplexInputStream interface. This mode may not be used in conjunction with the text or buffered modes. aCharSet The character set to use for interpreting the text data being read. Used only in conju...
nsITaskbarTabPreview
on Microsoft Windows to control tab preview specific behavior. 1.0 66 Introduced Gecko 1.9.2 Inherits from: nsITaskbarPreview Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Tab preview support is disabled by default in Gecko 1.9.2 Creating an nsITaskbarTabPreview for a window will automatically hide that window's nsITaskbarWindowPreview; this is done by Windows and cannot be prevented. When there are no more tab previews left for a window, the window preview is automatically made visible again. An application may have as many tab previews as memory allows. You can't directly instantiate this interface; instead, call the nsIWinTaskbar.createTaskbarTabPreview(). Method overview void EnsureRegistration(); Violates the XPCOM interfac...
nsIURI
protocol handler implementation, since doing so will generally lead to unpredictable results. spec AUTF8String Returns a string representation of the URI. Setting the spec causes the new spec to be parsed using the rules for the scheme the URI currently has. If the string cannot be parsed as a URI, NS_ERROR_MALFORMED_URI thrown. Warning: Because parsing the string is done using the current URI's scheme, setting the spec to a URI with a different scheme will produce incorrect results. Therefore, only protocol handler implementations should do this. If the URI stores information from the nsIIOService interface's nsIIOService.newURI() call that created it, other than just the parsed string, the behavior of this information when setting the spec attribute is unde...
nsIWebBrowserFindInFrames
embedding/components/find/public/nsIWebBrowserFind.idlScriptable Controls how find behaves when multiple frames or iframes are present. Inherits from: nsISupports Last changed in Gecko 1.7 Get an instance by doing a QueryInterface from nsIWebBrowserFind. Attributes Attribute Type Description currentSearchFrame nsIDOMWindow Frame at which to start the search. Once the search is done, this will be set to be the last frame searched, whether or not a result was found. Has to be equal to or contained within the rootSearchFrame. rootSearchFrame nsIDOMWindow Frame within which to confine the search (normally the content area frame). Set this to only search a subtree of the frame hierarchy. searchParentFrames boolean Whether to allow the search to propagate out of the currentS...
nsIWebBrowserPersist
ple for text fields). ENCODE_FLAGS_WRAP 32 Wrap documents at the specified column. ENCODE_FLAGS_FORMAT_FLOWED 64 For plain text output. Output for format flowed (RFC 2646). This is used when converting to text for mail sending. This differs just slightly but in an important way from normal formatted, and that is that lines are space stuffed. This can't (correctly) be done later. ENCODE_FLAGS_ABSOLUTE_LINKS 128 Convert links to absolute links where possible. ENCODE_FLAGS_ENCODE_W3C_ENTITIES 256 Attempt to encode entities standardized at W3C (HTML, MathML, and so on.). This is a catch-all flag for documents with mixed contents. Beware of interoperability issues. See below for other flags which might likely do what you want. ENC...
nsIWebNavigationInfo
ts.interfaces.nsIWebNavigationInfo); Method overview unsigned long isTypeSupported(in ACString aType, in nsIWebNavigation aWebNav); Constants Support type constants Constant Value Description UNSUPPORTED 0 Returned by isTypeSupported() to indicate lack of support for a type. Note: This is guaranteed not to change, so that boolean tests can be done on the return value if isTypeSupported to detect whether a type is supported at all. IMAGE 1 Returned by isTypeSupported() to indicate that a type is supported as an image. PLUGIN 2 Returned by isTypeSupported() to indicate that a type is supported via an NPAPI ("Netscape 4 API") plug-in. This is not the value returned for "XPCOM plug-ins". OTHER 1 << 15 ...
nsIXMLHttpRequest
erface definition: //github.com/RealityRipple/UXP/blob/master/dom/xhr/nsIXMLHttpRequest.idl Elevated Privileges As mentioned in the "Non-Standard Properties" the property of channel was read-only. When using the XPCOM interface, as seen below in Example 2, we can get access to this. The most obvious benefit is that we can set nsiRequest - Constants in the xhr.channel.loadFlags. For instance, as done in Example 2, the flag of LOAD_ANONYMOUS is added, this strips all user data (cookies, tokens, etc). Using event handlers from native code (Not sure if it's up-to-date) From native code, the way to set up onload and onerror handlers is a bit different. Here is a comment from Johnny Stenback <jst@netscape.com>: The mozilla implementation of nsIXMLHttpRequest implements the interface nsIDOMEven...
nsIXULTemplateBuilder
ing the starting reference point, determined by calling the query processor's translateRef method with the root node's ref attribute as an argument. queryProcessor nsIXULTemplateQueryProcessor [noscript] Readonly: The query processor used to generate results. Methods rebuild() Force the template builder to rebuild its content. All existing content will be removed first. The query processor's done() method will be invoked during cleanup, followed by its initializeForBuilding() method when the content is to be regenerated. void rebuild(); Parameters None. refresh() Reloads any RDF datasources that support nsIRDFRemoteDatasource. Note: This is a temporary hack so that remote-XUL authors can reload remote datasources. When RDF becomes remote-scriptable, this will no longer be necessary. void ...
Setting HTTP request headers
de up HTTP header is X-Hello and NOT Hello because we correctly added the X- in front of our name.) No longer the case: http://tools.ietf.org/html/rfc6648 Notifications The question that may be coming to your mind right now is, how do you get the nsIHttpChannel when an HTTP request is made. In the case your code initiates the request, you probably already have one. Trapping other requests is done with notifications, which are a lot like events or signals found in other languages and frameworks. In particular, to get the nsIHttpChannel just before the HTTP request is made we need to observe the "http-on-modify-request" topic. (And yes, "http-on-modify-request" is a string.) NOTE: There are many topics, besides just "http-on-modify-request", that you can get notifications about, for examp...
Performance
p the cache active between transactions, you needed to have a second connection with a 'dummy' (and schema changing) transaction. That is not needed now. You can control the size of the memory cache using the cache_size pragma. This value controls the number of pages of the file that can be kept in memory at once. The page size can be set using the page_size pragma before any operations have been done on the file. You can see an example of setting the maximum cache size to be a percentage of memory in nsNavHistory::InitDB in toolkit/components/places/src/nsNavHistory.cpp. Sharding the cache between connections By default, Storage enables the sqlite shared-cache mode which makes multiple connections to the same database share the same cache. The cache is threadsafe. All you need to do is use Se...
XPCOM tasks
ng nsAVLTree nsHashtable our various array classes In some cases, this might initially be provided by additional interfaces. In all cases, we want to transition the primary APIs toward the standard. P2 Our various enumerator classes should be made compatible with the enumerators from the Standard C Library, so that we can apply the standard algorithms to our containers. This is probably best done with a C wrapper around an XPCOM enumerator. P2 Do we still require our own version of QuickSort? And if so, can we narrow it to only those platforms that need it? P3 We need to check for aggregation in CreateInstance(). See bug 16763 P3 Improve the performance of the registry. Explore the idea of using a separate registry. 5.1 If the build hierarchy were fixed, the Registry could exploit exp...
Xptcall Porting Guide
on call overhead is a tiny part of the time involved. I put together xptcall/src/md/test as a place to evolve the basic functionality as a port is coming together. Not all of the functionality is exercised, but it is a place to get started. xptcall/tests has an api level test for NS_InvokeByIndex, but no tests for the stubs functionality. Such a test ought to be written, but this has not yet been done. A full 'test' at this point requires building the client and running the XPConnect test called TestXPC in mozilla/js/src/xpconnect/tests. Getting these ports done is very important. Please let me know if you are interested in doing one. I'll answer any questions as I get them. Porting Status Original Author: John Bandhauer, 31 May 1999. ...
pyxpidl
elib.py, which generates XPT files. pyxpidl requires a directory to cache certain information in. You can use a temporary directory or the current directory or whatever works best for you. Generating C++ headers To generate C++ headers, use the header.py utility: sdkdir/sdk/bin/header.py --cachedir=<path> -o <outputfilename.h> <filename.idl> Generating typelibs Generating typelib files is done using the typelib.py utility: sdkdir/sdk/bin/typelib.py --cachedir=<path> -o <outputfilename.xpt> <filename.idl> Comparing pyxpidl to xpidl This table provides a mapping of old xpidl options to pyxpidl. xpidl option Description pyxpidl equivalent -a Emit annotations to typelib n/a (feature removed) -w Turn on warnings n/a (this is now the default ...
Xray vision
s which are themselves objects, and these objects are same-origin with the content, then their value properties are visible as well. There are two main sorts of restrictions: First, the chrome code might expect to rely on the prototype's integrity, so the object's prototype is protected: the Xray has the standard Object or Array prototype, without any modifications that content may have done to that prototype. The Xray always inherits from this standard prototype, even if the underlying instance has a different prototype. if a script has created a property on an object instance that shadows a property on the prototype, the shadowing property is not visible in the Xray Second, we want to prevent the chrome code from running content code, so functions and accessor properties o...
Address Book examples
openDialog. Using the propertiesChromeURI means that the different implementations can call up their own dialog. window.openDialog(addressbook.propertiesChromeURI, "editDirectory", "chrome,modal=yes,resizable=no", {selectedDirectory: addressbook}); How do I set up my own address book? As of Thunderbird 7.0, implementing your own address book type can be done with either JavaScript or with a binary component. In either case, you'll need: A factory object implementing nsIAbDirFactory A directory object implementing nsIAbDirectory If you are using C++, you can inherit from nsAbDirProperty and override functions for your specific implementation to save implementing all the functions on nsIAbDirectory yourself. The best example of a binary implement...
Index
ape.com> Contents 37 Mail event system Mozilla mail requires an event system to notify different subsystems that data has changed. This document describes the system that events are passed amongst the mail objects. 38 MailNews Filters MailNews, thunderbird Mailnews filters consist of a set of search terms, and a set of filter actions. Filter execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match. For new incoming messages, the protocol specific object that handles new messages calls nsIMsgFilterList::ApplyFiltersToHdr and passes itself in as nsIMsgFilterHitNotify interface to handle filter hits. E.g., IMAP, POP3. 39 MailNews Protocols MailN...
Mail event system
or something. Then we could // verify that our listener fired by checking if listenerHasFired and // totalMessagesListenerHasFired are true // this is left as an exercise for the reader. Future plans The notification system has two duplicate methods which could be implemented with OnItemEvent/NotifyItemEvent: FolderLoaded , and DeleteOrMoveMessagesCompleted . Both of these could be done by making atoms for each of these events and just firing it with NotifyItemEvent. Completed There are some of redundant methods between the nsIMsgMailSession and the nsIFolderListener interfaces. nsIMsgMailSession also contains a number of other methods that are completely unrealted to folder notification. It would make sense to collapse the nsIMsgMailSession simply into an object that implemen...
Mailnews and Mail code review requirements
le to which the test corresponds. A bug is still required, even if it is immediately marked fixed. rs=orange-debugging Requirements: The patch is trying to fix an intermittent orange test failure. The patch only touches test logic. The patch only adds/modifies logging statements, although the logs can be conditional. The patch must have been run at least once on the try server. (I have done some mozmill orange fixing where the try server would not duplicate the orange failures of the trunk and so in order to get the enhanced logging, the changes need to go into the trunk.) The patch is authored by the module owner/a peer for the affected test. There must be an associated bug tracking the orange bug to be fixed. Mailnews individuals and roles Mail individuals and roles ...
Thunderbird Configuration Files
with userChrome.css, this folder does not exist by default, so you need to create it before you can start adding your preferences. user.js This is the additional preferences file for Thunderbird and is located in your profile folder. The file does not exist by default, so you need to create it before you can start adding your preferences. In almost all cases, edits made using the user.js can be done via the Config Editor, which is the recommended method. Windows users: If you know how to create a file, just skip this section. Before you can create the file, you must make sure that you can see the file type extensions in Windows. Start Explorer (just click on the My Computer icon on your desktop) and select Tools > Folder Options. Click the View tab and uncheck the Hide extensions for known ...
Creating a Custom Column
} In this example we have a function addCustomColumnHandler() that is called whenever the event is fired. This function is a simple one liner along the lines of: function addCustomColumnHandler() { gDBView.addColumnHandler("colReplyTo", columnHandler); } Wrap Up As you have seen it is quite easy to add your own custom column handler. Most of the dirty tasks (displaying and sorting) are done for you in the background - so that all that's left to you, the Extension developer is to populate the code with your feature. Don't forget that columns aren't restricted to text - they can also load images (via getImageSrc()) so that your extension can display a new visual cue to the user. As you develop your custom extension, please revisit this article and add any helpful hints that you find...
Finding the code for a feature
Frequently you are trying to figure out the code that implements a specific feature of the user interface. How do you find that out? As an example, I received the following inquiry, and I decided to follow my usual path and document what I do: Hello i would like to add colours and tags to specific emails...by using nsiMsgTagService, can this be done? Here is my (edited) response: nsIMsgTagService is used to store the list of valid tags, so it is not the correct way to tag messages. Tags are applied using the message database property "keyword". I know the underlying code, but I don't remember the user interface level function to do it. But here is how I find out. There are two key tools that you need. The first is the DOM inspector extension which I have routinely installed in all of my T...
Filter Incoming Mail
tService(Components.interfaces.nsIMimeConverter); var subject = mimeConvert.decodeMimeHeader(aMsgHdr.subject, null, false, true); // Here with have a string to modify with Javascript. ...
Virtualenv
he same functionality. It will require it to be part of a clone of the github repository or have internet access to fetch setuptools. On Mac OS X, you will need Xcode to use virtualenv. See this article for details. Using Virtualenv Once you have virtualenv installed, you can make virtual environments: > virtualenv tmp New python executable in tmp/bin/python Installing setuptools............done. Installing pip...............done. A python binary, as well as easy_install and pip are available in the bin/ subdirectory (or Scripts on windows). > ls tmp/bin/ activate activate.fish easy_install pip python activate.csh activate_this.py easy_install-2.7 pip-2.7 Using this python binary, or these scripts (which point to this python binary), you will correctly install ...
Working with windows in chrome code
er window. The DOM tree, as shown by the DOM Inspector, can look like this: #document window main-window ... browser #document window myExtensionWindow where the child window is where your code runs in. Your task is to access elements above your chrome document, i.e. to break out of your chrome window and access the ancestors. ...
Declaring and Using Callbacks
that funcPtrType is a type of function pointer, and adds a special case to its constructor. In the ordinary case, invoking the type object creates a regular CData object containing a pointer to the data. However, if the first argument is a function, js-ctypes creates a special object (known internally as a CClosure) that wraps the JavaScript function within an ordinary C function. This can all be done in a single line of code, like so: var callback = ctypes.FunctionType(...).ptr(function(...) {...}); Note: The use of .ptr() here isn't a method call; we're accessing a property that dynamically creates a callable object, and then invoking the result. If two arguments are passed to the callback constructor, the second is used as the this parameter: function myJSCallback() { alert(this.mess...
Declaring types
pointer to a FILE record. Declaring an array type with a specific length Declaring an array type that specifies the array length is as simple as adding a length when calling ctypes.ArrayType(), like this: const FileArray = new ctypes.ArrayType(FILE, 20); This declares FileArray as an array type that can hold 20 elements. ...
Memory Management
an array will hold the referent objects alive. What won't keep objects alive It's important to note that getting direct access to the contents of a CData object using address(), addressOfElement(), or contents, will result in a CData object that does not hold its referent alive. Be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it. Closures You also need to be sure to retain references to any JavaScript code that native code may call back into. This should be obvious, but is important enough to be worth stating explicitly. When in doubt, malloc() When you need to keep data around, you can use malloc() to allocate it directly. This bypasses JavaScript's memory management and lets you handle memory management yo...
Standard OS Libraries
-C js-ctypes snippets that can be copied and pasted to scratchpad Android Android runs on Java and can be used by js-ctypes through the JNI libraries. Thankfully all the js-ctypes was abstracted away into JNI.jsm. Undrestanding js-ctypes is important as arrays and other features used in JNI.jsm will require us to create arrays from the types available to the ctypes.jsm module. Although JNI is done completely through js-ctypes, a JSM was created to abstract away the js-ctypes so developers can focus on the JNI aspect. Therefore elaboration on this technique is not done in the js-ctypes section but it is done in the JNI.jsm article. This article links to a fully funcitonal demo that can be copied and pasted into scratchpad, as a quick reference here is the link to that demo: Following the An...
ctypes
int C type on the platform. unsigned_int An unsigned integer type that behaves like the unsigned int C type on the platform. long A long integer type that behaves like the corresponding C type on the platform. NOTE This automatically converts to an Int64 JavaScript object on all platforms, since it's unknown whether this is a 32-bit or 64-bit value. This is done for compatibility's sake. unsigned_long An unsigned long integer type that behaves like the corresponding C type on the platform. NOTE This automatically converts to a UInt64 JavaScript object on all platforms, since it's unknown whether this is a 32-bit or 64-bit value. This is done for compatibility's sake. long_long A integer type at lea...
Flash Activation: Browser Comparison - Plugins
ir choice: Site Authoring Tips If a Flash element is very small, hidden, or covered by other content, users will probably not notice that Flash is required and will become confused. Even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. ...
Constants - Plugins
ch. NPERR_INVALID_PARAM 9 Parameter missing or invalid. NPERR_INVALID_URL 10 URL missing or invalid. NPERR_FILE_NOT_FOUND 11 File missing or invalid. NPERR_NO_DATA 12 Stream contains no data. NPERR_STREAM_NOT_SEEKABLE 13 Seekable stream expected. Result Codes Constant Value Description NPRES_DONE 0 (Most common): Completed normally; all data was sent to the instance. NPRES_NETWORK_ERR 1 Stream failed due to problems with network, disk I/O, lack of memory, or other problems. NPRES_USER_BREAK 2 User canceled stream directly by clicking the Stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operatio...
Plug-in Development Overview - Plugins
nderbird 10.0 / SeaMonkey 2.7), you can get the origin of the document in a secure, convenient way by calling NPN_GetValue() to retrieve the value of the variable NPNVdocumentOrigin. The returned value is the Unicode serialization of the document's origin converted to NFKC-encoded (that is, normalized) UTF-8. Your plug-in must free the returned string's memory by calling NPN_MemFree() when you're done with it. Getting Version and UI Information The Netscape group of Plug-in API methods provides some basic services to the plug-in. You can use these Netscape methods: To identify the browser in which your plug-in is displayed: Use the NPN_UserAgent method to read this information. To determine whether plug-in and the browser versions are compatible and possibly provide alternative processin...
Scripting plugins - Plugins
NPObject (which is created by calling NPN_CreateObject) when the browser requests it by calling: NPP_GetValue(npp, NPPVpluginScriptableNPObject, ...); Accessing browser objects from a plugin A plugin that wishes to access objects in the browser window that loaded the plugin can do this by getting the NPObject for the browser's window object, or the DOM element that loaded the plugin. This is done by using an extension to NPN_GetValue. The extensions are two additions to the NPNVariables enumeration; the new enumerations are NPNVWindowNPObject and NPNVPluginElementNPObject. Calling NPN_GetValue() with either of those new enumerations will return an NPObject representing the browser object, and from there, the functions in this API can be used to get and set properties, and to call methods ...
Accessibility Inspector - Firefox Developer Tools
accessing information because of any disability they may have, or any other personal circumstances such as the device they are using, the speed of their network connection, or their geographic location or locale. You can find more extensive information in the Accessibility section of MDN Web Docs. Here we are mainly talking about exposing information to people with visual disabilities -- this is done via the accessibility APIs available inside web browsers, which expose information on what roles the different elements on your page play (e.g., are they just text, or are they buttons, links, form elements, etc.?). Semantic DOM elements have roles assigned to them by default that hint at what their purpose is. Sometimes, however, you need to use some non-semantic markup (e.g., <div>s) to build ...
Debugging service workers - Firefox Developer Tools
, you'll get the following output shown: This gives you some advice on what to do if you don't have a service worker registered, and were perhaps expecting there to be one registered! Let's start by troubleshooting this. Getting your service worker to register Before you can look at your service worker in action in the Applications panel, you need to successfully register it. ...
Browser Console - Firefox Developer Tools
ole but also Web Console. Here is an example on how to clear the contents of the Browser console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserConsole(); hud.jsterm.clearOutput(true); If you would like to access the content document of the Browser Console this can be done with the HUDService. This example here makes it so that when you mouse over the "Clear" button it will clear the Browser Console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserConsole(); var clearBtn = hud.chromeWindow.document.querySelector('.webconsole-clear-console-...
Set event listener breakpoints - Firefox Developer Tools
es as each event is fired: Instead, we can then switch to the console, and whenever we press a key we are given a log of where related events were fired. There's an issue here -- the console is showing that the keypress event is being fired somewhere inside jQuery. Instead, it'd be far more useful if we showed where in our own app code is calling the jQuery that fired the event. This can be done by finding jquery.js in the Sources panel, and choosing the Ignore source option from its context menu. Now the logs will show where in your app jQuery was called, rather than where in jQuery the event was fired: Filter by event type Also added to Firefox 71 is a new Filter by event type... text input, which can also be found at the top of the Event Listener Breakpoints list. When you clic...
Debugger.Memory - Firefox Developer Tools
Object Memory Use Analysis Exposes Implementation Details Memory analysis may yield surprising results, because browser implementation details that are transparent to content JavaScript often have visible effects on memory consumption. Web developers need to know their pages' actual memory consumption on real browsers, so it is correct for the tool to expose these behaviors, as long as it is done in a way that helps developers make decisions about their own code. This section covers some areas where Firefox's actual behavior deviates from what one might expect from the specified behavior of the web platform. Objects SpiderMonkey objects usually use less memory than the naive "table of properties with attributes" model would suggest. For example, it is typical for many objects to have i...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
ed, this display shows that popup.xml and content.js, which are internal components of Firefox, allocated more objects in the page's compartment than the page itself. (We will probably revise the allocation log to present such allocations in a way that is more informative, and that exposes less of Firefox's internal structure.) As expected, the onclick handler is responsible for all allocation done by the page's own code. (The line number for the onclick handler is 1, indicating that the allocating call is located on line one of the handler text itself. We will probably change this to be the line number within page.html, not the line number within the handler code.) The onclick handler calls doDivsAndSpans, which calls divsAndSpans, which invokes closures of factory to do all the actual ...
DevTools API - Firefox Developer Tools
tion MyPanel(window, target) { // The window object that has loaded the URL defined in the ToolDefinition this.window = window; // The Target this toolbox is debugging. this.target = target; // Do synchronous initialization here. window.document.body.addEventListener("click", this.handleClick); } MyPanel.prototype = { open: function() { // Any asynchronous operations should be done here. return this.doSomethingAsynchronous() .then(() => this); }, destroy: function() { // Synchronous destruction. this.window.document.body.removeEventListener("click", this.handleClick); // Async destruction. return this.destroySomethingAsynchronosly() .then(() => console.log("destroyed")); }, handleClick: function(event) { console.log("Clicked", ...
Console messages - Firefox Developer Tools
at triggered the reflow. Click the link to open the file in the Debugger. Synchronous and asynchronous reflows If a change is made that invalidates the current layout -- for example, the browser window is resized or some JavaScript modifies an element's CSS -- the layout is not recalculated immediately. Instead, the reflow happens asynchronously, the next time the browser decides it needs to be done (generally, the next time the browser repaints). In this way the browser can save up a collection of invalidating changes and recalculate their effect at once. However, if some JavaScript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return. For example, code like this will cause an immediate, synchronous...
Rich output - Firefox Developer Tools
the clipboard. Then you can paste it into a document. The output will look something like this: console.log(todoList) Array(4) [ {...}, {...}, {...}, {...} ] debugger eval code:1:9 undefined If you expand objects, such as arrays, you get slightly different content. ...
AbortController - Web APIs
Constructor AbortController() Creates a new AbortController object instance. ...
AddressErrors - Web APIs
ror: genericAddressError, shippingAddressErrors, ...defaultPaymentDetails }; } ev.updateWith(updateDetails); } The shippingaddresschange event doesn't receive the PaymentRequest object directly, so we fetch it from the target property of the event. If the request's shippingAddress has a value for country which isn't in the array validCountries, we generate the error. That's done by removing all shipping options currently set on the request, then set up an object named shippingAddressErrors which contains a country property which is an error message describing why the stated country isn't being permitted as a value. Then a PaymentDetailsUpdate object is created with its error set to a generic message about address errors and with the reset of the object's values taken fr...
AnalyserNode.smoothingTimeConstant - Web APIs
cally an average between the current buffer and the last buffer the AnalyserNode processed, and results in a much smoother set of value changes over time. Syntax var smoothValue = analyserNode.smoothingTimeConstant; analyserNode.smoothingTimeConstant = newValue; Value A double within the range 0 to 1 (0 meaning no time averaging). The default value is 0.8. If 0 is set, there is no averaging done, whereas a value of 1 means "overlap the previous and current buffer quite a lot while computing the value", which essentially smoothes the changes across AnalyserNode.getFloatFrequencyData/AnalyserNode.getByteFrequencyData calls. In technical terms, we apply a Blackman window and smooth the values over time. The default value is good enough for most cases. Note: If a value outside the range ...
Animation.onfinish - Web APIs
Working Draft Editor's draft. ...
Animation.ready - Web APIs
Web › API › Animation › ready
or both pending play and pending pause requests, authors are advised to check the state of the animation when the promise is resolved. Syntax var readyPromise = Animation.ready; Value A Promise which resolves when the animation is ready to be played. You'll typically use a construct similar to this when using the ready promise: animation.ready.then(function() { // Do whatever needs to be done when // the animation is ready to run }); Example In the following example, the state of the animation will be running when the current ready Promise is resolved because the animation does not leave the pending play state in between the calls to pause and play and hence the current ready Promise does not change. animation.pause(); animation.ready.then(function() { // Displays 'running' a...
AudioContext.createMediaElementSource() - Web APIs
Specifications Specification Status Comment Web Audio APIThe definition of 'createMediaElementSource()' in that specification. Working Draft ...
AudioContext.createMediaStreamSource() - Web APIs
Specifications Specification Status Comment Web Audio APIThe definition of 'AudioContext.createMediaStreamSource()' in that specification. Working Draft ...
AudioListener - Web APIs
person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. It is important to note that there is only one listener per context and that it isn't an AudioNode. Properties The position, forward, and up value are set and retrieved using different syntaxes. Retrieval is done by accessing, for example, AudioListener.positionX, while setting the same property is done with AudioListener.positionX.value. This is why these values are not marked read only, which is how they appear in the specification's IDL. AudioListener.positionX Represents the horizontal position of the listener in a right-hand cartesian coordinate sytem. The default is 0. AudioListener.positionY ...
AudioParamDescriptor - Web APIs
f custom AudioParams, we'll expand the example from AudioWorkletNode page. There we've created a simple node which outputs white noise. Here, additionally, we'll create a custom gain parameter, so we can directly change volume of the output (although you could use GainNode to achieve this as well). First, we need to define a custom AudioWorkletProcessor, and register it. Note that this should be done in a separate file. We expand the processor by adding a static parameterDescriptors getter. It will be used internally by the AudioWorkletNode constructor to populate its parameters with instantiated AudioParam objects. // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { static get parameterDescriptors () { return [{ name: 'customGain', defaul...
AudioWorkletGlobalScope.registerProcessor - Web APIs
allowed. TypeError The processorCtor is not a callable constructor, or the parameterDescriptors property of the constructor exists and doesn't return an array of AudioParamDescriptor-based objects. Examples In this example we create a custom AudioWorkletNode that outputs silence. First, we need to define a custom AudioWorkletProcessor and register it. Note that this should be done in a separate file. // test-processor.js class TestProcessor extends AudioWorkletProcessor { process (inputs, outputs, parameters) { return true } } registerProcessor('test-processor', TestProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode -- passing it the processor name that we used when calling registerProcessor -- and connect ...
AudioWorkletGlobalScope - Web APIs
ods registerProcessor() Registers a class derived from the AudioWorkletProcessor interface. The class can then be used by creating an AudioWorkletNode, providing its registered name. Examples In this example we output all global properties into the console in the constructor of a custom AudioWorkletProcessor. First we need to define the processor, and register it. Note that this should be done in a separate file. // 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, // wh...
AudioWorkletNode.parameters - Web APIs
f custom AudioParams, we'll expand the example from AudioWorkletNode page. There we've created a simple node which outputs white noise. Here, additionally, we'll create a custom gain parameter, so we can directly change volume of the output (although you could use GainNode to achieve this as well). First, we need to define a custom AudioWorkletProcessor, and register it. Note that this should be done in a separate file. We expand the processor by adding a static parameterDescriptors getter. It will be used internally by the AudioWorkletNode constructor to populate its parameters with instantiated AudioParam objects. // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { static get parameterDescriptors () { return [{ name: 'customGain', defaul...
AudioWorkletNode.port - Web APIs
The MessagePort object that is connecting the AudioWorkletNode and its associated AudioWorkletProcessor. Examples To demonstrate bidirectional communication capabilities, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. First, we need to define a custom AudioWorkletProcessor, and register it. Note that that this should be done in a separate file. // ping-pong-processor.js class PingPongProcessor extends AudioWorkletProcessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main s...
AudioWorkletNode - Web APIs
e will output silence throughout its lifetime. Methods Also inherits methods from its parent, AudioNode. The AudioWorkletNode interface does not define any methods of its own. Examples In this example we create a custom AudioWorkletNode that outputs white noise. First, we need to define a custom AudioWorkletProcessor, which will output white noise, and register it. Note that this should be done in a separate file. // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { process (inputs, outputs, parameters) { const output = outputs[0] output.forEach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = Math.random() * 2 - 1 } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProce...
AudioWorkletProcessor() - Web APIs
minimum have numberOfInputs and numberOfOutputs. Return value The newly constructed AudioWorkletProcessor instance. Example In this example we pass custom options to the AudioWorkletNode constructor and observe how a structured clone of them gets passed to our AudioWorkletProcessor constructor. First, we need to define a custom AudioWorkletProcessor and register it. Note that this should be done in a separate file. // test-processor.js class TestProcessor extends AudioWorkletProcessor { constructor (options) { super() console.log(options.numberOfInputs) console.log(options.processorOptions.someUsefulVariable) } process (inputs, outputs, parameters) { return true } } registerProcessor('test-processor', TestProcessor) Next, in our main script file we'll load the...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
f custom AudioParams, we'll expand the example from AudioWorkletNode page. There we've created a simple node which outputs white noise. Here, additionally, we'll create a custom gain parameter, so we can directly change volume of the output (although you could use GainNode to achieve this as well). First, we need to define a custom AudioWorkletProcessor, and register it. Note that this should be done in a separate file. We expand the processor by adding a static parameterDescriptors getter. It will be used internally by the AudioWorkletNode constructor to populate its parameters with instantiated AudioParam objects. // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { static get parameterDescriptors () { return [{ name: 'customGain', defaul...
AudioWorkletProcessor.port - Web APIs
The MessagePort object that is connecting the AudioWorkletProcessor and the associated AudioWorkletNode. Examples To demonstrate bidirectional communication capabilities, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. First, we need to define a custom AudioWorkletProcessor, and register it. Note that that this should be done in a separate file. // ping-pong-processor.js class PingPongProcessor extends AudioWorkletProcessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main s...
AudioWorkletProcessor - Web APIs
Create an AudioWorkletNode based on the processor. The processor will be instantiated internally by the AudioWorkletNode constructor. Connect the node to the other nodes. Examples In the example below we create a custom AudioWorkletNode that outputs white noise. First, we need to define a custom AudioWorkletProcessor, which will output white noise, and register it. Note that this should be done in a separate file. // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { process (inputs, outputs, parameters) { const output = outputs[0] output.forEach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = Math.random() * 2 - 1 } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProce...
BaseAudioContext.createBuffer() - Web APIs
AudioContext Interface is used to create a new, empty AudioBuffer object, which can then be populated by data, and played via an AudioBufferSourceNode For more details about audio buffers, check out the AudioBuffer reference page. Note: createBuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createBuffer() was blocking other code execution. The asynchronous method decodeAudioData() does the same thing -- takes compressed audio, say, an MP3 file, and directly gives you back an AudioBuffer that you can then set to play via in an AudioBufferSourceNode. For simple uses like playing an MP3, decodeAudioData() is what you should be using. Syntax var buffer =...
Battery Status API - Web APIs
us API extends window.navigator with a navigator.getBattery() method returning a battery promise, which is resolved in a BatteryManager object providing also some new events you can handle to monitor the battery status. Example In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the chargingchange, levelchange, chargingtimechange, dischargingtimechange events. navigator.getBattery().then(function(battery) { function updateAllBatteryInfo(){ updateChargeInfo(); updateLevelInfo(); updateChargingInfo(); updateDischargingInfo(); } updateAllBatteryInfo(); battery.addEventListener('chargingchange', function(){ updateChargeInfo(); ...
BlobBuilder - Web APIs
Note: The BlobBuilder interface has been deprecated in favor of the newly introduced Blob constructor. ...
BroadcastChannel.close() - Web APIs
g channel, allowing the object to be garbage collected. This is a necessary step to perform as there is no other way for a browser to know that this channel is not needed anymore. Note: This feature is available in Web Workers. Syntax var str = channel.close(); Example // Connect to a channel var bc = new BroadcastChannel('test_channel'); // More operations (like postMessage, ...) // When done, disconnect from the channel bc.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.close()' in that specification. Living Standard Initial definition. ...
BroadcastChannel.name - Web APIs
his name is passed to the BroadcastChannel() constructor at creation time and is therefore read-only. Note: This feature is available in Web Workers. Syntax var str = channel.name; Examples // Connect to a channel var bc = new BroadcastChannel('test_channel'); // More operations (like postMessage, ...) // Log the channel name to the console console.log(bc.name); // "test_channel" // When done, disconnect from the channel bc.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.name' in that specification. Living Standard Initial definition. ...
CSSStyleDeclaration.setProperty() - Web APIs
he array found at stylesheet.cssRules; for each one, we check whether its CSSStyleRule.selectorText property is equal to the selector .box p, which indicates it is the one we want. If so, we store a reference to this CSSStyleRule object in a variable. We then use three functions to generate random values for the properties in question, and update the rule with these values. ...
Using the CSS Painting API - Web APIs
orklet To use the paint worklet, we need to register it using addModule() and include it in our CSS, ensuring the CSS selector matches a DOM node in our HTML Registering the worklet The setup and design of our paint worklet took place in the external script shown above. We need to register that worklet from our main script. CSS.paintWorklet.addModule('nameOfPaintWorkletFile.js'); This can be done using the paint worklet's addModule() method in a <script> within the main HTML or in an external JavaScript file linked to from the document. In our example, the paintworklet is stored on Github. CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/01partOne/header-highlight.js'); Reference the paint worklet in CSS Once we have a registered paint worklet, we can...
Cache.delete() - Web APIs
Web › API › Cache › delete
he Cache entry and returns a Promise that resolves to true. If no Cache entry is found, it resolves to false. Syntax cache.delete(request, {options}).then(function(found) { // your cache entry has been deleted if found }); Parameters request The Request you are looking to delete. This can be a Request object or a URL. options Optional An object whose properties control how matching is done in the delete operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. If set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. It defaults to false. ignoreMethod: A Boolean that, when set to true, prevents matching operations from validating the Req...
Cache.keys() - Web APIs
Web › API › Cache › keys
ifferent headers can be returned if their responses have the VARY header set on them. Syntax cache.keys(request, {options}).then(function(keys) { // do something with your array of requests }); Parameters request Optional The Request want to return, if a specific key is desired. This can be a Request object or a URL. options Optional An object whose properties control how matching is done in the keys operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. If set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. It defaults to false. ignoreMethod: A Boolean that, when set to true, prevents matching operations from validating the Reque...
CacheStorage.match() - Web APIs
tionality is to call cache.match() on each cache (in the order returned by caches.keys()) until a Response is returned. Syntax caches.match(request, options).then(function(response) { // Do something with the response }); Parameters request The Request you want to match. This can be a Request object or a URL string. options Optional An object whose properties control how matching is done in the match operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. For example, if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. It defaults to false. ignoreMethod: A Boolean that, when set to true, prevents matching operations from valida...
CanvasRenderingContext2D.resetTransform() - Web APIs
he fillRect() method draws a filled rectangle, adjusted according to that matrix. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Draw a rotated rectangle ctx.rotate(45 * Math.PI / 180); ctx.fillRect(60, 0, 100, 30); // Reset transformation matrix to the identity matrix ctx.resetTransform(); Result Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call resetTransform() before rendering anything else. In this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Skewed rectangles...
CanvasRenderingContext2D.rotate() - Web APIs
gray, and the rotated rectangle is red. Rotating a shape around its center This example rotates a shape around its center point. To do this, the following steps are applied to the matrix: First, translate() moves the matrix's origin to the shape's center. rotate() rotates the matrix by the desired amount. Finally, translate() moves the matrix's origin back to its starting point. This is done by applying the values of the shape's center coordinates in a negative direction. HTML <canvas id="canvas"></canvas> JavaScript The shape is a rectangle with its corner at (80, 60), a width of 140, a height of 30. Its horizontal center is at (80 + 140 / 2), or 150. Its vertical center is at (60 + 30 / 2), or 75. Thus, the center point is at (150, 75). const canvas = document.getElementById...
A basic ray-caster - Web APIs
distance from the camera to the wall, and is drawn centered over the horizon line. The code I ended up with is a regurgitated amalgam of the raycaster chapters from an old Andre LaMotheTricks of the Game Programming Gurus book (ISBN: 0672305070), and a java raycaster I found online, filtered through my compulsion to rename everything so it makes sense to me, and all the tinkering that had to be done to make things work well. Results The canvas in Safari 2.0.1 performed surprisingly well. With the blockiness factor cranked up to render slivers 8 pixels wide, I can run a 320 x 240 window at 24 fps on my Apple mini. Firefox 1.5 Beta 1 is even faster; I can run 320 x 240 at 24 fps with 4 pixel slivers. Not exactly a new member of the ID software family, but pretty decent considering it's a ful...
Applying styles and colors - Web APIs
+ ')'; ctx.beginPath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true); ctx.stroke(); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); The result looks like this: ScreenshotLive sample Transparency In addition to drawing opaque shapes to the canvas, we can also draw semi-transparent (or translucent) shapes. This is done by either setting the globalAlpha property or by assigning a semi-transparent color to the stroke and/or fill style. globalAlpha = transparencyValue Applies the specified transparency value to all future shapes drawn on the canvas. The value must be between 0.0 (fully transparent) to 1.0 (fully opaque). This value is 1.0 (fully opaque) by default. The globalAlpha property can be useful if y...
Drawing shapes with canvas - Web APIs
<< PreviousNext >> Now that we have set up our canvas environment, we can get into the details of how to draw on the canvas. By the end of this article, you will have learned how to draw rectangles, triangles, lines, arcs and curves, providing familiarity with some of the basic shapes. Working with paths is essential when drawing objects onto the canvas and we will see how that can be done. The grid Before we can start drawing, we need to talk about the canvas grid or coordinate space. Our HTML skeleton from the previous page had a canvas element 150 pixels wide and 150 pixels high. To the right, you see this canvas with the default grid overlayed. Normally 1 unit in the grid corresponds to 1 pixel on the canvas. The origin of this grid is positioned in the top left corner at co...
Hit regions and accessibility - Web APIs
e following guidelines can help to make it more accessible. Fallback content The content inside the <canvas> ... </canvas> tags can be used as a fallback for browsers which don't support canvas rendering. It's also very useful for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done: <canvas> <h2>Shapes</h2> <p>A rectangle with a black border. In the background is a pink circle. Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>. Partially overlaying the circle is a green <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a> an...
Transformations - Web APIs
vas id="canvas" width="150" height="150"></canvas> draw(); The first step is to draw a large rectangle with the default settings. Next we save this state and make changes to the fill color. We then draw the second and smaller blue rectangle and save the state. Again we change some drawing settings and draw the third semi-transparent white rectangle. So far this is pretty similar to what we've done in previous sections. However once we call the first restore() statement, the top drawing state is removed from the stack, and settings are restored. If we hadn't saved the state using save(), we would need to change the fill color and transparency manually in order to return to the previous state. This would be easy for two properties, but if we have more than that, our code would become very lo...
Canvas API - Web APIs
rdware-accelerated 2D and 3D graphics. Basic example This simple example draws a green rectangle onto a canvas. HTML <canvas id="canvas"></canvas> JavaScript The Document.getElementById() method gets a reference to the HTML <canvas> element. Next, the HTMLCanvasElement.getContext() method gets that element's context--the thing onto which the drawing will be rendered. The actual drawing is done using the CanvasRenderingContext2D interface. The fillStyle property makes the rectangle green. The fillRect() method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(10, 10, 150, 100); Result Reference HTMLCanvasElement ...
Clipboard.write() - Web APIs
Web › API › Clipboard › write
. The key of the object passed to the ClipboardItem constructor indicates the content type, the value indicates the content. The content could be a text or even a Blob (e.g. for copying images to the clipboard). Then write() is called, specifying both a fulfilment function and an error function. Example of copying canvas contents to the clipboard function copyCanvasContentsToClipboard(canvas, onDone, onError) { canvas.toBlob(function (blob) { let data = [new ClipboardItem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function () { onDone(); }, function (err) { onError(err); }) }); } Note: You can only pass in one clipboard item at a time. Specifications Specification Status Comment Clipboard API and eventsThe defin...
CryptoKey - Web APIs
Web › API › CryptoKey
algorithm for which this key can be used and any associated extra parameters. AesKeyGenParams if the algorithm is any of the AES variants. RsaHashedKeyGenParams if the algorithm is any of the RSA variants. EcKeyGenParams if the algorithm is any of the EC variants. HmacKeyGenParams if the algorithm is HMAC. CryptoKey.usages An Array of strings, indicating what can be done with the key. Possible values for array elements are: "encrypt": The key may be used to encrypt messages. "decrypt": The key may be used to decrypt messages. "sign": The key may be used to sign messages. "verify": The key may be used to verify signatures. "deriveKey": The key may be used in deriving a new key. "deriveBits": The key may be used in deriving bits. "wrapKey": The key...
DataTransfer.clearData() - Web APIs
; dropable.removeEventListener('drop', dropHandler); } } function dragOverHandler (event) { status.innerHTML = 'Drop available'; event.preventDefault(); } function dragLeaveHandler (event) { status.innerHTML = 'Drag in process (drop was available)'; event.preventDefault(); } function dropHandler (event) { dropped = true; status.innerHTML = 'Drop done'; event.preventDefault(); // Get data linked to event format << text >> var _data = event.dataTransfer.getData('text/plain'); var element = document.getElementById(_data); // Append drag source element to event's target element event.target.appendChild(element); // Change CSS styles and displayed text element.style.cssText = 'border: 1px solid black;display: bl...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the main thread it was sent to. Only MessagePort and ArrayBuffer objects can be transferred. Returns Void. Example The following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script. ...
DirectoryEntrySync - Web APIs
es methods for creating, reading, looking up, and recursively removing files in a directory. This interface has been abandonned: it was on a standard track and it proves not a good idea. Do not use it anymore. About this document This document was last updated on March 2, 2012 and follows the W3C Specifications (Working Draft) drafted on April 19, 2011. This specification is pretty much abandoned, having failed to reach any substantial traction. Basic concepts If you want to create subdirectories, you have to create each child directory in sequence. If you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. So create the hierarchy by recursively adding a new path after creating the parent directory. Example The getFile...
DirectoryReaderSync - Web APIs
rectoryReaderSync interface of the File System API lets you read the entries in a directory. This interface has been abandonned: it was on a standard track and it proves not a good idea. Do not use it anymore. About this document This document was last updated on March 2, 2012 and follows the W3C Specifications (Working Draft) drafted on April 19, 2011. This specification is pretty much abandoned, having failed to reach any substantial traction. Basic concepts Before you call the only method in this interface, readEntries(), create the DirectoryEntrySync object. But DirectoryEntrySync (as well as FileEntrySync) is not a data type that you can pass between a calling app and Web Worker thread. It's not a big deal, because you don't really need to have the main app and the worker thread s...
Document.all - Web APIs
Web › API › Document › all
e. In other words, it returns all of the document's elements, accessible by order (like an array) and by ID (like a regular object). Syntax var htmlAllCollection = document.all; Value An HTMLAllCollection which contains every element in the document. Conversion to boolean document.all is the only falsy object accessible to JavaScript, because it has the [[IsHTMLDDA]] internal slot. This was done because of compatibility with older versions of Internet Explorer. More information about this can be found in this answer from StackOverflow. Specifications Specification Status Comment HTML Living StandardThe definition of 'all' in that specification. Living Standard Initial definition. Defined in the obsolete and legacy APIs section. ...
Document.fonts - Web APIs
Web › API › Document › fonts
the FontFaceSet interface of the document. Syntax let fontFaceSet = document.fonts; Value The returned value is the FontFaceSet interface of the document. The FontFaceSet interface is useful for loading new fonts, checking the status of previously loaded fonts etc. 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. }); Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'FontFaceSet' in that specification. Working Draft Initial definition Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute ...
Document.querySelector() - Web APIs
Syntax element = document.querySelector(selectors); Parameters selectors A DOMString containing one or more selectors to match. ...
Document.releaseCapture() - Web APIs
The releaseCapture() method releases mouse capture if it's currently enabled on an element within this document. Enabling mouse capture on an element is done by calling element.setCapture(). Syntax document.releaseCapture(); Once mouse capture is released, mouse events will no longer all be directed to the element on which capture is enabled. Example See the example for element.setCapture(). Specifications Based on Internet Explorer's implementation. ...
DocumentOrShadowRoot.activeElement - Web APIs
getSelection(). Syntax element = DocumentOrShadowRoot.activeElement Value The Element which currently has focus, <body> or null if there is no focused element. Example HTML <p>Select some text from one of the text areas below:</p> <form> <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">This is Text Area One. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.</textarea> <textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40">This is Text Area Two. Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.</textarea> </form> <p>Active element ID: <b id="output-elem...
Element: auxclick event - Web APIs
havior by calling preventDefault() from within an auxclick event handler. When listening for auxclick events originating on elements that do not support input or navigation, you will often want to explicitly prevent other default actions mapped to the down action of the middle mouse button. On Windows this is usually autoscroll, and on macOS and Linux this is usually clipboard paste. This can be done by preventing the default behaviour of the mousedown or pointerdown event. Additionally, you may need to avoid opening a system context menu after a right click. Due to timing differences between operating systems, this too is not a preventable default behavior of auxclick. Instead, this can be done by preventing the default behavior of the contextmenu event. Examples In this example we define...
Element.getBoundingClientRect() - Web APIs
ls. Properties other than width and height are relative to the top-left of the viewport. Empty border-boxes are completely ignored. If all the element's border-boxes are empty, then a rectangle is returned with a width and height of zero and where the top and left are the top-left of the border-box for the first CSS box (in content order) for the element. The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle. This means that the rectangle's boundary edges (top, right, bottom, left) change their values every time the scrolling position changes (because their values are relative to the viewport and not absolute). If you need the bounding rectangle relative to the top-left corner of the do...
Element.getClientRects() - Web APIs
xtRectangle object for each line of text. However, the CSSOM working draft specifies that it returns a DOMRect for each border box. For an inline element, the two definitions are the same. But for a block element, Mozilla will return only a single rectangle. Firefox 3.5 note Firefox 3.5 adds width and height properties to the TextRectangle object. The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the rectangles. The returned rectangles do not include the bounds of any child elements that might happen to overflow. For HTML <area> elements, SVG elements that do not render anything themselves, display:none elements, and generally any elements that are not directly rendered, an empty list is returned...
FileEntrySync - Web APIs
The FileEntrySync interface of the File System API represents a file in a file system. It lets you write content to a file. Inherits from: EntrySync About this document This document was last updated on March 2, 2012 and follows the W3C Specifications (Working Draft) drafted on April 19, 2011. This specification is more or less abandoned as it didn't get significant traction among browser makers. Basic concepts To write content to file, create a FileWriter object by calling createWriter(). Method overview FileWriterSync createWriter () raises (FileException); File file () raises (FileException); Methods createWriter() Creates a new FileWriter associated with the file that the FileEntry represents. void createWriter ( ) raises (FileException); Parameter ...
FileReader.abort() - Web APIs
Web › API › FileReader › abort
Syntax instanceOfFileReader.abort(); Exceptions DOM_FILE_ABORT_ERR Thrown when abort is called while no read operation is in progress (that is, the state isn't LOADING). ...
FileReader.readAsArrayBuffer() - Web APIs
At that time, the result attribute contains an ArrayBuffer representing the file's data. Newer API available The Blob.arrayBuffer() method is a newer promise-based API to read a file as an array buffer. Syntax instanceOfFileReader.readAsArrayBuffer(blob); Parameters blob The Blob or File from which to read. ...
FileReader.readAsBinaryString() - Web APIs
At that time, the result attribute contains the raw binary data from the file. Note that this method was once removed from the File API specification, but re-introduced for backward compatibility. Using FileReader.readAsArrayBuffer() is recommended. Syntax instanceOfFileReader.readAsBinaryString(blob); Parameters blob The Blob or File from which to read. ...
FileReader.readAsDataURL() - Web APIs
At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string. Note: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:*/*;base64, from the result. ...
FileReader.readAsText() - Web APIs
Newer API avaliable The Blob.text() method is a newer promise-based API to read a file as text. Syntax instanceOfFileReader.readAsText(blob[, encoding]); Parameters blob The Blob or File from which to read. encoding Optional A string specifying the encoding to use for the returned data. By default, UTF-8 is assumed if this parameter is not specified. ...
FileSystemEntry.toURL() - Web APIs
Syntax FileSystemEntry.toURL([mimeType]); Parameters mimeType Optional An optional string specifying the MIME type to use when interpreting the file. This can be used to help deal with files whose types aren't recognized automatically by the user agent. If this parameter is omitted, the user agent uses its standard algorithms to identify the file. ...
File and Directory Entries API support in Firefox - Web APIs
k. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The original File System API was created to let browsers implement support for accessing a sandboxed virtual file system on the user's storage device. Work to standardize the specification was abandoned back in 2012, but by that point, Google Chrome included its own implementation of the API. Over time, a number of popular sites and Web applications came to use it, often without providing any means of falling back to standard APIs or even checking to be sure the API is available before using it. Mozilla instead opted to implement other APIs which can be used to solve many of the same problems, ...
FontFace.loaded - Web APIs
Web › API › FontFace › loaded
Syntax var aPromise = FontFace.loaded; Value A Promise that resolves with the current FontFace object. ...
FontFace - Web APIs
Web › API › FontFace
uivalent to the font-family descriptor. FontFace.featureSettings A CSSOMString that retrieves or sets infrequently used font features that are not available from a font's variant properties. It is equivalent to the font-feature-settings descriptor. FontFace.loaded Read only Returns a Promise that resolves with the current FontFace object when the font specified in the object's constructor is done loading or rejects with a SyntaxError. FontFace.status Read only Returns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "error". FontFace.stretch A CSSOMString that retrieves or sets how the font stretches. It is equivalent to the font-stretch descriptor. FontFace.style A CSSOMString that retrieves or sets the style of the font. It is equ...
FontFaceSet - Web APIs
FontFaceSet.status Read only Indicates the font-face's loading status. It will be one of 'loading' or 'loaded'. FontFaceSet.ready Read only Promise which resolves once font loading and layout operations have completed. Events FontFaceSet.onloading An EventListener called whenever an event of type loading is fired, indicating a font-face set has started loading. FontFaceSet.onloadingdone An EventListener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. FontFaceSet.onloadingerror An EventListener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. Methods FontFaceSet.add() Adds a font to the font set. FontFaceSet.check() A Boolean that indica...
Guide to the Fullscreen API - Web APIs
documentElement.requestFullscreen(); } else { if (document.exitFullscreen) { document.exitFullscreen(); } } } This starts by looking at the value of the fullscreenElement attribute on the document (checking it prefixed with both moz, ms, or webkit). If it's null, the document is currently in windowed mode, so we need to switch to fullscreen mode. Switching to fullscreen mode is done by calling element.requestFullscreen(). If fullscreen mode is already active (fullscreenElement is non-null), we call document.exitFullscreen(). Prefixing Note: Currently, only Firefox 64 and Chrome 71 supports this unprefixed. For the moment not all browsers are implementing the unprefixed version of the API (for vendor agnostic access to the Fullscreen API you can use Fscreen). Here is th...
Fullscreen API - Web APIs
nt attribute. In a real-world deployment, at this time, you'll want to check for prefixed versions of this (mozFullScreenElement, msFullscreenElement, or webkitFullscreenElement, for example). If the value is null, the document is currently in windowed mode, so we need to switch to full-screen mode; otherwise, it's the element that's currently in full-screen mode. Switching to full-screen mode is done by calling Element.requestFullscreen() on the <video> element. If full-screen mode is already active (fullscreenElement is not null), we call exitFullscreen() on the document to shut off full-screen mode. Specifications Specification Status Fullscreen API Living Standard Browser compatibility Document.fullscreen The compatibility table on this page is gene...
Using the Geolocation API - Web APIs
oSomething(position.coords.latitude, position.coords.longitude); }); The above example will cause the doSomething() function to execute when the location is obtained. Watching the current position If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the watchPosition() function, which has the same input parameters as getCurrentPosition(). The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for getCurrentPosition(), can be called r...
GlobalEventHandlers.onchange - Web APIs
Note: Unlike oninput, the onchange event handler is not necessarily called for each alteration to an element's value. Syntax target.onchange = functionRef; functionRef is a function name or a function expression. The function receives an Event object as its sole argument. ...
GlobalEventHandlers.ontransitioncancel - Web APIs
px; height: 200px; -webkit-transform: rotate(180deg); transform: rotate(180deg); } JavaScript Next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. ...
GlobalEventHandlers.ontransitionend - Web APIs
FCCCC; color: #000000; width: 200px; height: 200px; transform: rotate(180deg); } JavaScript Next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. let box = document.querySelector(".box"); box.ontransitionrun = function(event) { box.innerHTML = "Zooming..."; } box.ontransitionend = function(event) { box.innerHTML = "Done!"; } Result The resulting content looks like this: Notice what happens when you hover your mouse cursor over the box, then move it away. Specification Specification Status Comment CSS TransitionsThe definition of 'ontransitionend' in that specification. Working Draft ...
HTMLCanvasElement - Web APIs
Element.mozPrintCallback Is a function that is Initially null. Web content can set this to a JavaScript function that will be called when the canvas is to be redrawn while the page is being printed. When called, the callback is passed a "printState" object that implements the MozCanvasPrintState interface. The callback can get the context to draw to from the printState object and must then call done() on it when finished. The purpose of mozPrintCallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. See this blog post. Methods Inherits methods from its parent, HTMLElement. HTMLCanvasElement.captureStream() Returns a CanvasCaptureMediaStream that is a real-time video capture of the surface of the canvas. HTMLCanvasElement.getCon...
HTMLCollection - Web APIs
he given zero-based index into the list. Returns null if the index is out of range. An alternative to accessing collection[i] (which instead returns undefined when i is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations. HTMLCollection.namedItem() Returns the specific node whose ID or, as a fallback, name matches the string specified by name. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name attribute. Returns null if no node exists by the given name. An alternative to accessing collection[name] (which instead returns undefined when name does not exist). This is mostly useful for non-JavaScript DOM implementations. Usage in JavaScript HTMLCollection also exposes its members directly as properties...
HTMLImageElement.complete - Web APIs
The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string (""). The image resource has been fully fetched and has been queued for rendering/compositing. ...
HTMLImageElement.naturalHeight - Web APIs
"); window.addEventListener("load", event => { output.innerHTML += `Natural size: ${image.naturalWidth} x ` + `${image.naturalHeight} pixels<br>`; output.innerHTML += `Displayed size: ${image.width} x ` + `${image.height} pixels`; }); The JavaScript code simply dumps the natural and as-displayed sizes into the <div> with the class output. This is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLImageElement.naturalheight' in that specification. Living Standard Browser compatibility The compatibility tabl...
HTMLImageElement.naturalWidth - Web APIs
"); window.addEventListener("load", event => { output.innerHTML += `Natural size: ${image.naturalWidth} x ` + `${image.naturalHeight} pixels<br>`; output.innerHTML += `Displayed size: ${image.width} x ` + `${image.height} pixels`; }); The JavaScript code simply dumps the natural and as-displayed sizes into the <div> with the class output. This is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLImageElement.naturalWidth' in that specification. Living Standard Browser compatibility The compatibility table...
HTMLImageElement.sizes - Web APIs
let image = document.querySelector("article img"); let break40 = document.getElementById("break40"); let break50 = document.getElementById("break50"); break40.addEventListener("click", event => image.sizes = image.sizes.replace(/50em,/, "40em,")); break50.ad...
HTMLImageElement.width - Web APIs
0px. <p>Image width: <span class="size">?</span>px (resize to update)</p> <img src="/files/16864/clock-demo-200px.png" alt="Clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 400px"> JavaScript The JavaScript code looks at the width to determine the width of the image at the moment. This is done in the window's load and resize event handlers, in order to always provide this information. var clockImage = document.querySelector("img"); let output = document.querySelector(".size"); const updateWidth = event => { output.innerText = clockImage.width; }; window.addEventListener("load", updateWidth); window.addEventListener("resize", updateWidth); Result This example may be easier to tr...
HTMLScriptElement - Web APIs
ute at all. HTMLScriptElement.noModule Is a Boolean that if true, stops the script's execution in browsers that support ES2015 modules -- used to run fallback scripts in older browsers that do not support JavaScript modules. HTMLScriptElement.referrerPolicy Is a DOMString that reflects the referrerpolicy HTML attribute indicating which referrer to use when fetching the script, and fetches done by that script. Methods No specific methods; inherits methods from its parent, HTMLElement. Examples Dynamically importing scripts Let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentScript). These scripts will be asynchronously executed. For more details, see the d...
HTMLSourceElement - Web APIs
g the URL for the media resource. The HTMLSourceElement.src property has a meaning only when the associated <source> element is nested in a media element that is a <video> or an <audio> element. It has no meaning and is ignored when it is nested in a <picture> element. Note: If the src property is updated (along with any siblings), the parent HTMLMediaElement's load method should be called when done, since <source> elements are not re-scanned automatically. HTMLSourceElement.srcset Is a DOMString reflecting the srcset HTML attribute, containing a list of candidate images, separated by a comma (',', U+002C COMMA). A candidate image is a URL followed by a 'w' with the width of the images, or an 'x' followed by the pixel density. HTMLSourceElement.type Is a DOMString reflecting the type...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
e new microtasks will execute before the next task begins to run, and before the end of the current event loop iteration. Problems Because your code runs in the same thread, using the same event loop, as the browser's user interface, if your code blocks or enters an infinite loop, the browser itself will stall. Even sluggish performance, whether caused by a bug or because of complex work being done by your code, can cause the user to suffer a sluggish browser. When multiple programs and multiple code objects within those programs start to try to work at once, alongside a browser which also needs processor time--let alone time to render and draw the site and its own UI, handle user events, and so forth--everything becomes clogged up far too easily nowadays. Solutions The use of web worker...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
ithout potentially having other tasks such as timeouts or the like delay the transmission. The server will receive the JSON string, then will presumably decode it and process the messages it finds in the resulting array. Examples Simple microtask example In this simple example, we see that enqueueing a microtask causes the microtask's callback to run after the body of this top-level script is done running. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; In the following code, we see a call to queueMicrotask() used to schedule a microtask to run. This call is bracketed by calls to log(), a custom function that simply outputs text to the screen. log("Before...
File drag and drop - Web APIs
Is to support dragging and dropping files. One API is the DataTransfer interface and the second API is the DataTransferItem and DataTransferItemList interfaces. This example illustrates the use of both APIs (and does not use any Gecko specific interfaces). Define the drop zone The target element of the drop event needs an ondrop global event handler. The following code snippet shows how this is done with a <div> element: <div id="drop_zone" ondrop="dropHandler(event);"> <p>Drag one or more files to this Drop Zone ...</p> </div> Typically, an application will include a dragover event handler on the drop target element and that handler will turn off the browser's default drag behavior. To add this handler, you need to include a ondragover global event handler: <div id="drop_zone" ondrop="...
Recommended Drag Types - Web APIs
. Caution: All methods and properties in this document with a moz prefix, such as mozSetDataAt(), will only work with Gecko-based browsers. Dragging Text For dragging text, use the text/plain type. The second data parameter should be the dragged string. For example: event.dataTransfer.setData("text/plain", "This is text to drag"); Dragging text in textboxes and selections on web pages is done automatically by the browser, so you do not need to handle it yourself. It is recommended to always add data of the text/plain type as a fallback for applications or drop targets that do not support other types, unless there is no logical text alternative. Always add this text/plain type last, as it is the least specific and shouldn't be preferred. Note: In older code, you may find text/unicode...
HTML Drag and Drop API - Web APIs
dragstart nor dragend events are fired when dragging a file into the browser from the OS. Interfaces The HTML Drag and Drop interfaces are DragEvent, DataTransfer, DataTransferItem and DataTransferItemList. The DragEvent interface has a constructor and one dataTransfer property, which is a DataTransfer object. DataTransfer objects include the drag event's state, such as the type of drag being done (like copy or move), the drag's data (one or more items), and the MIME type of each drag item. DataTransfer objects also have methods to add or remove items to the drag's data. The DragEvent and DataTransfer interfaces should be the only ones needed to add HTML Drag and Drop capabilities to an application. (Firefox supports some Gecko-specific extensions to the DataTransfer object, but those ext...
History API - Web APIs
The DOM Window object provides access to the browser's session history (not to be confused for WebExtensions history) through the history object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack. Concepts and usage Moving backward and forward through the user's history is done using the back(), forward(), and go() methods. Moving forward and backward To move backward through history: window.history.back() This acts exactly as if the user clicked on the Back button in their browser toolbar. Similarly, you can move forward (as if the user clicked the Forward button), like this: window.history.forward() Moving to a specific point in history You can use the go() method to load a s...
IDBObjectStore.add() - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // Make a request to add our newItem o...
IDBObjectStore.autoIncrement - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.autoIncrement...
IDBObjectStore.clear() - Web APIs
of opening the database in the db variable. ...
IDBObjectStore.delete() - Web APIs
in the db variable. ...
IDBObjectStore.get() - Web APIs
abase in the db variable. ...
IDBObjectStore.indexNames - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.indexNames); ...
IDBObjectStore.keyPath - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.keyPath); //...
IDBObjectStore.name - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.name); // Ma...
IDBObjectStore.transaction - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); console.log(objectStore.transaction);...
IDBObjectStore - Web APIs
Duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // make a request to add our newItem object to the obje...
IDBRequest.readyState - Web APIs
The readyState read-only property of the IDBRequest interface returns the state of the request. Every request starts in the pending state. The state changes to done when the request completes successfully or when an error occurs. Note: This feature is available in Web Workers. Syntax var currentReadyState = request.readyState; Value The IDBRequestReadyState of the request, which takes one of the following two values: Value Meaning pending The request is pending. done The request is done. Example The following example requests a given record title, onsuccess gets the associated record from the IDBObjectStore (made available as objectStoreTitleRequest.result), updates one property of the record, and then puts the updated record back...
IDBTransaction.abort() - Web APIs
validStateError The transaction has already been committed or aborted. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. At the end, we simply abort any activity done under the current transaction using abort(). For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. This is used a lot b...
IDBTransaction - Web APIs
You use IDBDatabase to start transactions, IDBTransaction to set the mode of the transaction (e.g. is it readonly or readwrite), and you access an IDBObjectStore to make a request. You can also use an IDBTransaction object to abort transactions. Note: This feature is available in Web Workers. ...
IdleDeadline.didTimeout - Web APIs
of a timeout in order to ensure that whatever task they're meant to perform actually happens, even if the user agent never has enough idle time available. Your callback will typically check the value of didTimeout if it needs to perform an action even if the browser is too busy to grant you the time; you should react by performing the needed task or, ideally, a minimal amount of work that can be done to keep things moving along, then schedule a new callback to try again to get the rest of the work done. Syntax var timedOut = IdleDeadline.didTimeout; Value A Boolean which is true if the callback is running due to the callback's timeout period elapsing or false if the callback is running because the user agent is idle and is offering time to the callback. Example See our complete example ...
Basic concepts - Web APIs
transaction. To learn more about transaction types, see the reference article for IndexedDB. Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see IDBTransaction, which also has reference documentation. request The operation by which reading and writing on a database is done. Every request represents one read or write operation. index An index is a specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in...
Checking when a deadline is due - Web APIs
of data to show the newly added item, by running displayData() again. displayData(); }; Last of all, we run the displayData() function, which updates the display of data in the app to show the new task that was just entered. Checking whether a deadline has been reached At this point our data is in the database; now we want to check whether any of the the deadlines have been reached. This is done by our checkDeadlines() function: function checkDeadlines() { var now = new Date(); First we grab the current date and time by creating a blank Date object. Easy huh? It's about to get a bit more complex. var minuteCheck = now.getMinutes(); var hourCheck = now.getHours(); var dayCheck = now.getDate(); var monthCheck = now.getMonth(); var yearCheck = now.getFullYear(); ...
IndexedDB API - Web APIs
exedDB for storing data offline with Service Workers for storing assets offline, as outlined in Making PWAs work offline with Service workers. Note: Like most web storage solutions, IndexedDB follows a same-origin policy. So while you can access stored data within a domain, you cannot access data across different domains. Synchronous and asynchronous Operations performed using IndexedDB are done asynchronously, so as not to block applications. IndexedDB originally included both synchronous and asynchronous APIs. The synchronous API was intended for use only with Web Workers but was removed from the spec because it was unclear whether it was needed. However, the synchronous API may be reintroduced if there is enough demand from web developers. Storage limits and eviction criteria There ...
IntersectionObserverEntry.boundingClientRect - Web APIs
the entire target element. Syntax var boundsRect = IntersectionObserverEntry.boundingClientRect; Value A DOMRectReadOnly which describes the smallest rectangle that contains every part of the target element whose intersection change is being described. This value is obtained using the same algorithm as Element.getBoundingClientRect(), so refer to that article for details on precisely what is done to obtain this rectangle and what is and is not included within its bounds. In the general case, however, it's safe to simply think of this as the bounds rectangle of the target element. Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserverEntry.boundingClientRect' in that specification. Working Draft Initial defi...
LargestContentfulPaint - Web APIs
request url of the image. Methods LargestContentfulPaint.toJSON() Returns the above properties as JSON. Examples The following example shows how to create a PerformanceObserver that listens for largest-contentful-paint entries and logs the LCP value to the console. This example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true. Note that in this example data is only sent to the server when the user leaves the tab. // Catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new PerformanceObserver((entryList) => { const entries = entryList.getEntries(); const lastEntry = entri...
Location - Web APIs
Web › API › Location
Both the Document and Window interface have such a linked Location, accessible via Document.location and Window.location respectively. ...
MSGestureEvent - Web APIs
hich represents events that occur due to touch gestures. Events using this interface include MSGestureStart, MSGestureEnd, MSGestureTap, MSGestureHold, MSGestureChange, and MSInertiaStart. MSGestureEvent derives from UIEvent, which in turn derives from Event. Though the MSGestureEvent.initGestureEvent() method is kept for backward compatibility, the creation of an MSGestureEvent object should be done using the MSGestureEvent() constructor. Constructor MSGestureEvent() Creates an MSGestureEvent object. Properties This interface also inherits properties of its parents, UIEvent and Event. MSGestureEvent.expansion Read only The diameter of the gesture area. For example, the distance between fingers. MSGestureEvent.gestureObject Read only Returns the MSGesture object for this gestu...
MediaElementAudioSourceNode - Web APIs
Specification Specification Status Comment Web Audio APIThe definition of 'MediaElementAudioSourceNode' in that specification. Working Draft ...
MediaStreamAudioSourceNode - Web APIs
Specification Specification Status Comment Web Audio APIThe definition of 'MediaStreamAudioSourceNode' in that specification. Working Draft ...
MediaStreamTrackAudioSourceNode - Web APIs
Specification Specification Status Comment Web Audio APIThe definition of 'MediaStreamTrackAudioSourceNode' in that specification. Working Draft ...
Recording a media element - Web APIs
recordingTimeMS, is set to 5000 milliseconds (5 seconds); this specifies the length of the videos we'll record. Utility functions Next, we create some utility functions that will get used later. function log(msg) { logElement.innerHTML += msg + "\n"; } The log() function is used to output text strings to a <div> so we can share information with the user. Not very pretty but it gets the job done for our purposes. function wait(delayInMS) { return new Promise(resolve => setTimeout(resolve, delayInMS)); } The wait() function returns a new Promise which resolves once the specified number of milliseconds have elapsed. It works by using an arrow function which calls window.setTimeout(), specifying the promise's resolution handler as the timeout handler function. That lets us use promise ...
MediaTrackConstraints.autoGainControl - Web APIs
ided by microphones, although it can be provided by other input sources as well. Syntax var constraintsObject = { autoGainControl: constraint }; constraintsObject.autoGainControl = constraint; Value If this value is a simple true or false, the user agent will attempt to obtain media with automatic gain control enabled or disabled as specified, if possible, but will not fail if this can't be done. If, instead, the value is given as an object with an exact field, that field's Boolean value indicates a required setting for the automatic gain control feature; if it can't be met, then the request will result in an error. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment ...
MediaTrackConstraints.echoCancellation - Web APIs
tracks associated with a WebRTC RTCPeerConnection will never include this property. Syntax var constraintsObject = { echoCancellation: constraint }; constraintsObject.echoCancellation = constraint; Value If this value is a simple true or false, the user agent will attempt to obtain media with echo cancellation enabled or disabled as specified, if possible, but will not fail if this can't be done. If, instead, the value is given as an object with an exact field, that field's Boolean value indicates a required setting for the echo cancellation feature; if it can't be met, then the request will result in an error. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment Me...
MediaTrackConstraints.noiseSuppression - Web APIs
rovided by microphones, although it can be provided by other input sources as well. Syntax var constraintsObject = { noiseSuppression: constraint }; constraintsObject.noiseSuppression = constraint; Value If this value is a simple true or false, the user agent will attempt to obtain media with noise suppression enabled or disabled as specified, if possible, but will not fail if this can't be done. If, instead, the value is given as an object with an exact field, that field's Boolean value indicates a required setting for the noise suppression feature; if it can't be met, then the request will result in an error. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment Me...
Capabilities, constraints, and settings - Web APIs
onstruct updated MediaTrackConstraints objects for the audio track (audioConstraints) and the video track (videoConstraints). MediaStreamTrack.applyConstraints() is called on the video track (if there is one) to apply the new videoConstraints. If this succeeds, the contents of the video track's current settings box are updated based on the result of calling its getSettings() method. Once that's done, applyConstraints() is called on the audio track (if there is one) to apply the new audio constraints. If this succeeds, the contents of the audio track's current settings box are updated based on the result of calling its getSettings() method. If an error occurs applying either set of constraints, handleError() is used to output a message into the log. document.getElementById("applyButton").a...
Microdata DOM API - Web APIs
You can't use them anymore and this document is kept as information only. Microdata becomes even more useful when scripts can use it to expose information to the user, for example offering it in a form that can be used by other applications. The document.getItems(typeNames) method provides access to the top-level microdata items. It returns a NodeList containing the items with the specified types, or all types if no argument is specified. ...
MouseEvent - Web APIs
The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click, dblclick, mouseup, mousedown. MouseEvent derives from UIEvent, which in turn derives from Event. Though the MouseEvent.initMouseEvent() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent() constructor. Several more specific events are based on MouseEvent, including WheelEvent and DragEvent. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" pres...
msPlayToPreferredSourceUri - Web APIs
d content. The app specifies a preferred Uniform Resource Identifier (URI). This URI can point to a cloud based media server allowing streaming directly from the cloud, which can be DRM protected, instead of streaming content from the Windows machine which must be unprotected content. A forward slash ("/") is appended to the URI string when it is sent over the network to a PlayTo device. This is done to conform to URI standards. 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 a...
MutationObserver.takeRecords() - Web APIs
observer.observe(targetNode, observerOptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takeRecords(); observer.disconnect(); if (mutations) { callback(mutations); } The code in lines 12-17 fetches any unprocessed mutation records, then invokes the callback with the records so that they can be processed. This is done immediately prior to calling disconnect() to stop observing the DOM. Specifications Specification Status Comment DOMThe definition of 'MutationObserver.takeRecords()' in that specification. Living Standard ...
Using the Notifications API - Web APIs
ent to display notifications in response to a user gesture (e.g. clicking a button). This is not only best practice -- you should not be spamming users with notifications they didn't agree to -- but going forward browsers will explicitly disallow notification permission requests not triggered in response to a user gesture. Firefox is already doing this from version 72, for example, and Safari has done it for some time. In addition, In Chrome and Firefox you cannot request notifications at all unless the site is a secure context (i.e. HTTPS), and you can no longer allow notification permissions to be requested from cross-origin <iframe>s. Checking current permission status You can check to see if you already have permission by checking the value of the Notification.permission read only prope...
OfflineAudioContext.suspend() - Web APIs
s is generally useful at the time of manipulating the audio graph synchronously on OfflineAudioContext. Note that the maximum precision of suspension is the size of the render quantum and the specified suspension time will be rounded down to the nearest render quantum boundary. For this reason, it is not allowed to schedule multiple suspends at the same quantized frame. Also scheduling should be done while the context is not running to ensure the precise suspension. Syntax OfflineAudioContext.suspend(suspendTime).then(function() { ... }); Parameters suspendTime A double specifying the suspend time, in seconds. Returns A Promise resolving to void. Exceptions The promise is rejected when any exception is encountered. InvalidStateError if the quantized frame number is one of the fol...
PaintWorklet.registerPaint - Web APIs
To use it, you register it with the CSS.paintWorklet.addModule() method: <script> CSS.paintWorklet.addModule('checkboardWorklet.js'); </script> You can then use the paint() CSS function in your CSS anywhere an <image> value is valid. li { background-image: paint(checkerboard); } Specifications Specification Status Comment CSS Painting API Level 1The defin...
PannerNode - Web APIs
Channel count mode "clamped-max" Channel count 2 Channel interpretation "speakers" Constructor PannerNode.PannerNode Creates a new PannerNode object instance. Properties Inherits properties from its parent, AudioNode. The orientation and position value are set and retrieved using different syntaxes, since they're stored as AudioParam values. Retrieval is done by accessing, for example, PannerNode.positionX. While setting the same property is done with PannerNode.positionX.value. This is why these values are not marked read only, which is how they appear in the WebIDL. PannerNode.coneInnerAngle Is a double value describing the angle, in degrees, of a cone inside of which there will be no volume reduction. PannerNode.coneOuterAngle A double value...
PaymentDetailsUpdate - Web APIs
Properties The PaymentDetailsUpdate dictionary is based on the PaymentDetailsBase dictionary, and inherits its properties, which are included in the list below. ...
PaymentRequest.abort() - Web APIs
The PaymentRequest.abort() method of the PaymentRequest interface causes the user agent to end the payment request and to remove any user interface that might be shown. Syntax PaymentRequest.abort(); Returns Void. Parameters None Examples The following example sets up a timeout to clear the payment request that might have been abandoned or neglected. var request = new PaymentRequest(supportedInstruments, details, options); var paymentTimeout = window.setTimeout(() => { window.clearTimeout(paymentTimeout); request.abort().then(() => { print('Payment timed out after 20 minutes.'); }).catch(() => { print('Unable to abort, because the user is currently in the process ' + 'of paying.'); }); }, 20 * 60 * 1000); /* 20 minutes */ Specifications Spec...
PerformanceNavigation.redirectCount - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceNavigation.redirectCount read-only property returns an unsigned short representing the number of REDIRECTs done before reaching the page. Syntax amount = performanceNavigation.redirectCount; Specifications Specification Status Comment Navigation TimingThe definition of 'PerformanceNavigation.redirectCount' in that specification. Recommendation Initial definition. ...
PerformanceNavigation.type - Web APIs
This interface of this property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead. The legacy PerformanceNavigation.type read-only property returns an unsigned short containing a constant describing how the navigation to this page was done. Possible values are: Value Constant name Meaning 0 TYPE_NAVIGATE The page was accessed by following a link, a bookmark, a form submission, a script, or typing the URL in the address bar. 1 TYPE_RELOAD The page was accessed by clicking the Reload button or via the Location.reload() method. 2 TYPE_BACK_FORWARD The page was accessed by navigating into the history. 255 TYPE_RESERVED Any other way. Sy...
ProgressEvent() - Web APIs
a long process. Syntax progressEvent = new ProgressEvent(type, {lengthComputable: aBooleanValue, loaded: aNumber, total: aNumber}); Arguments The ProgressEvent() constructor also inherits arguments from Event(). type Is a DOMString representing the name of the type of the ProgressEvent. It is case-sensitive. lengthComputable Optional Is a Boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. It defaults to false. loaded Optional Is an unsigned long long representing the amount of work already performed by the underlying process. The ratio of work done can be calculated with the property and ProgressEvent.total. When downloading a resource usi...
ProgressEvent.initProgressEvent() - Web APIs
d didn't complete. load The operation completed. loadend The operation stopped. canBubbleArg Is a Boolean flag indicating if the event can bubble (true) or not (false). cancelableArg Is a Boolean flag indicating if the event associated action can be avoided (true) or not (false). lengthComputable Is a Boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. loaded Is an unsigned long long representing the amount of work already performed by the underlying process. The ratio of work done can be calculated with the property and ProgressEvent.total. When downloading a resource using HTTP, this only represent th...
ProgressEvent.loaded - Web APIs
When downloading a resource using HTTP, this only represent the part of the content itself, not headers and other overhead. ...
ProgressEvent - Web APIs
" text-anchor="middle" alignment-baseline="middle">ProgressEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor ProgressEvent() Creates a ProgressEvent event with the given parameters. Properties Also inherits properties from its parent Event. ProgressEvent.lengthComputable Read only Is a Boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. ProgressEvent.loaded Read only Is an unsigned long long representing the amount of work already performed by the underlying process. The ratio of work done can be calculated with the property and ProgressEvent.total. When downloading a resource using HTT...
PushManager.subscribe() - Web APIs
// for example, an XMLHttpRequest. }, function(error) { // During development it often helps to log errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. ...
Web Push API Notifications best practices - Web APIs
Overview of web push notifications Web Push Notifications (created using a combination of the Notifications, Push, and Service Worker APIs) are part of the rising noise that product developers and marketers are using to get attention for their sites. ...
RTCDTMFSender: tonechange event - Web APIs
oneChangeEvent Event handler property ontonechange To determine what tone started playing, or if a tone stopped playing, check the value of the event's tone property. Examples This example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". ...
RTCDataChannel.bufferedAmount - Web APIs
The read-only RTCDataChannel property bufferedAmount returns the number of bytes of data currently queued to be sent over the data channel. The queue may build up as a result of calls to the send() method. This only includes data buffered by the user agent itself; it doesn't include any framing overhead or buffering done by the operating system or network hardware. The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. Closing the data channel doesn't reset this count, even though the user agent purges the queued messages. However, even after closing the channel, attempts to send messages continue to add to the bu...
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
the bufferedAmount property, falls to or below this value, a bufferedamountlow event is fired. This event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. Listeners may be added with onbufferedamountlow or addEventListener(). The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. Syntax var threshold = aDataChannel.bufferedAmountLowThreshold; aDataChannel.bufferedAmountLowThreshold = threshold; Value The number of queued outgoing data bytes below which the buffer is c...
RTCDataChannel: open event - Web APIs
as well as enabling the disconnect button and disabling the connect button. Finally, the message input box is focused so the user can immediately begin to type. dc.addEventListener("open", ev => { messageInputBox.disabled = false; sendMessageButton.disabled = false; disconnectButton.disabled = false; connectButton.disabled = true; messageInputBox.focus(); }, false); This can also be done by directly setting the value of the channel's onopen event handler property. dc.onopen = ev => { messageInputBox.disabled = false; sendMessageButton.disabled = false; disconnectButton.disabled = false; connectButton.disabled = true; messageInputBox.focus(); } ...
RTCDataChannel.send() - Web APIs
Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed. Different browsers have different limitations on the size of the message you can send. Specifications exist to define how to automatically fragment large messages, but not all browsers implement them, and those that do have various additional restrictions. ...
RTCIceCandidateInit.candidate - Web APIs
for this example candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" Example When a new ICE candidate is received by your signaling code from the remote peer, you need to construct the RTCIceCandidate object that encapsulates it. This is done in the event handler for the icecandidate event. If your client-side signaling layer builds and transmits a JSON string including the candidate to the remote peer, the remote peer might handle receiving that JSON message like this: function gotICECandidateMessage(msg) { var iceCandidate = new RTCIceCandidate({ candidate: msg.candidate; }); pc.addIceCandidate(iceCandidate).catch({ ...
RTCIceCandidatePairStats.state - Web APIs
dates. Each pair has a state, whose value is represented by RTCStatsIceCandidatePairState. When a candidate pair is added to the check list, it begins in the frozen state. As soon as there are no checks ongoing which block the pair from being analyzed, it is unfrozen and moves into the waiting state. This may happen immediately upon being added to the check list. Each time a candidate pair is done being checked, the next-highest priority candidate pair remaining on the check list moves from the waiting state to the in-progress state, and its check begins. If the check fails for any reason, the pair moves into its final state, failed. If the check succeeds, the pair ends up in the succeeded state. The ICE check list state for any given pair of ICE candidates can be found in the correspondi...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
let iceTransport = pc.getSenders[0].transport.iceTransport; let localProtoElem = document.getElementById("local-protocol"); let remoteProtoElem = document.getElementById("remote-protocol"); iceTransport.onselectedcandidatepairchange = ev => { let pair = iceTransport.getSelectedCandidatePair(); localProtoElem.inner...
RTCOutboundRtpStreamStats.qualityLimitationReason - Web APIs
g indicating the reason why the media quality in the stream is currently being reduced by the codec during encoding, or none if no quality reduction is being performed. This quality reduction may include changes such as reduced frame rate or resolution, or an increase in compression factor. The amount of time the encoded media has had its quality reduced in each of the potential ways that can be done can be found in qualityLimitationDurations. Syntax var qualityLimitationReason = RTCOutboundRtpStreamStats.qualityLimitationReason; Value A Map whose keys are DOMStrings whose values come from the RTCQualityLimitationReason enumerated type, and whose values are the duration of the media, in seconds, whose quality was reduced for that reason. Examples Specifications Specificat...
RTCPeerConnection.addTrack() - Web APIs
Description to pass into setRemoteDescription(). Once that succeeds, it uses MediaDevices.getUserMedia() to obtain access to the local webcam and microphone. If that succeeds, the resulting stream is assigned as the source for a <video> element which is referenced by the variable previewElement. The final step is to begin sending the local video across the peer connection to the caller. This is done by adding each track in the stream by iterating over the list returned by MediaStream.getTracks() and passing them to addTrack() along with the stream which they're a component of. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.addTrack()' in that specification. Candidate Recomme...
RTCPeerConnection.createOffer() - Web APIs
myPeerConnection.localDescription }); }) .catch(function(reason) { // An error occurred, so handle the failure to connect }); In this code, the offer is created, and once successful, the local end of the RTCPeerConnection is configured to match by passing the offer (which is represented using an object conforming to RTCSessionDescriptionInit) into setLocalDescription(). Once that's done, the offer is sent to the remote system over the signaling channel; in this case, by using a custom function called sendToServer(). The implementation of the signaling server is independent from the WebRTC specification, so it doesn't matter how the offer is sent as long as both the caller and potential receiver are using the same one. Use Promise.catch() to trap and handle errors. See Signalin...
RTCPeerConnection.getIdentityAssertion() - Web APIs
The RTCPeerConnection.getIdentityAssertion() method initiates the gathering of an identity assertion. This has an effect only if the signalingState is not "closed". The method returns immediately. If the assertion cannot be generated, an idpassertionerror will be sent to the object. It is not expected for the application dealing with the RTCPeerConnection: this is automatically done; an explicit call only allows to anticipate the need. Syntax pc.getIdentityAssertion(); There is neither parameter nor return value for this method. Example var pc = new PeerConnection(); pc.getIdentityAssertion(); // Not mandatory, but we know that we will need it in the future. Specifications Specification Status Comment Identity for WebRTCThe definition of 'RTCPeerCo...
RTCPeerConnection.iceGatheringState - Web APIs
CIceGatheringState enum The RTCIceGatheringState enum defines string constants which reflect the current status of ICE gathering, as returned using the RTCPeerConnection.iceGatheringState property. You can detect when this value changes by watching for an event of type icegatheringstatechange. Constant Description "new" The peer connection was just created and hasn't done any networking yet. "gathering" The ICE agent is in the process of gathering candidates for the connection. "complete" The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to "gathering" to gather those candidates. ...
RTCPeerConnection.restartIce() - Web APIs
This simplifies the process by allowing the same method to be used by either the caller or the receiver to trigger an ICE restart. After restartIce() returns, the offer returned by the next call to createOffer() is automatically configured to trigger ICE restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. ...
RTCRtpReceiver.getCapabilities() static function - Web APIs
starting to try to access media. Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. For that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. Example The function below returns a Boolean indicating whether or not the device supports receiving H.264 video on a WebRTC connection. Since RTCRtpReceiver.getCapabilities() actually only indicates probable support, attempting to receive H.264 video might still fail even after getting a positive response from this function. fu...
RTCRtpSender.getCapabilities() static function - Web APIs
starting to try to access media. Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. For that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. Example The function below returns a Boolean indicating whether or not the device supports sending H.264 video on an RTCRtpSender. Since RTCRtpSender.getCapabilities() actually only indicates probable support, H.264 support might still fail even after getting a positive response from this function. function canSendH264() { let...
RTCRtpSender.replaceTrack() - Web APIs
ionError Replacing the RTCRtpSender's current track with the new one would require negotiation. InvalidStateError The track on which this method was called is stopped rather than running. TypeError The new track's kind doesn't match the original track. Usage notes Things that trigger negotiation Not all track replacements require renegotiation. In fact, even changes that seem huge can be done without requiring negotation. Here are the changes that can trigger negotiaton: The new track has a resolution which is outside the bounds of the bounds of the current track; that is, the new track is either wider or taller than the current one. The new track's frame rate is high enough to cause the codec's block rate to be exceeded. The new track is a video track and its raw or pre-encoded ...
ReadableStream.ReadableStream() - Web APIs
es that define how the constructed stream instance will behave. underlyingSource can contain the following: start(controller) This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream fuctionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The controller parameter passed to this method is a ReadableStreamDefaultController or a ReadableByteStreamController, depending on the value of the type property. This can be used by the developer to control the stream during set up. pull(controller) Optional This method, also defined by the developer, will be called repea...
ReadableStream.cancel() - Web APIs
nse => { console.log('Received headers'); var decoder = new TextDecoder(); var reader = response.body.getReader(); var toMatch = caseInsensitive ? searchTerm.toLowerCase() : searchTerm; var bufferSize = Math.max(toMatch.length - 1, contextBefore); 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}); // already found match & just context-gathering? if (matchFoundAt === -1) { matchFoundAt = (caseInsensitive ? buffer.toLowerCase() : buffer).indexO...
ReadableStreamBYOBReader.read() - Web APIs
chunk in the byte stream's internal queue. Syntax var promise = readableStreamBYOBReader.read(view); Parameters view The view to be read into. Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, the stream has no owner, the view is not an object or has become detached, or the view's length is 0.
Response.redirected - Web APIs
erty of the Response interface indicates whether or not the response is the result of a request you made which was redirected. Relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected. Instead, you should actually instead do the filtering when you call fetch(). See the example Disallowing redirects, which shows this being done. Syntax var isRedirected = Response.redirected; Value A Boolean which is true if the response indicates that your request was redirected. Examples Detecting redirects Checking to see if the response comes from a redirected request is as simple as checking this flag on the Response object. In the code below, a textual message is inserted into an element when a redirect occurred during the ...
SpeechSynthesis.onvoiceschanged - Web APIs
Syntax speechSynthesisInstance.onvoiceschanged = function() { ... }; Examples This could be used to populate a list of voices that the user can choose between when the event fires (see our Speak easy synthesis demo.) Note that Firefox doesn't support it at present, and will just return a list ...
Using writable streams - Web APIs
ills when this is the case, inside of which we call WritableStreamDefaultWriter.write() to actually write the chunk to the stream. This also triggers the write() method specified inside the WritableStream() constructor, as discussed above. After the chunks have all been written, we then perform the ready check once more, to check that the last chunk has finished being written and all the work is done. When this ready check fulfills, we invoke WritableStreamDefaultWriter.close() to close the stream. This also triggers the close() method specified inside the WritableStream() constructor, as discussed above. Controllers As you'll have noticed when studying the WritableStream() syntax skeleton, the start(), write(), and close() methods can optionally have a controller parameter passed to them. ...
SubtleCrypto.deriveKey() - Web APIs
Algorithm is an object defining the algorithm the derived key will be used for. For HMAC: pass an HmacKeyGenParams object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: pass an AesKeyGenParams object. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the derived key. Note that the key usages must be allowed by the algorithm set in derivedKeyAlgorithm. Possible values of the array are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a ...
SubtleCrypto.generateKey() - Web APIs
RsaHashedKeyGenParams object. For ECDSA or ECDH: pass an EcKeyGenParams object. For HMAC: pass an HmacKeyGenParams object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: pass an AesKeyGenParams object. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the newly generated key. Possible values for array elements are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deriveBits: The key may be used in deriving bits. wrapKey...
SubtleCrypto.importKey() - Web APIs
R, AES-CBC, AES-GCM, or AES-KW: Pass the string identifying the algorithm or an object of the form { "name": ALGORITHM }, where ALGORITHM is the name of the algorithm. For PBKDF2 : Pass the string PBKDF2. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the key. Possible array values are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deriveBits: The key may be used in deriving bits. wrapKey: The key may be used to wrap...
SubtleCrypto.unwrapKey() - Web APIs
HmacImportParams object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: Pass the string identifying the algorithm or an object of the form { "name": ALGORITHM }, where ALGORITHM is the name of the algorithm. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the key. Possible values of the array are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deriveBits: The key may be used in deriving bits. wrapKey: The key may be used ...
SubtleCrypto - Web APIs
ta, usages, and extractability given as parameters. SubtleCrypto.exportKey() Returns a Promise that fulfills with a buffer containing the key in the requested format. SubtleCrypto.wrapKey() Returns a Promise that fulfills with a wrapped symmetric key for usage (transfer and storage) in insecure environments. The wrapped key matches the format specified in the given parameters, and wrapping is done by the given wrapping key, using the specified algorithm. SubtleCrypto.unwrapKey() Returns a Promise that fulfills with a CryptoKey corresponding to the wrapped key given in the parameter. Using SubtleCrypto We can split the functions implemented by this API into two groups: cryptography functions and key management functions. Cryptography functions These are the functions you can use to i...
TextEncoder.prototype.encodeInto() - Web APIs
oundUpToBucketSize(s.length), the maximum allocation size s.length * 3, and to have a chosen (as a tradeoff between memory usage and speed) threshold t such that if roundUpToBucketSize(s.length) + t >= s.length * 3, you simply allocate for s.length * 3. Otherwise, first allocate for roundUpToBucketSize(s.length) and convert. If the read item it the return dictionary is s.length, the conversion is done. If not, reallocate the target buffer to written + (s.length - read) * 3 and then convert the rest by taking a substring of s starting from index read and a subbuffer of the target buffer starting from index written. Above roundUpToBucketSize() is a function that rounds up to the allocator bucket size. For example, if your Wasm allocator is known to use power-of-two buckets, roundUpToBucketSize(...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
and present an interface for navigating the named chapters, where each cue in the list represents a chapter in the media. The user can then navigate to the desired chapter, which begins at the cue's start position and ends at the cue's end position. Example In this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback. This is done by setting the pauseOnExit property on each cue to true. However, to ensure that the track's cues are available, we first set mode to showing. window.addEventListener("load", event => { let trackElem = document.querySelector("track"); let track = trackElem.track; track.mode = "showing"; for (let index=0; index < track.cues.length; index++) { let cue = track.cues[index]; cue.pau...
Using Touch Events - Web APIs
i=0; i < ev.targetTouches.length; i++) { process_target(ev.targetTouches[i].target); } }, false); Prevent the browser from processing emulated mouse events. // touchmove handler function process_touchmove(ev) { // Set call preventDefault() ev.preventDefault(); } Best practices Here are some best practices to consider when using touch events: Minimize the amount of work that is done in the touch handlers. Add the touch point handlers to the specific target element (rather than the entire document or nodes higher up in the document tree). Add touchmove, touchend and touchcancel event handlers within the touchstart. The target touch element or node should be large enough to accommodate a finger touch. If the target area is too small, touching it could result in firing other...
TransformStream - Web APIs
writable end of a TransformStream. Methods None Examples Anything-to-uint8array stream In the following example, a transform stream passes through all chunks it receives as Uint8Array values. const transformContent = { start() {}, // required. ...
WEBGL_compressed_texture_s3tc - Web APIs
image in an RGB image format with a simple on/off alpha value. ext.COMPRESSED_RGBA_S3TC_DXT3_EXT A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression. ext.COMPRESSED_RGBA_S3TC_DXT5_EXT A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done. Examples var ext = ( gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc') ); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA_S3TC_DXT5_EXT, 512, 512, 0, textureData); gl.texParameteri(gl.
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
tained by the GPU. Some vertex attribute indices may have predefined purposes, depending on the platform and/or the GPU. Others are assigned by the WebGL layer when you create the attributes. Either way, since attributes cannot be used unless enabled, and are disabled by default, you need to call enableVertexAttribArray() to enable individual attributes so that they can be used. Once that's been done, other methods can be used to access the attribute, including vertexAttribPointer(), vertexAttrib*(), and getVertexAttrib(). Syntax void gl.enableVertexAttribArray(index); Parameters index A GLuint specifying the index number that uniquely identifies the vertex attribute to enable. If you know the name of the attribute but not its index, you can get the index by calling getAttribLocation(...
WebGLRenderingContext.getUniformLocation() - Web APIs
eceives the horizontal and vertical scaling factors from the variable currentScale. The uniform uRotationVector is set to the contents of the variable currentRotation. This, too, is a 2-component vertex. Finally, the uniform uGlobalColor is set to the color [0.1, 0.7, 0.2, 1.0], the components in this 4-component vector represent the values of red, green, blue, and alpha, respectively. Having done this, the next time the shading functions are called, their own variables named uScalingFactor, uGlobalColor, and uRotationVector will all have the values provided by the JavaScript code. Specifications Specification Status Comment WebGL 1.0The definition of 'getUniformLocation' in that specification. Recommendation Initial definition. OpenGL ES 2.0The def...
WebGLRenderingContext.stencilFunc() - Web APIs
Pass if (ref & mask) >= (stencil & mask). gl.ALWAYS: Always pass. ref A GLint specifying the reference value for the stencil test. This value is clamped to the range 0 to 2n -1 where n is the number of bitplanes in the stencil buffer. The default value is 0. mask A GLuint specifying a bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done. The default value is all 1. Return value None. Examples The stencil testing is disabled by default. To enable or disable stencil testing, use the enable() and disable() methods with the argument gl.STENCIL_TEST. gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.LESS, 0, 0b1110011); To get the current stencil function, reference value, or other stencil information, query the following constan...
WebGLRenderingContext.stencilFuncSeparate() - Web APIs
Pass if (ref & mask) >= (stencil & mask). gl.ALWAYS: Always pass. ref A GLint specifying the reference value for the stencil test. This value is clamped to the range 0 to 2n -1 where n is the number of bitplanes in the stencil buffer. The default value is 0. mask A GLuint specifying a bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done. The default value is all 1. Return value None. Examples The stencil testing is disabled by default. To enable or disable stencil testing, use the enable() and disable() methods with the argument gl.STENCIL_TEST. gl.enable(gl.STENCIL_TEST); gl.stencilFuncSeparate(gl.FRONT, gl.LESS, 0.2, 1110011); To get the current stencil function, reference value, or other stencil information, query the...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
ute, you must specify its index. This is independent from the location inside the array buffer, so your attributes can be sent in a different order than how they are stored in the array buffer. You have two options: Either you specify the index yourself. In this case, you call gl.bindAttribLocation() to connect a named attribute from the vertex shader to the index you want to use. This must be done before calling gl.linkProgram(). You can then provide this same index to gl.vertexAttribPointer(). Alternatively, you use the index that is assigned by the graphics card when compiling the vertex shader. Depending on the graphics card, the index will vary, so you must call gl.getAttribLocation() to find out the index, and then provide this index to gl.vertexAttribPointer(). If you are using We...
Canvas size and WebGL - Web APIs
mple explores the effect of setting (or not setting) the canvas size to its element size in CSS pixels, as it appears in the browser window. Effect of canvas size on rendering with WebGL With scissor() and clear() we can demonstrate how the WebGL drawing buffer is affected by the size of the canvas. The size of the first canvas is set to the styled Element size, determined by CSS. This is done by assigning the width and height properties of the canvas to the values of the clientWidth and clientHeight properties, respectively. In contrast, no such assignment is done for the second canvas. The internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas Element in the browser window. The effect is clearly visible wh...
Clearing with colors - Web APIs
green we know that WebGL's magic has worked. In addition, you may notice that clearing the drawing buffer with a solid color is a two-stage process. First, we set the clear color to green, using the method clearColor(). This only changes some internal state of WebGL, but does not draw anything yet. Next, we actually do the drawing by calling the clear() method. This is typical of how drawing is done with WebGL. There is only a handful of methods for actual drawing (clear() is one of them). All other methods are for setting and querying WebGL state variables (such as the clear color). There are many "dials" and "switches" that affect drawing with WebGL. The clear color is just the first of many you will get to know. This is why WebGL/OpenGL is often called a state machine. By tweaking those ...
Detect WebGL - Web APIs
hether the browser supports WebGL. To that end we will try to obtain the WebGL rendering context from a canvas element. The WebGL rendering context is an interface, through which you can set and query the state of the graphics machine, send data to the WebGL, and execute draw commands. Saving the state of the graphics machine within a single context interface is not unique to WebGL. This is also done in other graphics {{Glossary("API")}}, such as the canvas 2D rendering context. However, the properties and variables you can tweak are different for each API. <p>[ Here would go the result of WebGL feature detection ]</p> <button>Press here to detect WebGLRenderingContext</button> body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding :...
Textures from code - Web APIs
<p>Texture from code. ...
WebGL by example - Web APIs
ect WebGL This example demonstrates how to detect a WebGL rendering context and reports the result to the user. Clearing with colors How to clear the rendering context with a solid color. Clearing by clicking How to combine user interaction with graphics operations. Clearing the rendering context with a random color when the user clicks. Simple color animation A very basic color animation, done by clearing the WebGL drawing buffer with a different random color every second. Color masking Modifying random colors by applying color masking and thus limiting the range of displayed colors to specific shades. Basic scissoring How to draw simple rectangles and squares with scissoring operations. Canvas size and WebGL The example explores the effect of setting (or not setting) the canvas ...
WebGL constants - Web APIs
th a simple on/off alpha value. COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression. COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done. WEBGL_compressed_texture_etc Constant name Value Description COMPRESSED_R11_EAC 0x9270 One-channel (red) unsigned format compression. COMPRESSED_SIGNED_R11_EAC 0x9271 One-channel (red) signed format compression. COMPRESSED_RG11_EAC 0x9272 Two-channel (red and green) unsigned format compression. COMPRESSED_SIGNED_RG1...
Matrix math for the web - Web APIs
through 3D space. Manipulating the DOM with a matrix A really easy way to start using a matrix is to use the CSS matrix3d() transform. First we'll set up a simple <div> with some content. The style is not shown, but it's set to a fixed width and height and is centered on the page. The <div> has a transition set for the transform so that matrix is animated in making it easy to see what is being done. <div id='move-me' class='transformable'> <h2>Move me with a matrix</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> </div> Finally, for each of the examples we will generate a 4x4 matrix, then update the <div>'s style to have a transform applied to it, set to a matrix3d. Bear in mind that even though the matrix is made up of 4 rows and 4 columns, it collapses into a...
Adding 2D content to a WebGL context - Web APIs
oat32Array(positions), gl.STATIC_DRAW); return { position: positionBuffer, }; } This routine is pretty simplistic given the basic nature of the scene in this example. It starts by calling the gl object's createBuffer() method to obtain a buffer into which we'll store the vertex positions. This is then bound to the context by calling the bindBuffer() method. Once that's done, we create a JavaScript array containing the position for each vertex of the square plane. This is then converted into an array of floats and passed into the gl object's bufferData() method to establish the vertex positions for the object. Rendering the scene Once the shaders are established, the locations are looked up, and the square plane's vertex positions put in a buffer, we can actually r...
Animating textures in WebGL - Web APIs
o clamp to edge so it // will work regardless of the dimensions of the video. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); return texture; } Here's what the updateTexture() function looks like; this is where the real work is done: function updateTexture(gl, texture, video) { const level = 0; const internalFormat = gl.RGBA; const srcFormat = gl.RGBA; const srcType = gl.UNSIGNED_BYTE; gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, srcFormat, srcType, video); } You've seen this code before. It's nearly identical to the image onload function in the pr...
WebGL: 2D and 3D graphics for the web - Web APIs
Web › API › WebGL API
ly used to represent a 3D object view: the model, view and projection matrices. Matrix math for the web A useful guide to how 3D transform matrices work, and can be used on the web -- both for WebGL calculations and in CSS3 transforms. Resources Raw WebGL: An introduction to WebGL A talk by Nick Desaulniers that introduces the basics of WebGL. This is a great place to start if you've never done low-level graphics programming. Khronos WebGL site The main web site for WebGL at the Khronos Group. WebGL Fundamentals A basic tutorial with fundamentals of WebGL. WebGL playground An online tool for creating and sharing WebGL projects. Good for quick prototyping and experimenting. WebGL Academy An HTML/JavaScript editor with tutorials to learn basics of webgl programming. WebGL Stats A sit...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
er an ICE restart while handling the eventnegotiationneeded have significant flaws. These flaws have made it difficult to safely and reliably trigger a restart during negotiation. The perfect negotiation improvements have fixed this by adding a new restartIce() method to RTCPeerConnection. ...
Taking still photos with WebRTC - Web APIs
variables are: width Whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide. height The output height of the image will be computed given the width and the aspect ratio of the stream. streaming Indicates whether or not there is currently an active stream of video running. video This will be a reference to the <video> element after the page is done loading. canvas This will be a reference to the <canvas> element after the page is done loading. photo This will be a reference to the <img> element after the page is done loading. startbutton This will be a reference to the <button> element that's used to trigger capture. We'll get that after the page is done loading. The startup() function The startup() function is run when the page ha...
Writing WebSocket servers - Web APIs
hould consider the message delivered. More on this later. Decoding Payload Length To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps: Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're done. If it's 126, go to step 2. If it's 127, go to step 3. Read the next 16 bits and interpret those as an unsigned integer. You're done. Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit must be 0.) You're done. Reading and Unmasking the Data If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); thi...
Web Video Text Tracks Format (WebVTT) - Web APIs
A space or a newline. Zero or more characters other than those noted above. Example 4 - Common WebVTT example NOTE This is a comment Example 5 - Multi-line comment NOTE One comment that is spanning more than one line. NOTE You can also make a comment across more than one line this way. Example 6 - Common comment usage WEBVTT - Translation of that film I like NOTE This translation was done by Kyle so that some friends can watch it with their parents. 1 00:02:15.000 --> 00:02:20.000 - Ta en kopp varmt te. - Det ar inte varmt. 2 00:02:20.000 --> 00:02:25.000 - Har en kopp te. - Det smakar som te. NOTE This last line may not translate well. 3 00:02:25.000 --> 00:02:30.000 - Ta en kopp Styling WebVTT cues You can style WebVTT cues by looking for elements which match the ::cue ps...
Geometry and reference spaces in WebXR - Web APIs
ariety of XR hardware available, coming in a wide variety of form factors from many developers, it's impractical and non-scalable to expect developers to have to directly communicate with the tracking technology being used. Instead, the WebXR Device API is designed to have developers plan their users' experiences and request an appropriate reference space that best represents those needs. This is done by asking the user agent for an XRReferenceSpace matching those needs. An XRReferenceSpace object acts as a means to adapt one coordinate system reference frame to another. After putting on a headset, consider the virtual world around you to have a coordinate system in which your position is (0, 0, 0)--that is, you're at the center of everything. Doesn't that feel empowering? Forward, directly t...
Inputs and input sources - Web APIs
ment and rotation. Some inputs are instead used to control the application rather than the avatar. For example, a button might open an options menu used to configure the application. While that menu is open, inputs that would otherwise control the avatar might be instead applied to controlling the menu's interface. Using keyboard and mouse events Capturing input from the keyboard and mouse is done just like it is in any web application. Set up handlers for the events that you need to handle in order to obtain the inputs you want. It's what you do with those inputs that's interesting. Imagine an avatar object which we'll use to track information about the avatar and its worldview. We want the player to be able to use the W, A, S, and D keys to move forward, left, backward, and right. Becau...
WebXR application life cycle - Web APIs
sive-ar, in order to determine whether or not the type of session you wish to provide is available. If the session type you want to use is available, provide the appropriate interface to the user to allow them to activate it. When the user requests the activation of WebXR functionality by engaging with the user interface enabled above, request an XRSession using the desired mode. This is done by calling navigator.xr.requestSession(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar. If the promise returned by requestSession() resolves, use the new XRSession to manage the WebXR session for the duration of the WebXR experience. This will involve managing inputs, animations, and rendering. Call the XRSession method requestAn...
Using the Web Animations API - Web APIs
easing: 'ease-in-out', fill: 'both' }); Alice's animation has her going from half her size to twice her size over 8 seconds. 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 already! We want to set her animation's "playhead" in the middle, so she's already halfway done. We could do that by setting her Animation.currentTime to 4 seconds, like so: aliceChange.currentTime = 4000; But while working on this animation, we might change Alice's duration a lot. Wouldn't it be better if we set her currentTime dynamically, so we don't have to make two updates at a time? We can, in fact, do so by referencing aliceChange's Animation.effect property, which returns an objec...
Web Audio API best practices - Web APIs
to the data directly, which means more precision, and more precise manipulation. If you're looking to work with audio from the user's camera or microphone you can access it via the Media Stream API and the MediaStreamAudioSourceNode interface. This is good for WebRTC and situations where you might want to record or possibly analyse audio. The last way is to generate your own sound, which can be done with either an OscillatorNode or by creating a buffer and populating it with your own data. Check out the tutorial here for creating your own instrument for information on creating sounds with oscillators and buffers. Cross browser & legacy support The Web Audio API specification is constantly evolving and like most things on the web, there are some issues with it working consistently across br...
Using IIR filters - Web APIs
primary types of filters used in audio and digital signal processing. The other type is FIR -- finite impulse response filter. There's a really good overview to IIF filters and FIR filters here. A biquad filter is actually a specific type of infinite impulse response filter. It's a commonly-used type and we already have it as a node in the Web Audio API. If you choose this node the hard work is done for you. For instance, if you want to filter lower frequencies from your sound, you can set the type to highpass and then set which frequency to filter from (or cut off). There's more information on how biquad filters work here. When you are using an IIRFilterNode instead of a BiquadFilterNode you are creating the filter yourself, rather than just choosing a pre-programmed type. So you can creat...
Using the Web Audio API - Web APIs
nt once it's finished playing, so we can listen for that and run code accordingly: audioElement.addEventListener('ended', () => { playButton.dataset.playing = 'false'; }, false); Modifying sound Let's delve into some basic modification nodes, to change the sound that we have. This is where the Web Audio API really starts to come in handy. First of all, let's change the volume. This can be done using a GainNode, which represents how big our sound wave is. There are two ways you can create nodes with the Web Audio API. You can use the factory method on the context itself (e.g. audioContext.createGain()) or via a constructor of the node (e.g. new GainNode()). We'll use the factory method in our code: const gainNode = audioContext.createGain(); Now we have to update our audio graph fro...
Visualizations with Web Audio API - Web APIs
}; At the end of this section of code, we invoke the draw() function to start off the whole process: draw(); This gives us a nice waveform display that updates several times a second: Creating a frequency bar graph Another nice little sound visualization to create is one of those Winamp-style frequency bar graphs. We have one available in Voice-change-O-matic; let's look at how it's done. First, we again set up our analyser and data array, then clear the current canvas display with clearRect(). The only difference from before is that we have set the fft size to be much smaller; this is so that each bar in the graph is big enough to actually look like a bar rather than a thin strand. analyser.fftSize = 256; var bufferLength = analyser.frequencyBinCount; console.log(bufferLength)...
Web Audio API - Web APIs
s distortion effects, it is often used to add a warm feeling to the signal. PeriodicWave Describes a periodic waveform that can be used to shape the output of an OscillatorNode. IIRFilterNode Implements a general infinite impulse response (IIR) filter; this type of filter can be used to implement tone control devices and graphic equalizers as well. Defining audio destinations Once you are done processing your audio, these interfaces define where to output it. AudioDestinationNode The AudioDestinationNode interface represents the end destination of an audio source in a given context -- usually the speakers of your device. MediaStreamAudioDestinationNode The MediaStreamAudioDestinationNode interface represents an audio destination consisting of a WebRTC MediaStream with a single Au...
Web Locks API - Web APIs
ting some potentially shared resource, identified by a name chosen by the web app. For example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and Indexed DB, each tab could try to acquire a "my_net_db_sync" lock, but only one tab will succeed (the leader election pattern.) The API is used as follows: The lock is requested. Work is done while holding the lock in an asynchronous task. The lock is automatically released when the task completes. navigator.locks.request('my_resource', async lock => { // The lock has been acquired. await do_something(); await do_something_else(); // Now the lock will be released. }); While a lock is held, requests for the same lock from this execution context, or from other tabs/workers,...
Using the Web Speech API - Web APIs
eparated by a pipe character. You can have as many terms defined as you want on separate lines following the above structure, and include fairly complex grammar definitions. For this basic demo, we are just keeping things simple. Plugging the grammar into our speech recognition The next thing to do is define a speech recogntion instance to control the recognition for our application. This is done using the SpeechRecognition() constructor. We also create a new speech grammar list to contain our grammar, using the SpeechGrammarList() constructor. var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); We add our grammar to the list using the SpeechGrammarList.addFromString() method. This accepts as parameters the string we want to add, plus optional...
Web Storage API - Web APIs
ng one of these will create an instance of the Storage object, through which data items can be set, retrieved and removed. A different Storage object is used for the sessionStorage and localStorage for each origin -- they function and are controlled separately. Note: From Firefox 45 onwards, when the browser crashes/restarts, the amount of data saved per origin is limited to 10MB. This has been done to avoid memory issues caused by excessive usage of web storage. Note: Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies (Firefox implements this behaviour from version 43 onwards.) Note: Web Storage is not the same as mozStorage (Mozilla's XPCOM interfaces to SQLite) or the Session store API (an XPCOM storage utility for use by extensions...
Web Workers API - Web APIs
ssets residing on the server. They will also allow access to push notifications and background sync APIs. Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to js-ctypes in your worker. See ChromeWorker for more details. Audio Workers provide the ability for direct scripted audio processing to be done inside a web worker context. Note: As per the Web workers Spec, worker error events should not bubble (see bug 1188141. This has been implemented in Firefox 42. Web Worker interfaces AbstractWorker Abstracts properties and methods common to all kind of workers (i.e. Worker or SharedWorker). Worker Represents a running worker thread, allowing you to pass messages to the running worker c...
Window.console - Web APIs
Web › API › Window › console
...
Window.controllers - Web APIs
rollers). Specification XUL-specific. Not part of specification. By default, a window's controller contains the code that supports the global window commands. Chrome code can add controllers (to be used in conjunction with the goDoCommand and goUpdateCommand functions in globalOverlay.js). However, the added controllers must be explicitly removed when the window is unloaded, as this is not done automatically. Each missing removal can cause bug 415775: ASSERTION: XPConnect is being called on a scope without a 'Components' property! ...
Window: popstate event - Web APIs
into History.state; otherwise, state is null. If the value of state changed, the popstate event is sent to the document. Any persisted user state is restored, if the browser chooses to do so. If the original and new entry's shared the same document, but had different fragments in their URLs, send the hashchange event to the window. As you can see, the popstate event is nearly the last thing done in the process of navigating pages in this way. Examples A page at http://example.com/example.html running the following code will generate logs as indicated: window.addEventListener('popstate', (event) => { console.log("location: " + document.location + ", state: " + JSON.stringify(event.state)); }); history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2",...
Worker - Web APIs
Web › API › Worker
Workers may themselves spawn new workers, as long as those workers are hosted at the same origin as the parent page. (Note: nested workers are not yet implemented in WebKit). Not all interfaces and functions are available to scripts inside a Worker. Workers may use XMLHttpRequest for network communication, but its responseXML and channel attributes are always null. ...
WritableStream - Web APIs
set when creating the counting strategy (line 35), sets the maximum amount of data that the WritableStream instance will handle in a single write() operation. In this example, it's the maximum amount of data that can be sent to defaultWriter.write() (line 11). The defaultWriter.ready property returns a promise that resolves when the sink (the first property of the WritableStream constructor) is done writing data. The data source can either write more data (line 9) or call close() (line 24). Calling close() too early can prevent data from being written. This is why the example calls defaultWriter.ready twice (lines 9 and 22). The Promise returned by the sink's write() method (line 40) tells the WritableStream and its writer when to resolve defaultWriter.ready. Specifications Spe...
WritableStreamDefaultWriter.ready - Web APIs
er 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. The first uses ready to ensure that the WritableStream is done writing and thus able to receive data before sending a binary chunk. The second also checks whether the the WritableStream is done writing, but this time because the writing must be finished before the writer can be closed. function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter var defaultWriter = writableStream.getWriter(); var encoder = ne...
Synchronous and asynchronous requests - Web APIs
., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess. Line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously. Line 16 actually initiates the request. Example: using a timeout You can use a timeout to prevent your code from hanging while waiting for a read to finish. ...
Using XMLHttpRequest - Web APIs
ame="foo" bar -----------------------------314911788813839 Content-Disposition: form-data; name="baz" The first line. The second line. -----------------------------314911788813839-- However, if you are using the GET method, a string like the following will be simply added to the URL: ?foo=bar&baz=The%20first%20line.%0AThe%20second%20line. A little vanilla framework All these effects are done automatically by the web browser whenever you submit a <form>. If you want to perform the same effects using JavaScript you have to instruct the interpreter about everything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. For this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and to upload files: <!docty...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
Specifications Specification Status Comment XMLHttpRequestThe definition of 'getAllResponseHeaders()' in that specification. Living Standard WHATWG living standard ...
XMLHttpRequest.onreadystatechange - Web APIs
quest.onreadystatechange = callback; Values callback is the function to be executed when the readyState changes. ...
XMLHttpRequest.response - Web APIs
am The response is part of a streaming download; this response type is only allowed for download requests, and is only supported by Internet Explorer. Example This example presents a function, load(), which loads and processes a page from the server. It works by creating an XMLHttpRequest object and creating a listener for readystatechange events such that that when readyState changes to DONE (4), the response is obtained and passed into the callback function provided to load(). The content is handled as raw text data (since nothing here is overriding the default responseType). var url = 'somePage.html'; //A local page function load(url, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { callback(xhr.response...
XMLHttpRequest.responseXML - Web APIs
TML. Exceptions InvalidStateError The responseType isn't either "document" or an empty string. Example var xhr = new XMLHttpRequest; xhr.open('GET', '/server'); // If specified, responseType must be empty string or "document" xhr.responseType = 'document'; // Force the response to be parsed as XML xhr.overrideMimeType('text/xml'); xhr.onload = function () { if (xhr.readyState === xhr.DONE && xhr.status === 200) { console.log(xhr.response, xhr.responseXML); } }; xhr.send(); Specifications Specification Status Comment XMLHttpRequestThe definition of 'responseXML' in that specification. Living Standard WHATWG living standard ...
XMLHttpRequest.send() - Web APIs
; // 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.onreadystatechange = function() { // Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { // Request finished. Do processing here. } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new Int8Array()); // xhr.send(document); Specifications Specification Status Comment XMLHttpRequestThe definition of 'send()' in that specification. Living Standard WHATWG living standard ...
XMLSerializer - Web APIs
Specifications Specification Status Comment DOM Parsing and SerializationThe definition of 'XMLSerializer' in that specification. Working Draft ...
XRBoundedReferenceSpace.boundsGeometry - Web APIs
ace property boundsGeometry is an array of DOMPointReadOnly objects which specifies the points making up a polygon inside which the viewer is allowed to move. Each point is treated as a two-dimensional point, and must be located at ground level (that is, its y coordinate must be 0). This boundary is typically configured by the user, using the software that controls their XR hardware. This may be done by walking the border of the space they wish to use, or by drawing the shape of their room using their XR input device. Theoretically, a more advanced system might use sensors or other detection methods to determine the bounds of a dedicated XR room (notice how we carefully don't call it a holodeck?). Syntax bounds = xrReferenceSpace.boundsGeometry; Value The boundsGeometry property is an arr...
XRPose.transform - Web APIs
Web › API › XRPose › transform
e XRFrame to which this XRPose is aligned. This is the same pose that's returned by the frame's getPose() method. Example This handler for the XRSession event select handles events for tracked pointers. It determines the targeted object by passing the event frame's pose into a function called findTargetUsingRay(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the XRInputSource property handedness to a value in the variable user.handedness. If the source is a controller in the user's primary hand, a function is called on the targeted object called primaryAction(); otherwise, it calls the targeted object's offHandAction() function. xrSession.addEventListener("select", event => { let source = event.inputSource; let frame = ...
XRSession.requestAnimationFrame() - Web APIs
ssion method requestAnimationFrame(), much like the Window method of the same name, schedules a callback to be executed the next time the browser is ready to paint the session's virtual environment to the XR display. The specified callback is executed once before the next repaint; if you wish for it to be executed for the following repaint, you must call requestAnimationFrame() again. This can be done from within the callback itself. The callback takes two parameters as inputs: an XRFrame describing the state of all tracked objects for the session, and a time stamp you can use to compute any animation updates needed. You can cancel a previously scheduled animation by calling cancelAnimationFrame(). Note: Despite the obvious similarities between these methods and the global requestAnimation...
XRTargetRayMode - Web APIs
Typically a target ray is drawn from the source of the targeting system along the target ray in the direction in which the user is looking or pointing. The style of the ray is generally up to you, as is the method for indicating the endpoint of the ray. ...
XRWebGLLayerInit.ignoreDepthValues - Web APIs
value, false, means the depth buffer will be used, if available. Usage notes If ignoreDepthValues is true, the WebXR compositor will ignore the contents of the depth buffer, if it exists, while compositing and rendering the scene. If false, the depth buffer's contents are used, if one is present. Using a depth buffer while compositing allows the XR compositor to help ensure the compositing is done as accurately as possible. Each entry in the depth buffer corresponds to the depth of the fragment whose color is at the same location in the color buffer, and must have a value between 0.0 and 1.0, where 0.0 corresponds to the distance specified in the XRSession object's renderState record's depthNear and 1.0 represents the distance given by depthFar. Ignoring depth values causes the compositor...
Using the link role - Accessibility
ng window.open() via clicking, and using keyboard, CSS to give the desired visuals of a link, the tabindex="0" attribute to make it keyboard-focussable, and role="link" to make it recognised as a link by assistive technology. This is a huge amount of work just to recreate something you've get for free using the <a> element, so you should really use that if possible. But this shows that it can be done. You should however note that there are still problems with this approach: It is very difficult to detect whether the target of the fake link has been visited before, and therefore use :visited styles (e.g. the default purple color for visited links). Opening a page using the open() method counts as being a popup, and certain browsers may issue a warning when you try to activate it, or make ...
ARIA: figure role - Accessibility
tent that describes the figure, and then reference that ID inside an appropriate attribute on the figure to associate the figure with the label: <div role="figure" aria-labelledby="figure-1"> ... <p id="figure-1">Text that describes the figure.</p> </div> Use aria-labelledby when the text is a concise label. Use aria-describedby when the text is a longer description. Again, this can be done semantically, without ARIA, with HTML's <figure> and <figcaption> elements <figure> ... <figcaption>Text that describes the figure.</figcaption> </figure> If you don't want the label to be visible on the screen, but still want to provide a descriptive label for assistive technology users, you can use the aria-label attribute on the figure container: <div role="figure" aria-label="Text t...
ARIA: gridcell role - Accessibility
er applied to them via aria-describedby, it allows assistive technology to understand the position and relationship of the gridcell element to the rest of the table-style grouping of content. Interactive grids and treegrids Editable cells Both td elements and elements with a role of gridcell applied to them can be made editable, mimicking functionality similar to editing a spreadsheet. This is done by applying the HTML contenteditable attribute. <td contenteditable="true">Notes</td> <div role="gridcell" contenteditable="true">Item cost</div> contenteditable will make the element it is applied to focusable via the Tab key. If a gridcell is conditionally toggled into a state where editing is prohibited, toggle aria-readonly on the gridcell element. Expandable cells In a treegrid, gridc...
ARIA: Region role - Accessibility
abelledby="please-reconsider"> <h3 id="please-reconsider">Please reconsider your document structure</h3> <!-- content --> </div> In this example, the region's label is being generated by the aria-labelledby attribute. Scrolling content areas with overflow text If there is a content area with tabindex="0", add role="region" to convey to screen reader users that is a generic region. This is done to allow keyboard-only users to scroll regions with overflow text. SVG role="region" can be declared on areas of SVG along with an aria-label to allow individual sections of the SVG to be described. Added benefits Certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to...
ARIA: dialog role - Accessibility
your details at any time in the user account section.</p> <button>Close</button> </div> Description Marking up a dialog element with the dialog role helps assistive technology identify the dialog's content as being grouped and separated from the rest of the page content. However, adding role="dialog" alone is not sufficient to make a dialog accessible. Additionally, the following needs to be done: The dialog must be properly labeled Keyboard focus must be managed correctly The sections below describe how these two requirements can be met. Labeling Even though it is not required for the dialog itself to be able to receive focus, it still needs to be labeled. The label given to the dialog will provide contextual information for the interactive controls inside the dialog. In other w...
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
nUnit"> minutes</span> A Note for JAWS 8 users JAWS 8.0 has its own logic to find labels, causing it to always override the accessibleName the textbox of an HTML document gets. With JAWS 8, I have not found a way to make it to accept the label from the example above. But NVDA and Window-Eyes do it just fine, and Orca on Linux also has no problems. TBD: add more compatibility info Can this be done without ARIA? Community member Ben Millard has pointed out in a blog post that controls can be embedded in labels as shown in the above example using HTML 4, simply by embedding the input into the label. Thanks for that info, Ben! It is very useful and shows that some techniques that have been available for years escape even the gurus sometimes. This technique works in Firefox; however, it doesn...
Accessibility documentation index - Accessibility
ended meaning while supporting live regions as an area for screen readers to innovate and compete. 4 ARIA Test Cases ARIA, Accessibility For each example we test the "Expected" results with assistive technologies, for each browser that AT supports WAI-ARIA in. Where a failure occurs we will test the browser for API incorrectness, using tools such as MSAA Inspect. This must be done in order to determine where to file a bug (browser or AT). 5 ARIA annotations ARIA, Accessibility, WAI-ARIA, annotations, comments, details, suggestions WAI-ARIA version 1.3 sees the addition of a set of new features, collectively known as ARIA annotations, which allow the creation of accessible annotations inside web documents. Typical use cases include edit suggestions (i.e...
Web accessibility for seizures and physical reactions - Accessibility
seizure triggered by content that flashes at certain frequencies for more than a few flashes" and goes on to note, very specifically that: "People are even more sensitive to red flashing than to other colors, so a special test is provided for saturated red flashing". You don't even need an image or video to cause harm. A <div> element set to change color and luminosity at high frequency, easily done via JavaScript, can cause real harm. And, flickering can occur everywhere. For example, "spinners" commonly used to display while pages load, can easily "flicker" while spinning. Additional concerns exist for individuals with motor-skills problems. For example, the page for Trace Research & Development Center's Photosensitive Epilepsy Analysis Tool notes that "Photosensitive seizures can be prov...
Web Accessibility: Understanding Colors and Luminance - Accessibility
d have an RGB value of rgb(255, 255, 255) and black, normalized to 0, would have an RGB value of rgb(0,0,0) Where do these numbers of 0 to 255 come from? Historically, graphics engines store the color channels as a single byte; that means a range of integers between 0 and 255. The luminances of the primary colors are different. Yellow has a greater luminance than blue, for example. This was done by way of design, "to achieve white alignment of the monitor" according to the NASA document, "Luminance Contrast in Color Graphics" Once luminance is established, the color contrast ratio can be established. A color contrast ratio is meaningless without its luminance component. Where human perception is concerned, a difference in luminance matters more than a difference in color. This is imp...
Operable - Accessibility
s guideline covers the necessity of making core website functionality available via a keyboard in addition to other means (e.g. mouse), so that users that rely on keyboard controls can access them. Success criteria How to conform to the criteria Practical resource 2.1.1 Keyboard (A) All functionality should be accessible using keyboard controls, unless it cannot be done using the keyboard (e.g. freehand drawing). Built-in controls should be used where possible (e.g. tabbing through form controls), and you should only build in custom functionality where needed. See UI controls and Building keyboard accessibility back in 2.1.2 No keyboard trap (A) When entering a section of functionality using the keyboard, you should be able to get out of that...
-moz-context-properties - CSS: Cascading Style Sheets
e to an SVG image In this example we have a simple SVG embedded using an <img> element. You first need to specify on the embedding element the properties whose values you wish to expose to the embedded SVG, using the -moz-context-properties property. ...
:fullscreen - CSS: Cascading Style Sheets
elects them all. Syntax :fullscreen Usage notes The :fullscreen pseudo-class lets you configure your stylesheets to automatically adjust the size, style, or layout of content when elements switch back and forth between full-screen and traditional presentations. Examples In this example, the color of a button is changed depending on whether or not the document is in full-screen mode. This is done without needing to specifically apply style changes using JavaScript. HTML The page's HTML looks like this: <h1>MDN Web Docs Demo: :fullscreen pseudo-class</h1> <p>This demo uses the <code>:fullscreen</code> pseudo-class to automatically change the style of a button used to toggle full-screen mode on and off, entirely using CSS.</p> <button id="fs-toggle">Toggle Fullscreen</button> The ...
:target - CSS: Cascading Style Sheets
Web › CSS › :target
are shown. Note: A more complete pure-CSS lightbox based on the :target pseudo-class is available on GitHub (demo). HTML <ul> <li><a href="#example1">Open example #1</a></li> <li><a href="#example2">Open example #2</a></li> </ul> <div class="lightbox" id="example1"> <figure> <a href="#" class="close"></a> <figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec felis enim, placerat id eleifend eu, semper vel sem.</figcaption> </figure> </div> <div class="lightbox" id="example2"> <figure> <a href="#" class="close"></a> <figcaption>Cras risus odio, pharetra nec ultricies et, mollis ac augue. Nunc et diam quis sapien dignissim auctor. Quisque quis neque arcu, nec gravida magna.</figcaption> </figure> </div> CSS /* Unopened lig...
unicode-range - CSS: Cascading Style Sheets
, including an ampersand, that we want to style with a different font. To make it obvious, we will use a sans-serif font, Helvetica, for the text, and a serif font, Times New Roman, for the ampersand. In the CSS we are in effect defining a completely separate @font-face that only includes a single character in it, meaning that only this character will be styled with this font. We could also have done this by wrapping the ampersand in a <span> and applying a different font just to that, but that is an extra element and rule set. HTML <div>Me & You = Us</div> CSS @font-face { font-family: 'Ampersand'; src: local('Times New Roman'); unicode-range: U+26; } div { font-size: 4em; font-family: Ampersand, Helvetica, sans-serif; } Result Specifications Specification Sta...
Coordinate systems - CSS: Cascading Style Sheets
ent is presented. Scrolling is not a factor. On a desktop computer, for example, the MouseEvent.clientX and MouseEvent.clientY properties indicate the position of the mouse cursor at the moment the event occurred, relative to the top-left corner of the browser window. The top-left corner of the window is always (0, 0), regardless of the content of the document or any scrolling that may have been done. In other words, scrolling the document will change the client coordinates of a given position within the document. Page The "page" coordinate system gives the position of a pixel relative to the top-left corner of the entire Document in which the pixel is located. That means that a given point in an element within the document will keep the same coordinates in the page model unless the element...
Detecting CSS animation support - CSS: Cascading Style Sheets
refixing each attribute as it's constructed. This variable, once constructed, contains the complete description of all the keyframes needed by our animation sequence. The next task is to actually add the keyframes to the page's CSS. The first thing to do is look to see if there's already a style sheet on the document; if so, we simply insert the keyframe description into that stylesheet; this is done in lines 13-15. If there isn't already a style sheet, a new <style> element is created, and its content is set to the value of keyframes. Then the new <style> element is inserted into the document's <head>, thereby adding the new style sheet to the document. View on JSFiddle ...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
To make that happen, we have to be creative. Here's what happens when the play() function gets called: The box's list of CSS classes is reset to simply "box". This has the effect of removing any other classes currently applied to the box, including the "changing" class that handles animation. In other words, we're removing the animation...
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
grab the // first item in the list and just return that. @if type-of($fg) == 'list' { $fg-boxflex: nth($fg, 1); } -webkit-box: $fg-boxflex; -moz-box: $fg-boxflex; -webkit-flex: $fg $fs $fb; -ms-flex: $fg $fs $fb; flex: $fg $fs $fb; } Flexbox justify content The justify-content property aligns flex items along the main axis of the current line of the flex container. This is done after any flexible lengths and any auto margins have been resolved. Typically, it helps to distribute extra free space leftover when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line. Note: space-* values not supported in older syntaxes. Values: flex-sta...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
see more information on browser support in the MDN documentation for writing-mode. However if you are planning on using writing modes in your layout, carefully testing the results is advisable -- not least because it would be easy to make things hard to read! Note that you would not normally use CSS and the writing-mode property to change an entire document to another writing mode. This would be done via HTML, by adding a dir and lang attribute to the html element to indicate the document language and default text direction. This would mean that the document would display correctly even if CSS did not load. Flexbox and other layout methods The flexbox specification contains a definition of what happens if an item uses another layout method and then becomes a flex item. For example, if an it...
Typical use cases of Flexbox - CSS: Cascading Style Sheets
nsions of the items in that one dimension, or control the spacing between items. These are the uses that flexbox was designed for. You can read more about the difference between flexbox and CSS Grid Layout in Relationship of Flexbox to other layout methods, where we discuss how flexbox fits into the overall picture of CSS Layout. In reality we also often use Flexbox for jobs that might be better done by Grid Layout, as a fallback for Grid, and also in order to get alignment capabilities. This is something that may well change once Box Alignment is implemented in Block Layout. In this guide I look at some of the typical things you might use flexbox for today. Navigation A common pattern for navigation is to have a list of items displayed as a horizontal bar. This pattern, as basic as it seem...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
ap. However sometimes, we are laying things out that don't have a logical order and we would like to create a layout that doesn't have gaps in it. To do this, add the property grid-auto-flow with a value of dense to the container. This is the same property you use to change the flow order to column, so if you were working in columns you would add both values grid-auto-flow: column dense. Having done this, grid will now backfill the gaps, as it moves through the grid it leaves gaps as before, but then if it finds an item that will fit in a previous gap it will pick it up and take it out of DOM order to place it in the gap. As with any other reordering in grid this does not change the logical order. Tab order for example, will still follow the document order. We will take a look at the potenti...
Grid template areas - CSS: Cascading Style Sheets
t you can actually see, right there in the CSS, what this layout looks like. Spanning multiple cells In our example each of the areas spans multiple grid cells and we achieve this by repeating the name of that grid area multiple times with white space between. You can add extra white space in order to keep your columns neatly lined up in the value of grid-template-areas. You can see that I have done this in order that the hd and ft line up with main. The area that you create by chaining the area names must be rectangular, at this point there is no way to create an L-shaped area. The specification does note that a future level might provide this functionality. You can however span rows just as easily as columns. For example we could make our sidebar span down to the end of the footer by repl...
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
ea. The specification defines the behavior when a grid container is a containing block and a parent of the absolutely positioned item. A grid container as containing block To make the grid container a containing block you need to add the position property to the container with a value of relative, just as you would make a containing block for any other absolutely positioned items. Once you have done this, if you give a grid item position: absolute it will take as its containing block the grid container or, if the item also has a grid position, the area of the grid it is placed into. In the below example I have a wrapper containing four child items. Item three is absolutely positioned and also placed on the grid using line-based placement. The grid container has position: relative and so bec...
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
hare the same namespace. Thus, the example URL would point to the heading "example" in this document. Suppose you wish to style any h2 element that is the target of a URL, but do not want any other kind of element to get a target style. This is simple enough: h2:target { font-weight: bold; } It's also possible to create styles that are specific to a particular fragment of the document. This is done using the same identifying value that is found in the URI. Thus, to add a border to the #example fragment, we would write: #example:target { border: 1px solid black; } Targeting all elements If the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy: :target { color: red; } Example In the following example, there are fi...
Using CSS transforms - CSS: Cascading Style Sheets
...
Recipe: Media objects - CSS: Cascading Style Sheets
ixels and as the image has a max-width of 100% applied, it scales down so that it continues to fit inside the column. By using grid-template-areas to achieve the layout, I can see the pattern in the CSS. I define my grid once we have a max-width of 500 pixels, so on smaller devices the media object stacks. An option for the pattern is to flip it to switch the image to the other side -- this is done by adding the media-flip class, which defines a flipped grid template causing the layout to be mirrored. When we nest one media object inside another we need to place it into the second track in the regular layout, and the first track when flipped. Fallbacks There are a number of possible fallbacks for this pattern, depending on the browsers you wish to support. A good catch-all would be to fl...
Privacy and the :visited selector - CSS: Cascading Style Sheets
This process was quick to execute, and made it possible not only to determine where the user had been on the web, but could also be used to guess a lot of information about the user's identity. To mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. ...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
ties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts. Custom properties are subject to the cascade and inherit their value from their parent. Basic usage Declaring a custom property is done using a custom property name that begins with a double hyphen (--), and a property value that can be any valid CSS value. Like any other property, this is written inside a ruleset, like so: element { --main-bg-color: brown; } Note that the selector given to the ruleset defines the scope that the custom property can be used in. A common best practice is to define custom properties on the :roo...
border-bottom-left-radius - CSS: Cascading Style Sheets
semi-major and semi-minor axes) of the ellipse defining the curvature of the corner. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. The rounding can be a circle or an ellipse, or if one of the value is 0 no rounding is done and the corner is square. A background, being an image or a color, is clipped at the border, even a rounded one; the exact location of the clipping is defined by the value of the background-clip property. Note: If the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-bottom-left-radius CSS property, the value of this proper...
border-bottom-right-radius - CSS: Cascading Style Sheets
semi-major and semi-minor axes) of the ellipse defining the curvature of the corner. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. The rounding can be a circle or an ellipse, or if one of the value is 0 no rounding is done and the corner is square. A background, being an image or a color, is clipped at the border, even a rounded one; the exact location of the clipping is defined by the value of the background-clip property. Note: If the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-bottom-right-radius CSS property, the value of this prope...
border-top-left-radius - CSS: Cascading Style Sheets
semi-major and semi-minor axes) of the ellipse defining the curvature of the corner. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. The rounding can be a circle or an ellipse, or if one of the value is 0,no rounding is done and the corner is square. A background, being an image or a color, is clipped at the border, even a rounded one; the exact location of the clipping is defined by the value of the background-clip property. Note: If the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-top-left-radius CSS property, the value of this property ...
border-top-right-radius - CSS: Cascading Style Sheets
semi-major and semi-minor axes) of the ellipse defining the curvature of the corner. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. The rounding can be a circle or an ellipse, or if one of the value is 0 no rounding is done and the corner is square. A background, being an image or a color, is clipped at the border, even a rounded one; the exact location of the clipping is defined by the value of the background-clip property. Note: If the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-top-right-radius CSS property, the value of this property...
break-inside - CSS: Cascading Style Sheets
umn; break-inside: avoid-region; /* Global values */ break-inside: inherit; break-inside: initial; break-inside: unset; Each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. To determine if a break must be done, the following rules are applied: If any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. If more than one of them are such a break, the value of the element that appears the latest in the flow is used. Thus, the break-before value has precedence over the break-after value, which in turn has precedence over the break-insid...
clamp() - CSS: Cascading Style Sheets
Web › CSS › clamp
sit amet. Fusce iaculis, libero quis elementum viverra, nulla ante accumsan lectus, sit amet convallis lacus ipsum vel est. Curabitur et urna non est consectetur pulvinar vel id risus. Ut vestibulum, sem in semper aliquet, felis arcu euismod sapien, ac imperdiet massa nisl quis sem. Vestibulum ac elementum felis, in tempor velit. Pellentesque purus ex, mattis at ornare quis, porta condimentum mi. Donec vestibulum ligula vel nulla blandit, quis euismod nulla vestibulum. Suspendisse potenti. Nunc neque mauris, tempor sed facilisis at, ultrices eget nulla. Pellentesque convallis ante nec augue porttitor, id tempus ante luctus.</p> <p>Integer rutrum sollicitudin tellus, quis cursus nulla scelerisque nec. Nunc eu facilisis lorem. Maecenas faucibus sapien eleifend, semper tellus at, pharetra quam. ...
float - CSS: Cascading Style Sheets
Web › CSS › float
l enough to encompass it's floated children, and to make sure it takes up the width of the parent so we don't have to clear it's adjacent sibling. HTML <section> <div class="left">1</div> <div class="left">2</div> <div class="right">3</div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique sapien ac erat tincidunt, sit amet dignissim lectus vulputate. Donec id iaculis velit. Aliquam vel malesuada erat. Praesent non magna ac massa aliquet tincidunt vel in massa. Phasellus feugiat est vel leo finibus congue.</p> </section> CSS section { border: 1px solid blue; width: 100%; float: left; } div { margin: 5px; width: 50px; height: 150px; } .left { float: left; background: pink; } .right { float: right; background: cyan...
font-family - CSS: Cascading Style Sheets
e at least one generic family name in a font-family list, since there's no guarantee that any given font is available. This lets the browser select an acceptable fallback font when necessary. The font-family property specifies a list of fonts, from highest priority to lowest. Font selection does not simply stop at the first font in the list that is on the user's system. Rather, font selection is done one character at a time, so that if an available font does not have a glyph for a needed character, the latter fonts are tried. (However, this doesn't work in Internet Explorer 6 or earlier.) When a font is only available in some styles, variants, or sizes, those properties may also influence which font family is chosen. Syntax /* A font family name and a generic family name */ font-family: Gil...
image() - CSS: Cascading Style Sheets
the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 This feature can help improve accessibility by providing a fallback color when an image fails to load. While this can and should be done by including a background-color on every background image, the CSS image() function allows adding allows only including background colors should an image fail to load, which means you can add a fall back color should a transparent PNG/GIF/WebP not load. Examples Directionally-sensitive images <ul> <li dir="ltr">Bullet is a right facing arrow on the left</li> <li dir="rtl">Bullet is the sa...
<integer> - CSS: Cascading Style Sheets
Web › CSS › integer
ycle there was a lot of discussion about setting a minimum range to support: the latest decision, in April 2012 during the LC phase, was [-227-1; 227-1], but other values like 224-1 and 230-1 were also proposed. However, the latest spec doesn't specify a range anymore. Interpolation When animated, values of the <integer> data type are interpolated using discrete, whole steps. The calculation is done as if they were real, floating-point numbers; the discrete value is obtained using the floor function. The speed of the interpolation is determined by the timing function associated with the animation. Examples Valid integers 12 Positive integer (without a leading + sign) +123 Positive integer (with a leading + sign) -456 Negative integer 0 Zero +0 Zer...
justify-content - CSS: Cascading Style Sheets
main-axis of a flex container, and the inline axis of a grid container. The interactive example below demonstrates some of the values using Grid Layout. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. The alignment is done after the lengths and auto margins are applied, meaning that, if in a Flexbox layout there is at least one flexible element, with flex-grow different from 0, it will have no effect as there won't be any available space. Syntax /* Positional alignment */ justify-content: center; /* Pack items around the center */ justify-content: start; /* Pack items from the start */ justify-content: e...
<length> - CSS: Cascading Style Sheets
Web › CSS › length
oot element's inline axis. vb Equal to 1% of the size of the initial containing block, in the direction of the root element's block axis. vmin Equal to the smaller of vw and vh. vmax Equal to the larger of vw and vh. Absolute length units Absolute length units represent a physical measurement when the physical properties of the output medium are known, such as for print layout. This is done by anchoring one of the units to a physical unit, and then defining the others relative to it. The anchor is done differently for low-resolution devices, such as screens, versus high-resolution devices, such as printers. For low-dpi devices, the unit px represents the physical reference pixel; other units are defined relative to it. Thus, 1in is defined as 96px, which equals 72pt. The consequenc...
scale() - CSS: Cascading Style Sheets
The scale() CSS function defines a transformation that resizes an element on the 2D plane. Because the amount of scaling is defined by a vector, it can resize the horizontal and vertical dimensions at different scales. Its result is a <transform-function> data type. This scaling transformation is characterized by a two-dimensional vector. Its coordinates define how much scaling is done in each direction. If both coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation). When a coordinate value is outside the [-1, 1] range, the element grows along that dimension; when inside, it shrinks. If it is negative, the result a point reflection in that dimension. A value of 1 has no effect. Note: The scale() fun...
scale3d() - CSS: Cascading Style Sheets
les. Its result is a <transform-function> data type. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. This scaling transformation is characterized by a three-dimensional vector. Its coordinates define how much scaling is done in each direction. If all three coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation). When a coordinate value is outside the [-1, 1] range, the element grows along that dimension; when inside, it shrinks. If it is negative, the result a point reflection in that dimension. A value of 1 has no effect. Synt...
CSS: Cascading Style Sheets
Web › CSS
scribe the presentation of a document written in HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS describes how elements should be rendered on screen, on paper, in speech, or on other media. CSS among the core languages of the open Web and is standardized across Web browsers according to the W3C specification. Previously development of various parts of CSS specification was done synchronously, which allowed versioning of the latest recommendation. You might have heard about CSS1, CSS2.1, CSS3. However, CSS4 has never become an official version. From CSS3, the scope of the specification increased significantly and the progress on different CSS modules started to differ so much, that it became more effective to develop and release recommendations separately per module. In...
Event reference
ging an element or text selection (use dragstart instead). mousewheel IE invented The wheel button of a pointing device is rotated. MozAudioAvailable Event Mozilla specific The audio buffer is full and the corresponding raw samples are available. MozBeforeResize Mozilla specific A window is about to be resized. mozbrowseractivitydone Firefox OS Browser API-specific Sent when some activity has been completed (complete description TBD.) mozbrowserasyncscroll Firefox OS Browser API-specific Sent when the scroll position within a browser <iframe> changes. mozbrowseraudioplaybackchange Firefox OS Browser API-specific Sent when audio starts or stops playing within the browser <iframe>...
Setting up adaptive streaming media sources - Developer guides
k --> <source src="my.mp4" type="video/mp4"> <source src="my.webm" type="video/webm"> </video> LIVE Profile A useful piece of software when dealing with MPEG-DASH is Dash Encoder. This uses MP4Box to encode media into MPEG-DASH format. Note: You will need to be comfortable with make files and installing dependencies to get this software up and running. Note: Since MPEG-DASH decoding is done partially using JavaScript and MSE files are often grabbed using XHR, keep same origin rules in mind. Note: If you use WebM you can use the methods shown in this tutorial DASH Adaptive Streaming for HTML 5 Video. Once encoded your file structure may look something like this: play list -> /segments/news.mp4.mpd main segment folder -> /segments/main/ 100 Kbps segment fol...
Audio and Video Delivery - Developer guides
setting the src attribute to an empty string will actually cause the browser to treat it as though you're setting a video source to a relative path. This causes the browser to attempt another download to something that is unlikely to be a valid video. Seeking through media Media elements provide support for moving the current playback position to specific points in the media's content. This is done by setting the value of the currentTime property on the element; see HTMLMediaElement for further details on the element's properties. Simply set the value to the time, in seconds, at which you want playback to continue. You can use the element's seekable property to determine the ranges of the media that are currently available for seeking to. This returns a TimeRanges object listing the ranges...
DOM onevent handlers - Developer guides
ents have attributes named onevent which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes' values using JavaScript will get the value set in the HTML. Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect. HTML Given this HTML document: <p>Demonstrating quirks of <code>on<em>event</em></code> HTML attributes on <a onclick="log('Click!')">these three words</a>. </p> <div></div> JavaScript Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
> element, just like any other type of image. WebGL The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See our WebGL tutorial to find out more. How to describe a color In order to represent a color in CSS, you have to find a way to translate the analog concept of "color" into a digital form that a computer can use. This is typically done by breaking down the color into components, such as how much of each of a set of primary colors to mix together, or how bright to make the color. As such, there are several ways you can describe color in CSS. For more detailed discussion of each of the color value types, see the reference for the CSS <color> unit. Keywords A set of standard color names have been defined, letting you use these ...
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
Web app manifest. Requires the use of the CORS protocol for cross-origin fetching. modulepreload Useful for improved performance, and relevant to the <link> anywhere in the document, setting rel="modulepreload" tells the browser to preemptively fetch the script (and dependencies) and store it in the document's module map for later evaluation. modulepreload links can ensure network fetching is done with the module ready (but not evaluated) in the module map before it is necessarily needed. See also link types: modulepreload. next Relevant to <form>, <link>, <a>, and <area>, the next values indicates that the current document is a part of a series, and that the next document in the series is the referenced document. When included in a <link>, browsers may assume that document will be fetch...
Date and time formats used in HTML - HTML: Hypertext Markup Language
eparating them. No information about the time zone is included in the string; the date and time is presumed to be in the user's local time zone. When you set the value of a datetime-local input, the string is normalized into a standard form. Normalized datetime strings always use the letter "T" to separate the date and the time, and the time portion of the string is as short as possible. This is done by leaving out the seconds component if its value is :00. Examples of valid datetime-local strings Date/time string Normalized date/time string Actual date and time 1986-01-28T11:38:00.01 1986-01-28T11:38:00.01 January 28, 1986 at 11:38:00.01 AM 1986-01-28 11:38:00.010 1986-01-28T11:38:00.011 January 28, 1986 at 11:38:00.01 AM 0170-07-31...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
art of the content (it's decoration or a tracking pixel), and that non-visual browsers may omit it from rendering. Visual browsers will also hide the broken image icon if the alt is empty and the image failed to display. This attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark. crossorigin Indicates if the fetching of the image must be done using a CORS request. Image data from a CORS-enabled image returned from a CORS request can be reused in the <canvas> element without being marked "tainted". If the crossorigin attribute is not specified, then a non-CORS request is sent (without the Origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> element...
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
ill be taken if the user presses the Enter or Return key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard. Note: This has been standardized as the global attribute enterkeyhint, but is not yet widely implemented. To see the status of the change being implemented in Firefox, see bug 1490661. Permitted values are: go, done, next, search, and send. The browser decides, using this hint, what label to put on the enter key. results The results attribute--supported only by Safari--is a numeric value that lets you override the maximum number of entries to be displayed in the <input> element's natively-provided drop-down menu of previous search queries. The value must be a non-negative decimal number. If not provide...
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
ill be taken if the user presses the Enter or Return key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard. Note: This has been standardized as the global attribute enterkeyhint, but is not yet widely implemented. To see the status of the change being implemented in Firefox, see bug 1490661. Permitted values are: go, done, next, search, and send. The browser decides, using this hint, what label to put on the enter key. Using tel inputs Telephone numbers are a very commonly collected type of data on the web. When creating any kind of registration or e-commerce site, for example, you will likely need to ask the user for a telephone number, whether for business purposes or for emergency contact purposes. Given how ...
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
ill be taken if the user presses the Enter or Return key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard. Note: This has been standardized as the global attribute enterkeyhint, but is not yet widely implemented. To see the status of the change being implemented in Firefox, see bug 1490661. Permitted values are: go, done, next, search, and send. The browser decides, using this hint, what label to put on the enter key. Using text inputs <input> elements of type text create basic, single-line inputs. You should use them anywhere you want the user to enter a single-line value and there isn't a more specific input type available for collecting that value (for example, if it's a date, URL, email, or search term, yo...
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
ill be taken if the user presses the Enter or Return key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard. Note: This has been standardized as the global attribute enterkeyhint, but is not yet widely implemented. To see the status of the change being implemented in Firefox, see bug 1490661. Permitted values are: go, done, next, search, and send. The browser decides, using this hint, what label to put on the enter key. Using URL inputs When you create a URL input with the proper type value, url, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mis-types their web site's address, or provides an inval...
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › marquee
rnate"> This text will bounce </marquee> </marquee> Specifications Specification Status Comment HTML Living StandardThe definition of '<marquee>' in that specification. Living Standard Make it obsolete in favor of CSS but define its expected behavior, for backward compatibility. However, the development of the marquee features of CSS have since been abandoned. HTML5The definition of '<marquee>' in that specification. Recommendation Make it obsolete in favor of CSS but define its expected behavior, for backward compatibility. However, the development of the marquee features of CSS have since been abandoned. ...
<sup>: The Superscript element - HTML: Hypertext Markup Language
Web › HTML › Element › sup
Attributes This element only includes the global attributes. Usage notes The <sup> element should only be used for typographical reasons--that is, to change the position of the text to comply with typographical conventions or standards, rather than solely for presentation or appearance purposes. For example, to style the wordmark of a business or product which uses a raised baseline should be done using CSS (most likely vertical-align) rather than <sup>. This would be done using, for example, vertical-align: super or, to shift the baseline up 50%, vertical-align: 50%. Appropriate use cases for <sup> include (but aren't necessarily limited to): Displaying exponents, such as "x3." It may be worth considering the use of MathML for these, especially in more complex cases. See Exponents und...
<tbody>: The Table Body element - HTML: Hypertext Markup Language
Web › HTML › Element › tbody
other cell borders. Result The resulting table looks like this: Multiple bodies You can create multiple sections within a table by using multiple <tbody> elements. Each may potentially have its own header row or rows; however, there can be only one <thead> per table! Because of that, you need to use a <tr> filled with <th> elements to create headers within each <tbody>. Let's see how that's done. Let's take the previous example, add some more students to the list, and update the table so that instead of listing each student's major on every row, the students are grouped by major, with heading rows for each major. Result First, the resulting table, so you know what we're building: HTML The revised HTML looks like this: <table> <thead> <tr> <th>Student ID</th> <th...
style - HTML: Hypertext Markup Language
itHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Usage note: This attribute must not be used to convey semantic information. Even if all styling is removed, a page should remain semantically correct. Typically it shouldn't be used to hide irrelevant information; this should be done using the hidden attribute. Specifications Specification Status Comment HTML Living StandardThe definition of 'style' in that specification. Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'style' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The definiti...
Using the application cache - HTML: Hypertext Markup Language
n cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. This speeds up the document load time. The browser then checks to see if the cache manifest has been updated on the server. If the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. This is done in the background and does not affect performance significantly. The process for loading documents and updating the application cache is specified in greater detail below: When the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first versi...
Data URLs - HTTP
ncoding of a file or string on Linux and Mac OS X systems can be achieved using the command-line base64 (or, as an alternative, the uuencode utility with -m argument). echo -n hello|base64 # outputs to console: aGVsbG8= echo -n hello>a.txt base64 a.txt # outputs to console: aGVsbG8= base64 a.txt>b.txt # outputs to file b.txt: aGVsbG8= Encoding on Microsoft Windows Encoding on Windows can be done through powershell or some dedicated tool. It can even be done via bash base64 utility (see section Encoding on a Unix system) if WSL is activated. [convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("hello")) # outputs to console: aGVsbG8= bash -c "echo -n hello`|base64" # outputs to console: aGVsbG8= # the backtick (`) is used to escape the piping (|) character here Common problems Th...
Evolution of HTTP - HTTP
tensibility - creating new headers or methods is easy - and even if the HTTP/1.1 protocol was refined over two revisions, RFC 2616 published in June 1999 and the series of RFC 7230-RFC 7235 published in June 2014 in prevision of the release of HTTP/2, this protocol has been extremely stable over more than 15 years. Using HTTP for secure transmissions The largest change that happened to HTTP was done as early as end of 1994. Instead of sending HTTP over a basic TCP/IP stack, Netscape Communications created an additional encrypted transmission layer on top of it: SSL. SSL 1.0 was never released outside the company, but SSL 2.0 and its successor SSL 3.0 allowed for the creation of e-commerce Web sites by encrypting and guaranteeing the authenticity of the messages exchanged between the server a...
Browser detection using the user agent - HTTP
Internet Explorer ; MSIE xyz; [1] Trident/7.0; .*rv:xyz [2] [1] Internet Explorer 10- [2] Internet Explorer 11 Of course, there is absolutely no guarantee that another browser will not hijack some of these things (like Chrome hijacked the Safari string in the past). That's why browser detection using the user agent string is unreliable and should be done only with the check of the version number (hijacking of past versions is less likely). Browser version The browser version is often, but not always, put in the value part of the BrowserName/VersionNumber token in the User Agent String. This is of course not the case for Internet Explorer (which puts the version number right after the MSIE token), and for Opera after version 10, which has added ...
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
...
Compression in HTTP - HTTP
onary that add to the initial size) can be higher than the extra gain in compression resulting in a larger file. Do not use the two following techniques for files in a compressed format. End-to-end compression For compression, end-to-end compression is where the largest performance improvements of Web sites reside. End-to-end compression refers to a compression of the body of a message that is done by the server and will last unchanged until it reaches the client. Whatever the intermediate nodes are, they leave the body untouched. All modern browsers and servers do support it and the only thing to negotiate is the compression algorithm to use. These algorithm are optimized for text. In the 1990s, compression technology was advancing at a rapid pace and numerous successive algorithms have...
Accept-Charset - HTTP
Content-Type response header, usually in a charset= parameter. Browsers usually don't send this header, as the default value for each resource is usually correct and transmitting it would allow fingerprinting. If the server cannot serve any character encoding from this request header, it can theoretically send back a 406 Not Acceptable error code. But for a better user experience, this is rarely done and the Accept-Charset header is ignored. In early versions of HTTP/1.1, a default character encoding was defined: ISO-8859-1. This is no longer recommended, and now each content-type may have its own default. UTF-8 is now well-supported and the overwhelmingly preferred character encoding. To guarantee better privacy through less configuration-based entropy, all browsers omit the Accept-Charse...
Accept-Language - HTTP
the Accept-Language is often out of the control of the user (like when traveling and using an Internet Cafe in a different country); the user may also want to visit a page in another language than the locale of their user interface. If the server cannot serve any matching language, it can theoretically send back a 406 (Not Acceptable) error code. But, for a better user experience, this is rarely done and more common way is to ignore the Accept-Language header in this case. Header type Request header Forbidden header name no CORS-safelisted request header yes, with the additional restriction that values can only be 0-9, A-Z, a-z, space or *,-.;=. Syntax Accept-Language: <language> Accept-Language: * // Multiple types, weighted with the quality valu...
Accept - HTTP
Web › HTTP › Headers › Accept
The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending on the context where the request is done: when fetching a CSS stylesheet a different value is set for the request than when fetching an image, video or a script. Header type Request header Forbidden header name no CORS-safelisted request header yes, with the additional restriction that values can't contain a CORS-unsafe request header byte: 0x00-0x1F (except 0x09 (HT)), "():<>?@[\]{}, and 0x7F (DEL). Syntax Accept: <MIME...
Connection - HTTP
Connection-specific header fields such as Connection and Keep-Alive are prohibited in HTTP/2. Chrome and Firefox ignore them in HTTP/2 responses, but Safari conforms to the HTTP/2 spec requirements and won't load any response which contains them. ...
Content-Disposition - HTTP
_charset_' indicates that the part is not an HTML field, but the default charset to use for parts without explicit charset information. filename Is followed by a string containing the original name of the file transmitted. The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. This parameter provides mostly indicative information. When used in combination with Content-Disposition: attachment, it is used as the default filename for an eventual "Save As" dialog presented to the user. filename* The parameters filename and filename* differ only in that filename* uses the encoding defined in RFC 5987. When both filename and filename* are present in a single header fiel...
Content-Security-Policy-Report-Only - HTTP
report-uri /_/csp-reports", "disposition": "report" } } As you can see, the report includes the full path to the violating resource in blocked-uri. This is not always the case. For example, when the signup.html would attempt to load CSS from http://anothercdn.example.com/stylesheet.css, the browser would not include the full path but only the origin (http://anothercdn.example.com). This is done to prevent leaking sensitive information about cross-origin resources. Specifications Specification Status Comment Content Security Policy Level 3 Working Draft No changes. Content Security Policy Level 2 Recommendation Initial definition. ...
If-Match - HTTP
Web › HTTP › Headers › If-Match
n guarantee that the new ranges requested comes from the same resource than the previous one. If it doesn't match, then a 416 (Range Not Satisfiable) response is returned. For other methods, and in particular for PUT, If-Match can be used to prevent the lost update problem. It can check if the modification of a resource that the user wants to upload will not override another change that has been done since the original resource was fetched. If the request cannot be fulfilled, the 412 (Precondition Failed) response is returned. Header type Request header Forbidden header name no Syntax If-Match: <etag_value> If-Match: <etag_value>, <etag_value>, ... Directives <etag_value> Entity tags uniquely representing the requested resources. They are a string of AS...
If-Unmodified-Since - HTTP
d resource, or accept it in the case of a POST or another non-safe method, only if it has not been last modified after the given date. If the resource has been modified after the given date, the response will be a 412 (Precondition Failed) error. There are two common use cases: In conjunction with non-safe methods, like POST, it can be used to implement an optimistic concurrency control, like done by some wikis: editions are rejected if the stored document has been modified since the original has been retrieved. In conjunction with a range request with a If-Range header, it can be used to ensure that the new fragment requested comes from an unmodified document. Header type Request header Forbidden header name no Syntax If-Unmodified-Since: <day-name>, <da...
X-DNS-Prefetch-Control - HTTP
measurably improved in this way. If the domain names for images can be resolved in advance of the images being requested, pages that load many images can see an improvement of 5% or more in the time of loading images. Configuring prefetching in the browser In general, you don't need to do anything to manage prefetching. However, the user may wish to disable prefetching. On Firefox, this can be done by setting the network.dns.disablePrefetch preference to true. Also, by default, prefetching of embedded link hostnames is not performed on documents loaded over HTTPS. On Firefox, this can be changed by setting the network.dns.disablePrefetchFromHTTPS preference to false. Examples Turning on and off prefetching You can either send the X-DNS-Prefetch-Control header server-side, or from indivi...
HTTP Messages - HTTP
Web › HTTP › Messages
et to chunked. Multiple-resource bodies, consisting of a multipart body, each containing a different section of information. These are relatively rare. HTTP/2 Frames HTTP/1.x messages have a few drawbacks for performance: Headers, unlike bodies, are uncompressed. Headers are often very similar from one message to the next one, yet still repeated across connections. No multiplexing can be done. Several connections need opening on the same server: and warm TCP connections are more efficient than cold ones. HTTP/2 introduces an extra step: it divides HTTP/1.x messages into frames which are embedded in a stream. Data and header frames are separated, this allows header compression. Several streams can be combined together, a process called multiplexing, allowing more efficient underlying...
Protocol upgrade mechanism - HTTP
ere we look at the most common use cases for the Upgrade header. Upgrading to a WebSocket connection By far, the most common use case for upgrading an HTTP connection is to use WebSockets, which are always implemented by upgrading an HTTP or HTTPS connection. Keep in mind that if you're opening a new connection using the WebSocket API, or any library that does WebSockets, most or all of this is done for you. For example, opening a WebSocket connection is as simple as: webSocket = new WebSocket("ws://destination.server.ext", "optionalProtocol"); The WebSocket() constructor does all the work of creating an initial HTTP/1.1 connection then handling the handshaking and upgrade process for you. You can also use the "wss://" URL scheme to open a secure WebSocket connection. If you need to cr...
Proxy Auto-Configuration (PAC) file - HTTP
tname is passed, it will be resolved into an IP address by this function. pattern an IP address pattern in the dot-separated format. mask mask for the IP address pattern informing which parts of the IP address should be matched against. 0 means ignore, 255 means match. True if and only if the IP address of the host matches the specified IP address pattern. Pattern and mask specification is done the same way as for SOCKS configuration. Examples: function alert_eval(str) { alert(str + ' is ' + eval(str)) } function FindProxyForURL(url, host) { alert_eval('isInNet(host, "63.245.213.24", "255.255.255.255")') // "PAC-alert: isInNet(host, "63.245.213.24", "255.255.255.255") is true" } dnsResolve() dnsResolve(host) Parameters host hostname to resolve. Resolves the given DNS hos...
HTTP resources and specifications - HTTP
This page lists relevant resources about HTTP. ...
511 Network Authentication Required - HTTP
Web › HTTP › Status › 511
tes that the client needs to authenticate to gain network access. This status is not generated by origin servers, but by intercepting proxies that control access to the network. Network operators sometimes require some authentication, acceptance of terms, or other user interaction before granting access (for example in an internet cafe or at an airport). They often identify clients who have not done so using their Media Access Control (MAC) addresses. Status 511 Network Authentication Required Specifications Specification Title RFC 6585, section 6: 511 Network Authentication Required Additional HTTP Status Codes ...
HTTP response status codes - HTTP
Web › HTTP › Status
ource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code. 406 Not Acceptable This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent. 407 Proxy Authentication Required This is similar to 401 but authentication is needed to be done by a proxy. 408 Request Timeout This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut...
HTTP
Web › HTTP
ce documentation. HTTP Headers HTTP message headers are used to describe a resource, or the behavior of the server or the client. Custom proprietary headers can be added using the X- prefix; others in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP message headers. HTTP Request Methods The different operations that can be done with HTTP: GET, POST, and also less common requests like OPTIONS, DELETE, or TRACE. HTTP Status Response Codes HTTP response codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors. CSP directives The Content-Security-Policy response ...
Functions - JavaScript
scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (The reason it is called "chaining" is explained later.) Consider the following example: function A(x) { function B(y) { function C(z) { console.log(x + y + z); } C(3); } B(2); } A(1); // logs 6 (1 + 2 + 3) In this example, C accesses B's y and A's x. This can be done because: B forms a closure including A (i.e. B can access A's arguments and variables). C forms a closure including B. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A, in that order. The reverse, however, is not true. A cannot access C, because A cannot access any argument or variabl...
JavaScript modules - JavaScript
could always use .mjs during development and convert them to .js during your build step. It is also worth noting that: Some tools may never support .mjs, such as TypeScript. The <script type="module"> attribute is used to denote when a module is being pointed to, as you'll see below. Exporting module features The first thing you do to get access to module features is export them. This is done using the export statement. The easiest way to use it is to place it in front of any items you want exported out of the module, for example: export const name = 'square'; export function draw(ctx, length, x, y, color) { ctx.fillStyle = color; ctx.fillRect(x, y, length, length); return { length: length, x: x, y: y, color: color }; } You can export functions, var, let, ...
Regular expression syntax cheatsheet - JavaScript
kslash; for example, /a\*/ matches "a*". Note that some characters like :, -, @, etc. neither have a special meaning when escaped nor when unescaped. Escape sequences like \:, \-, \@ will be equivalent to their literal, unescaped character equivalents in regular expressions. However, in regular expressions with the unicode flag, these will cause an invalid identity escape error. This is done to ensure backward compatibility with existing code that uses new escape sequences like \p or \k. To match this character literally, escape it with itself. In other words to search for \ use /\\/. Assertions If you are looking to contribute to this document, please also edit the original article Boundary-type assertions Characters Meaning ^ ...
Using Promises - JavaScript
result3) */ Timing To avoid surprises, functions passed to then() will never be called synchronously, even with an already-resolved promise: Promise.resolve().then(() => console.log(2)); console.log(1); // 1, 2 Instead of running immediately, the passed-...
Working with objects - JavaScript
bjectToInspect)) { result = result.concat( Object.getOwnPropertyNames(objectToInspect) ); } return result; } This can be useful to reveal "hidden" properties (properties in the prototype chain which are not accessible through the object, because another property has the same name earlier in the prototype chain). Listing accessible properties only can easily be done by removing duplicates in the array. Creating new objects JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator. Using object initializers In addition t...
Memory Management - JavaScript
ing // Since strings are immutable values, // JavaScript may decide to not allocate memory, // but just store the [0, 3] range. var a = ['ouais ouais', 'nan nan']; var a2 = ['generation', 'nan nan']; var a3 = a.concat(a2); // new array with 4 elements being // the concatenation of a and a2 elements. Using values Using values basically means reading and writing in allocated memory. This can be done by reading or writing the value of a variable or an object property or even passing an argument to a function. Release when the memory is not needed anymore The majority of memory management issues occur at this phase. The most difficult aspect of this stage is determining when the allocated memory is no longer needed. Low-level languages require the developer to manually determine at which p...
constructor - JavaScript
nd initializing an object of that class. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax constructor([arguments]) { ... } Description A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object. class Person { constructor(name) { this.name = name; } introduce() { console.log(`Hello, my name is ${this.name}`); } } const otto = new Person('Otto'); otto.introduce(); If you don't provide your own constructor, then a default constructor will be supplied for you. If your class is a base class, the default ...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
ables in JavaScript can't be deleted using the delete operator. In strict mode, an attempt to delete a variable will throw an error and is not allowed. The delete operator can only delete properties on an object. Object properties are "qualified" if they are configurable. Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references, see the memory management page and the delete operator page for more details. This error only happens in strict mode code. In non-strict code, the operation just returns false. Examples Freeing the contents of a variable Attempting to delete a plain variable, doesn't work in JavaScript and it throws an error in strict mode: 'use strict'; var x; // ... d...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
ring method if you just want to format one date. var today = new Date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var date = today.toLocaleDateString('de-DE', options); console.log(date); // "Freitag, 10. Marz 2017" Or, you can make use of the Intl.DateTimeFormat object, which allows you to cache an object with most of the computations done so that formatting is fast. This is useful if you have a loop of dates to format. var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var dateFormatter = new Intl.DateTimeFormat('de-DE', options) var dates = [Date.UTC(2012, 11, 20, 3, 0, 0), Date.UTC(2014, 04, 12, 8, 0, 0)]; dates.forEach(date => console.log(dateFormatter.format(date)...
Array.prototype.slice() - JavaScript
myCar[0].color = purple newCar[0].color = purple Array-like objects slice method can also be called to convert Array-like objects/collections to a new Array. You just bind the method to the object. The arguments inside a function is an example of an 'array-like object'. function list() { return Array.prototype.slice.call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] Binding can be done with the call() method of Function.prototype and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. Anyway, it can be simplified using bind. let unboundSlice = Array.prototype.slice let slice = Function.prototype.call.bind(unboundSlice) function list() { return slice(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] Specifications Speci...
BigInt.prototype.toLocaleString() - JavaScript
housands/lakh/crore separators console.log(bigint.toLocaleString('en-IN')); // -> 1,23,45,67,89,12,34,56,789 // the nu extension key requests a numbering system, e.g. ...
Date.prototype.toLocaleDateString() - JavaScript
rabic digits console.log(date.toLocaleDateString('ar-EG')); // -> "???/???/????" // for Japanese, applications may want to use the Japanese calendar, // where 2012 was the year 24 of the Heisei era console.log(date.toLocaleDateString('ja-JP-u-ca-japanese')); // -> "24/12/20" // when requesting a language that may not be supported, such as // Balinese, include a fallback language, in this case Indonesian console.log(date.toLocaleDateString(['ban', 'id'])); // -> "20/12/2012" Using options The results provided by toLocaleDateString() can be customized using the options argument: var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // request a weekday along with a long date var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; console.log(date.toLocaleDateStr...
Date.prototype.toLocaleString() - JavaScript
console.log(date.toLocaleString('ar-EG')); // -> "???/???/???? ?:??:?? ...
Date.prototype.toLocaleTimeString() - JavaScript
eString('en-GB')); // -> "03:00:00" // Korean uses 12-hour time with AM/PM console.log(date.toLocaleTimeString('ko-KR')); // -> "?? 12:00:00" // Arabic in most Arabic speaking countries uses real Arabic digits console.log(date.toLocaleTimeString('ar-EG')); // -> "?:??:?? ...
Function.prototype.call() - JavaScript
Toy('robot', 40); Using call to invoke an anonymous function In this example, we create an anonymous function and use call to invoke it on every object in an array. The main purpose of the anonymous function here is to add a print function to every object, which is able to print the correct index of the object in the array. Passing the object as this value is not strictly necessary, but is done for explanatory purpose. const animals = [ { species: 'Lion', name: 'King' }, { species: 'Whale', name: 'Fail' } ]; for (let i = 0; i < animals.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i); } Using call to invoke a function and specifying...
Intl.DateTimeFormat - JavaScript
ew Intl.DateTimeFormat('ar-EG').format(date)); // -> "???/???/????" // for Japanese, applications may want to use the Japanese calendar, // where 2012 was the year 24 of the Heisei era console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date)); // -> "24/12/19" // when requesting a language that may not be supported, such as // Balinese, include a fallback language, in this case Indonesian console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date)); // -> "19/12/2012" Using options The date and time formats can be customized using the options argument: var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200)); // request a weekday along with a long date var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; console.log(new Intl.DateTimeForm...
Intl.NumberFormat - JavaScript
ands/lakh/crore separators console.log(new Intl.NumberFormat('en-IN').format(number)); // -> 1,23,456.789 // the nu extension key requests a numbering system, e.g. ...
Map - JavaScript
ferable in certain cases: Map Object Accidental Keys A Map does not contain any keys by default. It only contains what is explicitly put into it. An Object has a prototype, so it contains default keys that could collide with your own keys if you're not careful. Note: As of ES5, this can be bypassed by using Object.create(null), but this is seldom done. Key Types A Map's keys can be any value (including functions, objects, or any primitive). The keys of an Object must be either a String or a Symbol. Key Order The keys in Map are ordered. Thus, when iterating over it, a Map object returns keys in order of insertion. The keys of an Object are not ordered. Note: Since ECMAScript 2015, ...
Number.prototype.toLocaleString() - JavaScript
????????? // India uses thousands/lakh/crore separators console.log(number.toLocaleString('en-IN')); // -> 1,23,456.789 // the nu extension key requests a numbering system, e.g. ...
Promise.all() - JavaScript
w empty'); console.log(p); }); // logs // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "rejected", <reason>: 44 } But, Promise.all resolves synchronously if and only if the iterable passed is empty: var p = Promise.all([]); // will be immediately resolved var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously console.log(p); console.log(p2) setTimeout(function() { console.log('the stack is now empty'); console.log(p2); }); // logs // Promise { <state>: "fulfilled", <value>: Array[0] } // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: Array[2] } Promise.all fail-fast behaviour Promise.all is rejected if any of the elements...
Promise.any() - JavaScript
rray of rejection values. Examples First to fulfil Promise.any() resolves with the first promise to fulfil, even if a promise rejects first. This is in contrast to Promise.race(), which resolves or rejects with the first promise to settle. const pErr = new Promise((resolve, reject) => { reject("Always fails"); }); const pSlow = new Promise((resolve, reject) => { setTimeout(resolve, 500, "Done eventually"); }); const pFast = new Promise((resolve, reject) => { setTimeout(resolve, 100, "Done quick"); }); Promise.any([pErr, pSlow, pFast]).then((value) => { console.log(value); // pFast fulfils first }) // expected output: "Done quick" Rejections with AggregateError Promise.any() rejects with an AggregateError if no promise fulfils. const pErr = new Promise((resolve, reject) => ...
Promise.prototype.then() - JavaScript
{ console.log("I am always called even if the prior then's promise rejects"); }); You can also use chaining to implement one function with a Promise-based API on top of another such function. function fetch_current_data() { // The fetch() API returns a Promise. This function // exposes a similar API, except the fulfillment // value of this function's Promise has had more // work done on it. return fetch('current-data.json').then(response => { if (response.headers.get('content-type') != 'application/json') { throw new TypeError(); } var j = response.json(); // maybe do something with j return j; // fulfillment value given to user of // fetch_current_data().then() }); } If onFulfilled returns a promise, the return value of then will...
Promise - JavaScript
The testPromise() method is called each time the <button> is clicked. It creates a promise that will be fulfilled, using window.setTimeout(), to the promise count (number starting from 1) every 1-3 seconds, at random. The Promise() constructor is used to...
RegExp.$1-$9 - JavaScript
wing script uses the test() method of the RegExp instance to grab a number in a generic string. var str = 'Test 24'; var number = /(\d+)/.test(str) ? RegExp.$1 : '0'; number; // "24" Please note that any operation involving the usage of other regular expressions between a re.test(str) call and the RegExp.$n property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected. Specifications Specification Legacy RegExp features in JavaScript ...
String.prototype.replace() - JavaScript
defined in replace() and includes the ignore case flag. let str = 'Twas the night before Xmas...'; let newstr = str.replace(/xmas/i, 'Christmas'); console.log(newstr); // Twas the night before Christmas... This logs 'Twas the night before Christmas...'. Note: See this guide for more explanations about regular expressions. Using global and ignore with replace() Global replace can only be done with a regular expression. In the following example, the regular expression includes the global and ignore case flags which permits replace() to replace each occurrence of 'apples' in the string with 'oranges'. let re = /apples/gi; let str = 'Apples are round, and apples are juicy.'; let newstr = str.replace(re, 'oranges'); console.log(newstr); // oranges are round, and oranges are juicy. Thi...
String.prototype.split() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.split([separator[, limit]]) Parameters separator Optional The pattern describing where each split should occur. ...
TypedArray.prototype.fill() - JavaScript
The fill method takes up to three arguments value, start and end. The start and end arguments are optional with default values of 0 and the length of the this object. If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. Use the following "polyfill" along with the Array.prototype.fill() polyfill. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!Uint8Array.prototype.fill) { Uint8Array.prototype.fill = Array.prototype.fill; } Examples Using fill new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4] new Uint8Array([1, 2, 3]).fill(4, 1); // Uint...
TypedArray.prototype.join() - JavaScript
t. Syntax typedarray.join([separator = ',']); Parameters separator Optional. Specifies a string to separate each element. The separator is converted to a string if necessary. If omitted, the typed array elements are separated with a comma (","). Return value A string with all array elements joined. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join if (!Uint8Array.prototype.join) { Object.defineProperty(Uint8Array.prototype, 'join', { value: Array.prototype.join }); } If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make...
TypedArray.prototype.slice() - JavaScript
of the sequence (typedarray.length). Return value A new typed array containing the extracted elements. Description The slice method does not alter. It returns a shallow copy of elements from the original typed array. If a new element is added to either typed array, the other typed array is not affected. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. if (!Uint8Array.prototype.slice) { Object.defineProperty(Uint8Array.prototype, 'slice', { value: function (begin, end) { return new Uint8Array(Array.prototype.slice.call(this, begin, end)); } }); } If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype method...
TypedArray.prototype.some() - JavaScript
en invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some does not mutate the typed array on which it is called. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some if (!Uint8Array.prototype.some) { Object.defineProperty(Uint8Array.prototype, 'some', { value: Array.prototype.some }); } If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make...
parseInt() - JavaScript
are allowed. Because some numbers use the e character in their string representation (e.g. 6.022e23 for 6.022 x 1023), using parseInt to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.floor(). parseInt understands exactly two signs: + for positive, and - for negative (since ECMAScript 1). It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If radix is undefined, 0, or unspecified, JavaScript assumes the following: If the input string begins with "0x" or "0X" (a zero, followed by lowercase or uppercase X), radix is as...
undefined - JavaScript
// these statements execute } if (x === undefined) { // throws a ReferenceError } However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object, using the in operator, for instance: if ('x' in window) { // these statements execute only if x is defined globally } void operator and undefined The void operator is a third alternative. var x; if (x === void 0) { // these statements execute } // y has not been declared before if (y === void 0) { // throws Uncaught Refe...
Lexical grammar - JavaScript
he second way is the /* */ style, which is much more flexible. For example, you can use it on a single line: function comment() { /* This is a one line JavaScript comment */ console.log('Hello world!'); } comment(); You can also make multiple-line comments, like this: function comment() { /* This comment spans multiple lines. Notice that we don't need to end the comment until we're done. */ console.log('Hello world!'); } comment(); You can also use it in the middle of a line, if you wish, although this can make your code harder to read so it should be used with caution: function comment(x) { console.log('Hello ' + x /* insert the value of x */ + ' !'); } comment('world'); In addition, you can use it to disable code to prevent it from running, by wrapping code in a comment...
Logical NOT (!) - JavaScript
// !f returns true n3 = !'' // !f returns true n4 = !'Cat' // !t returns false Double NOT (!!) It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the "truthyness" or "falsyness" of the value (see truthy and falsy). The same conversion can be done through the Boolean function. n1 = !!true // !!truthy returns true n2 = !!{} // !!truthy returns true: any object is truthy... n3 = !!(new Boolean(false)) // ...even Boolean objects with a false .valueOf()! n4 = !!false // !!falsy returns false n5 = !!"" // !!falsy returns false n6 = !!Boolean(false) // !!falsy ...
delete operator - JavaScript
property is an own non-configurable property, in which case, false is returned in non-strict mode. Exceptions Throws TypeError in strict mode if the property is an own non-configurable property. Description Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references. See the memory management page for more details. The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. However, it is important to consider the following scenarios: If the property which you are trying to delete does not exist, delete will not have any effect and will return t...
async function - JavaScript
t results = [await p1, await p2] // Do not do this! Use Promise.all or Promise.allSettled instead. } foo().catch(() => {}) // Attempt to swallow all errors... Examples Async functions and execution order function resolveAfter2Seconds() { console.log("starting slow promise") return new Promise(resolve => { setTimeout(function() { resolve("slow") console.log("slow promise is done") }, 2000) }) } function resolveAfter1Second() { console.log("starting fast promise") return new Promise(resolve => { setTimeout(function() { resolve("fast") console.log("fast promise is done") }, 1000) }) } async function sequentialStart() { console.log('==SEQUENTIAL START==') // 1. Execution gets here almost instantly const slow = await resolveAfter2Seco...
JavaScript typed arrays - JavaScript
1); Then you can access, for example, the amount due with amountDueView[0]. Note: The data structure alignment in a C structure is platform-dependent. Take precautions and considerations for these padding differences. Conversion to normal arrays After processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the Array prototype. This can be done using Array.from(), or using the following code where Array.from() is unsupported. let typedArray = new Uint8Array([1, 2, 3, 4]), normalArray = Array.prototype.slice.call(typedArray); normalArray.length === 4; normalArray.constructor === Array; Specifications Specification ECMAScript (ECMA-262)The definition of 'TypedArray Objects' in that specification. ...
Web audio codec guide - Web media technologies
No This information refers to support for Vorbis in HTML <audio> and <video> elements, and not to WebRTC. Container support Ogg, WebM RTP / WebRTC compatible Yes Licensing Fully open and free of any licensing requirements Choosing an audio codec Typically, regardless of what codec you use, it will generally get the job done, even if it's not the ideal choice, as long as you choose a codec not specifically designed for a totally different kind of source audio. Choosing a voice-only codec and trying to use it for music will not give you usable results, for instance. Some codecs may limit compatibility, however, and others may be more optimal for your needs than others. Here we'll provide guidance to help you select a...
Image file type and format guide - Web media technologies
palette of 24-bit colors (8 bits each of red, green, and blue). The length of a color table is always a power of 2 (that is, each palette has 2, 4, 8, 16, 32, 64, or 256 entries). To simulate more than 255 or 256 colors, dithering is generally used. It is technically possible to tile multiple image blocks, each with its own color palette, to create truecolor images, but in practice this is rarely done. Pixels are opaque, unless a specific color index is designated as transparent, in which case pixels colored that value are entirely transparent. GIF supports simple animation, in which following an initial full-size frame, a series of images reflecting the parts of the image that change with each frame are provided. GIF has been extremely popular for decades, due to its simplicity and compati...
Web video codec guide - Web media technologies
mary drawback to AV1 at this time is that it is very new, and support is still in the process of being integrated into most browsers. Additionally, encoders and decoders are still being optimized for performance, and hardware encoders and decoders are still mostly in development rather than production. For this reason, encoding a video into AV1 format takes a very long time, since all the work is done in software. For the time being, because of these factors, AV1 is not yet ready to be your first choice of video codec, but you should watch for it to be ready to use in the future. Supported bit rates Varies depending on the video's level; theoretical maximum reaches 800 Mbps at level 6.3[2] Supported frame rates Varies by level; for example, level 2.0 has a maximum of ...
OpenSearch description format
t The data: URI kitchen.) <Image height="16" width="16" type="image/x-icon">https://example.com/favicon.ico</Image> <!-- or --> <Image height="16" width="16">data:image/x-icon;base64,AAABAAEAEBAAA ... DAAA=</Image> Firefox caches the icon as a base64 data: URI (search plug-ins are stored in the profile's searchplugins/ folder). http: and https: URLs are converted to data: URIs when this is done. Note: For icons loaded remotely (that is, from https:// URIs as opposed to data: URIs), Firefox will reject icons larger than 10 kilobytes. Url Describes the URL or URLs to use for the search. The template attribute indicates the base URL for the search query. Firefox supports three URL types: type="text/html" specifies the URL for the actual search query. type="application/x-sug...
CSS and JavaScript animation performance - Web Performance
est results above, we'd argue that CSS animations are the better choice. But how? The key is that as long as the properties we want to animate do not trigger reflow/repaint (read CSS triggers for more information), we can move those sampling operations out of the main thread. The most common property is the CSS transform. If an element is promoted as a layer, animating transform properties can be done in the GPU, meaning better performance/efficiency, especially on mobile. Find out more details in OffMainThreadCompositing. To enable the OMTA (Off Main Thread Animation) in Firefox, you can go to about:config and search for the layers.offmainthreadcomposition.async-animations. Toggle its value to true. After enabling OMTA, try running the above test again. You should see that the FPS of the...
Navigation and resource timings - Web Performance
The main thing to look at for each resource. See Also PerformanceNavigationTiming PerformanceResourceTiming, PerformanceMark PerformanceMeasure PerformancePaintTiming ...
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
stent as possible environment. Synthetic Monitoring involves deploying scripts to simulate the path an end user might take through a web application, reporting back the performance the simulator experiences. The traffic measured is not of your actual users, but rather synthetically generated traffic collecting data on page performance. An example of synthetic monitoring is WebPageTest.org. It is done in a controlled environment where variable like geography, network, device, browser, and cached status are predetermined. It provides waterfall charts for every asset served by the host and CDN as well as every third party asset and asset requests generated by all third party scripts, such as ads and analytic services. Controlling for environmental variables is helpful in understanding where per...
Understanding latency - Web Performance
sidered blocked. Blocking happens when there are too many simultaneous connections made to a single server over HTTP. If all connections are in use, the browser can't download more resources until a connection is released, meaning those requests and resources are blocked. DNS resolution is the time it took to do the DNS lookup. The greater the number of hostnames, the more DNS lookups need to be done. Connecting is the time it takes for a TCP handshake to complete. Like DNS, the greater the number of server connections needed, the more time is spend creating server connections. The TLS handshake is how long it took to set up a secure connection. While a TLS handshake does take longer to connect than an insecure connection, the additional time needed for a secure connection is worth it. Sen...
Web Performance
s to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. There are tools, APIs, and best practices that help us measure and improve web performance. We cover them in this section: Key performance guides Animation performance and frame rateAnimation on the web can be done via SVG, JavaScript, including <canvas> and WebGL, CSS animation, <video>, animated gifs and even animated PNGs and other image types. The performance cost of animating a CSS property can vary from one property to another, and animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate.Critical rendering pathThe Critical Rendering Path is the sequence...
The building blocks of responsive design - Progressive web apps (PWAs)
from it do not, so upon resizing the screen it was possible to end up with a messy layout with different sized elements when using max-width: 100%, such as: Media queries Fluid grids are a great start, but you'll notice that at certain points (known as breakpoints) the layout starts to break down. At these points you'll want to change the layout to rectify the layout problem, and this can be done using media queries. Note: Media queries are a CSS3 feature that allow you to selectively apply CSS depending on the results of media feature tests -- for more on the basics, read Media queries. Typical desktop layout In our example, we have a desktop layout, as we've already seen. This is created using the CSS rules included at the top of the stylesheet, before any media queries are encount...
Structural overview of progressive web apps - Progressive web apps (PWAs)
l the service worker itself. The service worker will actually handle caching all the listed files. ...
image-rendering - SVG: Scalable Vector Graphics
Note: As a presentation attribute, image-rendering can be used as a CSS property. See the css image-rendering property for more information. ...
transform - SVG: Scalable Vector Graphics
bout a given point. If optional parameters x and y are not supplied, the rotation is about the origin of the current user coordinate system. If optional parameters x and y are supplied, the rotation is about the point (x, y). Example html,body,svg { height:100% } <svg viewBox="-12 -2 34 14" xmlns="http://www.w3.org/2000/svg"> <rect x="0" y="0" width="10" height="10" /> <!-- rotation is done around the point 0,0 --> <rect x="0" y="0" width="10" height="10" fill="red" transform="rotate(100)" /> <!-- rotation is done around the point 10,10 --> <rect x="0" y="0" width="10" height="10" fill="green" transform="rotate(100,10,10)" /> </svg> SkewX The skewX(<a>) transform function specifies a skew transformation along the x axis by a degrees. Example html,body,s...
xlink:title - SVG: Scalable Vector Graphics
It may be used, for example, to make titles available to applications used by visually impaired users, or to create a table of links, or to present help text that appears when a user lets a mouse pointer hover over a starting resource. Note: New content should use a <title> child element rather than a xlink:title attribute. ...
Namespaces crash course - SVG: Scalable Vector Graphics
ever, instead of setting the default namespace, this namespace declaration sets the namespace for something called a "namespace prefix". In this case, we have chosen to use the prefix xlink (the second part) since the prefix will be used to tell the user agent about attributes that belong to XLink. As their name suggests, namespace prefixes are used to prefix parameter and element names. This is done by putting the namespace prefix and a colon before the parameter name as shown on the <script> element in the example above. This tells the user agent that that particular parameter belongs to the namespace assigned to the namespace prefix (XLink), and is a parameter that can be used with the same meaning on other elements. Note that it is an XML error to use a prefix that hasn't been bound to a...
SVG animation with SMIL - SVG: Scalable Vector Graphics
f CSS animations and Web animations, the Chrome developers have since suspended that deprecation. Firefox 4 introduced support for animating SVG using Synchronized Multimedia Integration Language (SMIL). SMIL allows you to: animate the numeric attributes of an element (x, y, ...) animate transform attributes (translation or rotation) animate color attributes follow a motion path This is done adding an SVG element like <animate> inside the SVG element to animate. Below are examples for the four different ways. Animating attributes of an element The following example animates the cx attribute of a circle. To do so, we add an <animate> element inside the <circle> element. The important attributes for <animate> are: attributeName The name of the attribute to animate. from The ini...
Fills and Strokes - SVG: Scalable Vector Graphics
<< PreviousNext >> There are several ways to color shapes (including specifying attributes on the object) using inline CSS, an embedded CSS section, or an external CSS file. Most SVG you'll find around the web use inline CSS, but there are advantages and disadvantages associated with each type. Fill and Stroke Attributes Painting Basic coloring can be done by setting two attributes on the node: fill and stroke. Using fill sets the color inside the object and stroke sets the color of the line drawn around the object. You can use the same css color naming schemes that you use in HTML, whether that's color names (that is red), rgb values (that is rgb(255,0,0)), hex values, rgba values, etc. <rect x="10" y="10" width="100" height="100" stroke="blue" fill="purple" fill-o...
Gradients in SVG - SVG: Scalable Vector Graphics
te values will use the stop that is assigned furthest down the XML tree. Also, like with fill and stroke, you can specify a stop-opacity attribute to set the opacity at that position (again, in FF3 you can also use rgba values to do this). <stop offset="100%" stop-color="yellow" stop-opacity="0.5"/> To use a gradient, we have to reference it from an object's fill or stroke attributes. This is done the same way you reference elements in CSS, using a url. In this case, the url is just a reference to our gradient, which I've given the creative ID, "Gradient". To attach it, set the fill to url(#Gradient), and voila! Our object is now multicolored. You can do the same with stroke. The <linearGradient> element also takes several other attributes, which specify the size and appearance of the gra...
Introduction - SVG: Scalable Vector Graphics
age rely on this relatively small set of elements to define the graphics area. Before you start There are a number of drawing applications available such as Inkscape which are free and use SVG as their native file format. However, this tutorial will rely on the trusty XML or text editor (your choice). The idea is to teach the internals of SVG to those who want to understand it, and that is best done by dirtying your hands with a bit of markup. You should note your final goal though. Not all SVG viewers are equal and so there is a good chance that something written for one app will not display exactly the same in another, simply because they support different levels of the SVG specification or another specification that you are using along with SVG (that is, JavaScript or CSS). SVG is suppor...
SVG Filters Tutorial - SVG: Scalable Vector Graphics
lying and testing the effect step by step. This element has different attributes that help us create the clipping region. Between the filter tags, we can define the primitives that allow us to implement the desired effect. One of these primitives is the feGaussianBlur. The keyword SourceAlpha identifies the input for this primitive, is in this case input 'in'. The amount of blur to be applied is done using the stdDeviation attribute. SVG filter example <defs> <filter id="drop-shadow"> <feGaussianBlur in="SourceAlpha" stdDeviation="3"/> </filter> </defs> <g id="ghost" style="filter: url(#drop-shadow);"/> <!--Ghost drawing in here--> </g> This above example will not produced the desired output. Instead we need to add more filter primitives which will produce the desire rendering. By...
Using custom elements - Web Components
, we are just running the updateStyle() function again to make sure that the square's style is updated as per the new values: attributeChangedCallback(name, oldValue, newValue) { console.log('Custom square element attributes changed.'); updateStyle(this); } Note that to get the attributeChangedCallback() callback to fire when an attribute changes, you have to observe the attributes. This is done by specifying a static get observedAttributes() method inside custom element class - this should return an array containing the names of the attributes you want to observe: static get observedAttributes() { return ['c', 'l']; } This is placed right at the top of the constructor, in our example. Note: Find the full JavaScript source here. Polyfills vs. classes Custom Element polyfills may ...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
n run XSLT transformations through the XSLTProcessor object. Once instantiated, an XSLTProcessor has an XSLTProcessor.importStylesheet() method that takes as an argument the XSLT stylesheet to be used in the transformation. The stylesheet has to be passed in as an XML document, which means that the .xsl file has to be loaded by the page before calling XSLTProcessor.importStylesheet(). This can be done via XMLHttpRequest or XMLDocument.load(). 11 Resources XSLT No summary! 12 Setting Parameters XSLT While running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from JavaScript may be even more useful. For example, JavaScript and XSLT could be used to sort XML data and then display it. The sorting would have t...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
n run XSLT transformations through the XSLTProcessor object. Once instantiated, an XSLTProcessor has an XSLTProcessor.importStylesheet() method that takes as an argument the XSLT stylesheet to be used in the transformation. The stylesheet has to be passed in as an XML document, which means that the .xsl file has to be loaded by the page before calling XSLTProcessor.importStylesheet(). This can be done via XMLHttpRequest or XMLDocument.load(). Figure 1 : Instantiating an XSLTProcessor var xsltProcessor = new XSLTProcessor(); // Load the xsl file using synchronous (third param is set to false) XMLHttpRequest var myXMLHTTPRequest = new XMLHttpRequest(); myXMLHTTPRequest.open("GET", "example.xsl", false); myXMLHTTPRequest.send(null); var xslRef = myXMLHTTPRequest.responseXML; //...
XSLT: Extensible Stylesheet Language Transformations
Web › XSLT
sired, and transforming the content into a different format. Using the Mozilla JavaScript interface to XSL Transformations This document describes the JavaScript interface to the XSLT processing engine in Mozilla 1.2 and up. Specifying parameters using processing instructions Firefox allows stylesheet parameters to be specified when using the <?xml-stylesheet?> processing instruction. This is done using the <?xslt-param?> PI described in this document. XSLT & XPath Tutorial The TopXML XSLT tutorial introduces you to the basics of XSLT concepts, syntax, and programming. XSLT Tutorial This W3Schools tutorial teaches the reader how to use XSLT to transform XML documents into other formats, like XHTML. What is XSLT? This extensive introduction to XSLT and XPath assumes no prior knowledge...
WebAssembly Concepts - WebAssembly
gains in performance. It is not primarily intended to be written by hand, rather it is designed to be an effective compilation target for low-level source languages like C, C++, Rust, etc. This has huge implications for the web platform -- it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn't have done so. What's more, you don't even have to know how to create WebAssembly code to take advantage of it. WebAssembly modules can be imported into a web (or Node.js) app, exposing WebAssembly functions for use via JavaScript. JavaScript frameworks could make use of WebAssembly to confer massive performance advantages and new features while still making functionality easily available to web developers...
Compiling from Rust to WebAssembly - WebAssembly
rname again. This imports the new module from the node_modules folder. This isn't considered a best practice, but this is a demo, so it's OK for now. Once it's loaded, it calls the greet function from that module, passing "WebAssembly" as a string. Note how there's nothing special here, yet we're calling into Rust code. As far as the JavaScript code can tell, this is just a normal module. We're done making files. Let's give this a shot: $ npm install $ npm run serve This starts a web server. Load http://localhost:8080 and an alert box appears on the screen, with Hello, WebAssembly! in it. We've successfully called from JavaScript into Rust, and from Rust into JavaScript. Conclusion This is the end of our tutorial; we hope you've found it useful. There's lots of exciting work going on in...
Compiling an Existing C Module to WebAssembly - WebAssembly
e the Image The image is now available in wasm. It is time to call the WebP encoder to do its job. Looking at the WebP documentation, you'll find that WebPEncodeRGBA seems like a perfect fit. The function takes a pointer to the input image and its dimensions, as well as a quality option between 0 and 100. It also allocates an output buffer for us that we need to free using WebPFree() once we are done with the WebP image. The result of the encoding operation is an output buffer and its length. Because functions in C can't have arrays as return types (unless you allocate memory dynamically), this example resorts to a static global array. This may not be clean C. In fact, it relies on wasm pointers being 32 bits wide. But this is a fair shortuct for keeping things simple: int result[2]; EMSCRI...
WebAssembly
such as C/C++, C# and Rust with a compilation target so that they can run on the web. It is also designed to run alongside JavaScript, allowing both to work together. In a Nutshell WebAssembly has huge implications for the web platform -- it provides a way to run code written in multiple languages on the web at near native speed, with client apps running on the web that previously couldn't have done so. WebAssembly is designed to complement and run alongside JavaScript -- using the WebAssembly JavaScript APIs, you can load WebAssembly modules into a JavaScript app and share functionality between the two. This allows you to take advantage of WebAssembly's performance and power and JavaScript's expressiveness and flexibility in the same apps, even if you don't know how to write WebAssembly co...