Search completed in 1.13 seconds.
4447 results for "following":
Your results are loading. Please wait...
Following the Android Toasts Tutorial from a JNI Perspective
java code let's start with the following java code, which invokes a toast and says "hello, firefox!".
...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 methods - maketext, show fields - length_short no constructors are used.
...And 2 more matches
copyToFollowingLinks
this content is now available at nsifile.copytofollowinglinks().
copyToFollowingLinksNative
this content is now available at nsifile.copytofollowinglinksnative().
following-sibling - XPath
the following-sibling axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.
following - XPath
WebXPathAxesfollowing
the following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.
sslfnc.html
syntax #include "nss.h" secstatus nss_init(char *configdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside.
... syntax #include "nss.h" secstatus nss_initreadwrite(char *configdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside.
... syntax #include "nss.h" secstatus nss_nodb_init(char *reserved); parameter this function has the following parameter: reserved should be null..
...And 55 more matches
Index - Archive of obsolete content
the following article explains these security mechanisms, ideally an extension that needs to display web content (which is always potentially dangerous) will use all of them.
...the following instructions also apply to a theme and other xpi files.
... 396 prerequisites add-ons, extensions in order to complete this tutorial you need to have and know how to use the following programs on your computer: 397 specifying the appearance add-ons, extensions now that we have defined a panel in which to display an icon, we use css to specify which icon to display.
...And 48 more matches
Index - Web APIs
WebAPIIndex
98 arraybufferview api, interface, javascript, reference, typed arrays arraybufferview is a helper type representing any of the following javascript typedarray types: 99 attr api, dom the attr interface represents one of a dom element's attributes as an object.
... 126 audiocontext.createjavascriptnode() api, audio, method, obsolete, reference, web, createjavascriptnode the following script illustrates the use of createjavascriptnode(): 127 audiocontext.createmediaelementsource() api, audiocontext, method, reference, référence(2), web audio api, createmediaelementsource for more details about media element audio source nodes, check out the mediaelementaudiosourcenode reference page.
...lcountmode api, audionode, property, reference, web audio api, channelcountmode the possible values of channelcountmode and their meanings are: 159 audionode.channelinterpretation api, audionode, property, reference, web audio api, channelinterpretation when the number of channels doesn't match between an input and an output, up- or down-mixing happens according the following rules.
...And 39 more matches
Drawing graphics - Learn web development
add the following code into it, just below the opening <body> tag: <canvas class="mycanvas"> <p>add suitable fallback here.</p> </canvas> we have added a class to the <canvas> element so it will be easier to select if we have multiple canvases on the page, but we have removed the width and height attributes for now (you could add them back in if you wanted, but we will set them using javascript in a below ...
... now add the following lines of javascript inside the <script> element: const canvas = document.queryselector('.mycanvas'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; here we have stored a reference to the canvas in the canvas constant.
...add the following into the <head> of your document: <style> body { margin: 0; overflow: hidden; } </style> the scrollbars should now be gone.
...And 28 more matches
LiveConnect Overview - Archive of obsolete content
all javascript access to java takes place with these objects, which are summarized in the following table.
...for example, you can use the following: var mystring = new java.lang.string("hello world"); instead of the longer version: var mystring = new packages.java.lang.string("hello world"); working with java arrays when any java method creates an array and you reference that array in javascript, you are working with a javaarray.
... for example, the following code creates the javaarray x with ten elements of type int: var x = java.lang.reflect.array.newinstance(java.lang.integer, 10); like the javascript array object, javaarray has a length property which returns the number of elements in the array.
...And 27 more matches
Python binding for NSS
for information on nss and nspr, see the following: network security services (nss).
...red hat following it's open source philosophy has contributed the source to the mozilla security project.
...`pip wheel -w dist .` the following constants were added: ssl.tls_aes_128_gcm_sha256 ssl.tls_aes_256_gcm_sha384 ssl.tls_chacha20_poly1305_sha256 release 1.0.0 release date 2016-09-01 scm tag pynss_release_1_0_0 source download https://ftp.mozilla.org/pub/mozilla.org/security/python-nss/releases/pynss_release_1_0_0/src/ change log ...
...And 27 more matches
Details of the object model - JavaScript
summary of differences the following table gives a short summary of some of these differences.
... inheritance model inherit properties by following the class chain.
... inherit properties by following the prototype chain.
...And 23 more matches
TypeScript support in Svelte - Learn web development
in the following sections we hope to give you more evidence to make up your mind about it.
...all you have to do is run the following terminal commands (run them somewhere where you are storing your svelte test projects — it creates a new directory): npx degit sveltejs/template svelte-typescript-app cd svelte-typescript-app node scripts/setuptypescript.js this creates a starter project that includes typescript support, which you can then modify as you wish.
... in this case, if you run npm run validate (either in the vs code console or terminal) you will get the following error: even better, if you run it from the vs code integrated terminal (you can open it with the ctrl + ` keyboard shortcut), cmd/ctrl + clicking on the file name will take you to the line containing the error.
...And 21 more matches
Setting up your own test automation environment - Learn web development
to install selenium-webdriver, run the following command, making sure you are inside your project folder: npm install selenium-webdriver note: it is still a good idea to follow these steps even if you previously installed selenium-webdriver and downloaded the browser drivers.
... paste the following into the bottom of your file (updating the path as it actually is on your machine): #add webdriver browser drivers to path export path=$path:/users/bob save and close this file, then restart your terminal/command prompt to reapply your bash configuration.
... check that your new paths are in the path variable by entering the following into your terminal: echo $path you should see it printed out in the terminal.
...And 20 more matches
OS.File for the main thread
using os.file from a jsm to import os.file into your chrome code, add the following line at the start of your script: components.utils.import("resource://gre/modules/osfile.jsm") promises before using os.file from the main thread, you need some understanding of the promise library.
... example: read the contents of a file as text the following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8).
... example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8).
...And 19 more matches
Index
the public keys that are exchanged between parties are transported using a container; the container is called a certificate, following standard x.509 version 3.
... 8 deprecated ssl functions nss the following ssl functions have been replaced with newer versions.
... 19 4.3 release notes jss, nss network security services for java (jss) 4.3 is a minor release with the following new features: 20 4.3.1 release notes jss, nspr, nss network security services for java (jss) 4.3.1 is a minor release with the following new features: 21 build instructions for jss 4.3.x jss newsgroup: mozilla.dev.tech.crypto 22 build instructions for jss 4.4.x jss newsgroup: mozilla.dev.tech.crypto 23 jss faq jss ...
...And 19 more matches
Expressions and operators - JavaScript
operators javascript has the following types of operators.
... there are also compound assignment operators that are shorthand for the operations listed in the following table: compound assignment operators name shorthand operator meaning assignment x = y x = y addition assignment x += y x = x + y subtraction assignment x -= y x = x - y multiplication assignment x *= y x = x * y division assignment x /= y x = x / y remainder assignment x %= y x = x % y ...
...the following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; comparison operators operator description examples returning true equal (==) returns true if the operands are equal.
...And 19 more matches
Grammar and types - JavaScript
in the following code, the variable input is not assigned a value, and the if statement evaluates to true.
...for example, the following code executes the function myfunction because the myarray element is undefined: var myarray = []; if (!myarray[0]) myfunction(); the undefined value converts to nan when used in numeric context.
... for example, the following code will log 5, because the scope of x is the global context (or the function context if the code is part of a function).
...And 18 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
in the following sections we will show you how they can be used.
...it takes the following parameters: a function to run, or a reference to a function defined elsewhere.
... in the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr.
...And 16 more matches
NSS Tools modutil
syntax to run the security module database tool, type the command modutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section.
...the following cipher is currently available: fortezza.
...the following mechanisms are currently available: rsa, dsa, rc2, rc4, rc5, des, dh, fortezza, sha1, md5, md2, random (for random number generation), and friendly (meaning certificates are publicly readable).
...And 16 more matches
Legacy layout methods - Learn web development
replace whatever is inside the body currently with the following: <h1>2 column layout example</h1> <div> <h2>first column</h2> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit.
...first, of all, apply the following to your html to provide some basic setup: body { width: 90%; max-width: 900px; margin: 0 auto; } the body will be 90% of the viewport wide until it gets to 900px wide, in which case it will stay fixed at this width and center itself in the viewport.
...add the following to the bottom of your css: div:nth-of-type(1) { width: 48%; } div:nth-of-type(2) { width: 48%; } here we've set both to be 48% of their parent's width — this totals 96%, leaving us 4% free to act as a gutter between the two columns, giving the content some space to breathe.
...And 14 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
the following new components will be developed throughout the course of this article: moreactions: displays the check all and remove completed buttons, and emits the corresponding events required to handle their functionality.
...put the following content into your moreactions.svelte file: <script> import { createeventdispatcher } from 'svelte' const dispatch = createeventdispatcher() let completed = true const checkall = () => { dispatch('checkall', completed) completed = !completed } const removecompleted = () => dispatch('removecompleted') </script> <div class="btn-group"> <button type="button" class="btn b...
... add the following import statement below the existing ones: import moreactions from './moreactions.svelte' then add the described functions at the end of the <script> section: const checkalltodos = (completed) => todos.foreach(t => t.completed = completed) const removecompletedtodos = () => todos = todos.filter(t => !t.completed) now go to the bottom of the todos.svelte markup section and replac...
...And 14 more matches
Introducing a complete toolchain - Learn web development
tools used in our toolchain in this article we're going to use the following tools and features: jsx, a react-related set of syntax extensions that allow you to do things like defining component structures inside javascript.
... as mentioned previously, github is a source code repository service that adds community features such as issue tracking, following project releases and much more.
... once you've signed up for github (click the sign up link on the homepage if you don't already have an account, and follow the instructions), you can use your github account for authentication on netlify (click sign up, then choose github from the "sign up with one of the following" list), so technically you only need to create one new account.
...And 14 more matches
Introduction to automated testing - Learn web development
once the install completes, test that node is installed by typing the following into the terminal, which returns the installed versions of node and npm: node -v npm -v if you've got node/npm already installed, you should update them to their latest versions.
...to update npm, use the following command in your terminal: npm install npm@latest -g note: if the above command fails with permissions errors, fixing npm permissions should sort you out.
... create a new directory somewhere sensible using your file manager ui, or, on a command line, by navigating to the location you want and running the following command: mkdir node-test to make this directory an npm project, you just need to go inside your test directory and initialize it, with the following: cd node-test npm init this second command will ask you many questions to find out the information required to set up the project; you can just select the defaults for now.
...And 13 more matches
Floats - Learn web development
first, we'll start off with some simple html — add the following to your html body, removing anything that was inside there before: <h1>simple float example</h1> <div class="box">float</div> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
...cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> now apply the following css to your html (using a <style> element or a <link> to a separate .css file — your choice): body { width: 90%; max-width: 900px; margin: 0 auto; font: .9em/1.2 arial, helvetica, sans-serif } .box { width: 150px; height: 100px; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } if you save and refresh now, you'll see something much like what you'd expe...
...to float the text around it add the float and margin-right properties to the .box rule: .box { float: left; margin-right: 15px; width: 150px; height: 100px; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } now if you save and refresh you'll see something like the following: float example 1 <h1>simple float example</h1> <div class="box">float</div> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
...And 12 more matches
Functions - JavaScript
for example, the following code defines a simple function named square: function square(number) { return number * number; } the function square takes one parameter, called number.
...a non-primitive value, such as array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example: function myfunc(theobject) { theobject.make = 'toyota'; } var mycar = {make: 'honda', model: 'accord', year: 1998}; var x, y; x = mycar.make; // x gets the value "honda" myfunc(mycar); y = mycar.make; // y gets the value "toyota" // (the make property was changed by the function) function expressions while the function declaration above is syntactically a stateme...
...the following example shows a map function that should receive a function as first argument and an array as second argument.
...And 12 more matches
Loops and iteration - JavaScript
a for statement looks as follows: for ([initialexpression]; [conditionexpression]; [incrementexpression]) statement when a for loop executes, the following occurs: the initializing expression initialexpression, if any, is executed.
...when the condition is false, execution stops, and control passes to the statement following do...while.
... example in the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.
...And 12 more matches
Theme changes in Firefox 2 - Archive of obsolete content
changes in browser bookmarks/addbookmark.css the addbookmarks.css file should have the following lines added to the top: @namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); @namespace html url("http://www.w3.org/1999/xhtml"); some microsummary-related css also needs to be added, to provide formatting for the microsummary picker.
... browser.css the following styles used in firefox 1.5 themes are no longer used in firefox 2 and should be removed from your theme: #bookmarks-button:active #copy-button:active #cut-button:active #downloads-button:active #forward-button[buttondown="true"] #history-button:active #home-button:active #mail-button #mail-button:active #mail-button[disabled="true"] #mail-button[open="true"] #new-tab-button:active ...
...aste-button:active toolbar[iconsize="small"] #print-button:active toolbar[iconsize="small"] #reload-button:active toolbar[iconsize="small"] #stop-button:active toolbar[mode="icons"] .toolbarbutton-text toolbar[mode="text"] .toolbarbutton-1 > .toolbarbutton-text toolbar[mode="text"] .toolbarbutton-1 > stack > toolbarbutton > .toolbarbutton-text toolbar[mode="text"] .toolbarbutton-icon the following styles need to be added to your theme to be compatible with firefox 2: #back-button .toolbarbutton-menubutton-dropmarker #back-button:hover #back-button:hover .toolbarbutton-menubutton-dropmarker #back-button:hover:active #back-button:hover:active .toolbarbutton-menubutton-dropmarker #back-button[buttondown="true"] > .toolbarbutton-menubutton-dropmarker #back-button[buttonover="true"] #...
...And 11 more matches
Practical positioning examples - Learn web development
general setup to begin with, add the following between your opening and closing <style> tags: html { font-family: sans-serif; } * { box-sizing: border-box; } body { margin: 0; } this is just some general setup to set a sans-serif font on our page, use the border-box box-sizing model, and get rid of the default <body> margin.
... next, add the following just below your previous css: .info-box { width: 450px; height: 400px; margin: 0 auto; } this sets a specific width and height on the content, and centers it on the screen using the old margin: 0 auto trick.
...first, add the following rule at the bottom of your css to remove the default padding-left and margin-top from the unordered list: .info-box ul { padding-left: 0; margin-top: 0; } note: we are using descendant selectors with .info-box at the start of the chain throughout this example — this is so that we can insert this feature into a page with other content already on it, without fear of interfering with the st...
...And 11 more matches
source-editor.jsm
this object has the following properties: property type description str string the last string that was searched for.
...it may have the following properties: property type description backwards boolean if true, the search begins at start (or the end of the text, if start is not specified) and progresses toward the beginning of the text.
...each breakpoint is an object with the following properties: property type description line number the 0-based line number on which the breakpoint is set.
...And 11 more matches
Index
its value is the logical or of zero or more of the following constants: 93 jsconstdoublespec jsapi reference, spidermonkey jsconstdoublespecs is used to define a set of double values that are assigned as properties to an object using js_defineconstdoubles.
... 106 jsfastnative jsapi reference, obsolete, spidermonkey the callback should use the following macros to access the fields of vp: 107 jsfinalizeop jsapi reference, reference, référence(2), spidermonkey the jsfinalizeop is analogous to java finalizers or c++ destructors.
... 128 jsobject jsapi reference, spidermonkey objects are made up of the following parts: 129 jsobjectop jsapi reference, obsolete, spidermonkey the callbacks of this type are: 130 jsobjectops.defaultvalue jsapi reference, obsolete, spidermonkey the jsobjectops.defaultvalue callback corresponds to the [[defaultvalue]] method defined in ecma 262-3 §8.6.2.6.
...And 11 more matches
Using Objective-C from js-ctypes
speech synthesis example let's start with the following objective-c code, which invokes the speech synthesis api to say "hello, firefox!".
... while ([synth isspeaking]) {} [synth release]; return 0; } save this file as test.m, and run with the following command, inside the same directory as the saved file (needs xcode).
...let's look at the following codelet: [nsspeechsynthesizer alloc] it passes an alloc message to the nsspeechsynthesizer class, in objective-c syntax.
...And 11 more matches
Element - Web APIs
WebAPIElement
nondocumenttypechildnode.nextelementsibling read only is an element, the element immediately following the given one in the tree, or null if there's no sibling node.
... properties included from slotable the element interface includes the following property, defined on the slotable mixin.
... recommendation added the following event handlers: ongotpointercapture and onlostpointercapture.
...And 11 more matches
JXON - Archive of obsolete content
the algorithms proposed here (see: #1, #2, #3, #4) will consider only the following types of nodes and their attributes: document (only as function argument), documentfragment (only as function argument), element, text (never as function argument), cdatasection (never as function argument), attr (never as function argument).
... the following algorithms are somewhat based on the parker convention, version 0.4, which prescribes the transformation of tags names into object properties names and the recognition of the typeof of all the collected text content of each tag (plain text parsing); but with some differences (so, one can say that we follow a our convention).
... algorithm #4: a very minimalist way the following is another possible way to do the conversion.
...And 10 more matches
Common Firefox theme issues and solutions - Archive of obsolete content
please see the following threads on mozillazine for solutions to this issue: http://forums.mozillazine.org/viewtopic.php?f=18&t=2131121 http://forums.mozillazine.org/viewtopic.php?f=18&t=1953371&start=60 windows 7 aero not going into full screen mode properly on win7 with aero glass support firefox doesn't always go to full screen mode from a normal window properly.
... the resolution to this issue is to add the following code to your browser.css file somewhere below where the main-window is made transparent to support aero glass.
...in order to work around this issue, you need to either rename any of the following files that are in your chrome://browser/skin/ folder and fix any references to those files, or copy them to the folder chrome://browser/skin/lion/: keyhole-circle.png toolbar.png toolbarbutton-dropmarker.png tabbrowser/alltabs-box-bkgnd-icon.png tabview/tabview.png places/toolbar.png linux linux select box fields are showing both drop arrow and spinner arrows on linux: the styling of ...
...And 10 more matches
Client-side form validation - Learn web development
when an element is valid, the following things are true: the element matches the :valid css pseudo-class, which lets you apply a specific style to valid elements.
... when an element is invalid, the following things are true: the element matches the :invalid css pseudo-class, and sometimes other ui pseudo-classes (e.g., :out-of-range) depending on the error, which lets you apply a specific style to invalid elements.
...update your html to add a pattern attribute like this: <form> <label for="choose">would you prefer a banana or a cherry?</label> <input id="choose" name="i_like" required pattern="[bb]anana|[cc]herry"> <button>submit</button> </form> input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } this gives us the following update — try it out: note: you can find this example live on github as fruit-pattern.html (see also the source code.) in this example, the <input> element accepts one of four possible values: the strings "banana", "banana", "cherry", or "cherry".
...And 10 more matches
A first splash into JavaScript - Learn web development
let's imagine your boss has given you the following brief for creating this game: i want you to create a simple guess the number type game.
...first of all, add the following lines inside your <script> element: let randomnumber = math.floor(math.random() * 100) + 1; const guesses = document.queryselector('.guesses'); const lastresult = document.queryselector('.lastresult'); const loworhi = document.queryselector('.loworhi'); const guesssubmit = document.queryselector('.guesssubmit'); const guessfield = document.queryselector('.guessfield'); let guesscount = 1; let...
... functions next, add the following below your previous javascript: function checkguess() { alert('i am a placeholder'); } functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time.
...And 10 more matches
Componentizing our Svelte app - Learn web development
eventually, we will split up our app into the following components: alert.svelte: a general notification box for communicating actions that have occurred.
...add the following content into the file: <script> export let filter = 'all' </script> <div class="filters btn-group stack-exception"> <button class="btn toggle-btn" class:btn__primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={()=> filter = 'all'} > <span class="visually-hidden">show</span> <span>all</span> <span class="visually-hidden">tasks</span> </button> <button class...
...first of all, we need to import it — add the following line at the top of the todos.svelte <script> section: import filterbutton from './filterbutton.svelte' now, replace the filters <div> with a call to the filterbutton component, which takes the current filter as a prop — the below line is all you need: <filterbutton {filter} /> note: remember that when the html attribute name and variable matches, they can be replaced with {vari...
...And 10 more matches
IME handling guide
for example, if a user types "watasinonamaehanakanodesu", it's converted to hiragana characters, "わたしのなまえはなかのです", automatically (in the following screenshots, the composition string has a wavy underline and the only one clause is called "raw input clause").
...then, converts each clause with chinese characters: "私の", "名前は" and "中野です" (in the following screenshot each clause is underlined and not connected adjacently.
... if one or more clauses were not converted as expected, the user can choose one of the clauses with arrow keys and look for the expected result form the list in the drop down menu (in the following screenshot, the clause with the thicker underline is called "selected clause").
...And 10 more matches
NSS PKCS11 Functions
syntax #include "secmod.h" extern secmodmodule *secmod_loadusermodule(char *modulespec, secmodmodule *parent, prbool recurse); parameters this function has the following parameters: modulespec is a pkcs #11 modulespec.
...syntax #include "secmod.h" extern secstatus secmod_unloadusermodule(secmodmodule *module); parameters this function has the following parameters: module is the module to be unloaded.
...syntax #include <pk11pub.h> secstatus secmod_closeuserdb(pk11slotinfo *slot) parameters this function has the following parameter: slot a pointer to a slot info structure.
...And 10 more matches
JIT Optimization Strategies
optimization information is currently collected for the following operations: getproperty (obj.prop) setproperty (obj.prop = val) getelement (obj[elemname]) setelement (obj[elemname] = val) call (func(...)) at each operation site, ionmonkey tries a battery of strategies, from the most optimized but most restrictive to the least optimized but least restrictive.
...the function containing the arguments.length is allowed to use the arguments object in the following ways without disabling this optimization: access arguments.length access arguments.callee access individual args using arguments[i] save arguments into variables, as long as those variables cannot be accessed by any nested function, and as long as there exists no eval anywhere within the function or nested function definitions.
...the function containing the arguments.callee is allowed to use the arguments object in the following ways without disabling this optimization: access arguments.length access arguments.callee access individual args using arguments[i] save arguments into variables, as long as those variables cannot be accessed by any nested function, and as long as there exists no eval anywhere within the function or nested function definitions.
...And 10 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
what is important to us now is the following three rights: open source rights: a user can create and distribute copies of the source code; a user can obtain a program’s source code; a user can modify the source code.
...the user is free to use (duplicate, distribute, and modify) the source code, following certain conditions.
... these conditions will vary from one license to the next, but the open source definition stipulates the following minimum conditions: the integrity of the author’s source code must be preserved; no discrimination may be made against individuals or organizations; no discrimination may be made based on field of endeavor; no additional licensing can be required when redistributing; license must not be specific to a product; license must not interfere with other software.
...And 9 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
439 list of commands xul the following lists commands which might be usable by <command> or command dispatchers/controllers.
...a floating panel can be created using the panel element with at least two additional attributes as in the following example: 601 menubuttons xul, xul popup guide menus may be attached to buttons in several ways.
...the following table lists the keys that are checked, and what the menu keyboard listener does in response: 610 positioning xul, xul popup guide there are several ways in which the location of a popup on screen may be controlled.
...And 9 more matches
Client-side storage - Learn web development
type the following lines into your javascript console: localstorage.removeitem('name'); let myname = localstorage.getitem('name'); myname the third line should now return null — the name item no longer exists in the web storage.
... enter the following lines again: let myname = localstorage.getitem('name'); myname you should see that the value is still available, even though the browser has been closed and then opened again.
...add the following lines to your javascript file: // create needed constants const rememberdiv = document.queryselector('.remember'); const forgetdiv = document.queryselector('.forget'); const form = document.queryselector('form'); const nameinput = document.queryselector('#entername'); const submitbtn = document.queryselector('#submitname'); const forgetbtn = document.queryselector('#forgetname'); const h1 = d...
...And 9 more matches
Video and Audio APIs - Learn web development
our finished example will look (and function) something like the following: getting started to get started with this example, download our media-player-start.zip and unzip it into a new directory on your hard drive.
... at the top of this file, insert the following code: const media = document.queryselector('video'); const controls = document.queryselector('.controls'); const play = document.queryselector('.play'); const stop = document.queryselector('.stop'); const rwd = document.queryselector('.rwd'); const fwd = document.queryselector('.fwd'); const timerwrapper = document.queryselector('.timer'); const timer = document.queryselector('.timer span');...
... next, insert the following at the bottom of your code: media.removeattribute('controls'); controls.style.visibility = 'visible'; these two lines remove the default browser controls from the video, and make the custom controls visible.
...And 9 more matches
Working with Svelte stores - Learn web development
give it the following content: import { writable } from 'svelte/store' export const alert = writable('welcome to the to-do list app!') note: stores can be defined and used outside of svelte components, so you can organize them in any way you please.
... give it the following content: <script> import { alert } from '../stores.js' import { ondestroy } from 'svelte' let alertcontent = '' const unsubscribe = alert.subscribe(value => alertcontent = value) ondestroy(unsubscribe) </script> {#if alertcontent} <div on:click={() => alertcontent = ''}> <p>{ alertcontent }</p> </div> {/if} <style> div { position: fixed; cursor: pointer; margin-right: 1.
... in app.svelte we'll import the component; add the following import statement below the existing one: import alert from './components/alert.svelte' then call the alert component just above the todos call, like this: <alert /> <todos {todos} /> load your test app now, and you should now see the alert message on screen.
...And 9 more matches
A guide to searching crash reports
this brings up a search form like the one in the following screenshot.
... the default search: signature facet if you click on the "search" button, you will get results like the ones in the following screenshot.
...the links within the results do the following things.
...And 9 more matches
sslcrt.html
syntax #include <cert.h> secstatus cert_verifycertnow( certcertdbhandle *handle, certcertificate *cert, prbool checksig, seccertusage certusage, void *wincx); parameters this function has the following parameters: handle a pointer to the certificate database handle.
... syntax #include <cert.h> secstatus cert_verifycertname( certcertificate *cert, char *hostname); parameters this function has the following parameters: cert a pointer to the certificate against which to check the hostname referenced by hostname.
...instead, it takes account of the following rules governing the construction of common names in ssl server certificates: * matches anything ?
...And 9 more matches
jpm - Archive of obsolete content
jpm usage is: jpm [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number --addon-dir - directory for your source code, defaulting to the current directory installation jpm is distributed with the node package manager npm.
...add the following line to the end of the file $home/.profile to add it to your path permanently (as the file .profile is executed every time a new terminal is opened): export path="$home/node_modules/.bin/:$path" installing jpm from git alternatively, you can also get the latest version of jpm using git: git clone https://github.com/mozilla-jetpack/jpm.git cd jpm npm install npm link after installing jpm af...
... command reference jpm supports the following commands: jpm init create a skeleton add-on as a starting point for your add-on.
...And 8 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
note: for information about how to find the directory where you installed seamonkey, see: installation directory if you cannot easily find the directory, you can use the following method to find it.
...copy the following code.
... edit the file: installed-chrome.txt at the end of the file, add the following line.
...And 8 more matches
Building up a basic demo with the PlayCanvas engine - Game development
add the following code to the bottom of your second <script> element: var app = new pc.application(canvas); app.start(); the pc global object contains all the playcanvas functions available in the engine.
...again, add the following lines at the bottom of your script.
...let's start by defining the geometry for a cube shape — add the following new code below your previous additions: var box = new pc.entity(); box.addcomponent("model", { type: "box" }); app.root.addchild(box); box.rotate(10, 15, 0); it will create an entity with the box model component and add it to the root of the application, our scene.
...And 8 more matches
Working with JSON - Learn web development
json is a text-based data format following javascript object syntax, which was popularized by douglas crockford.
...add the following at the bottom of your javascript code: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; to create a request, we need to create a new request object instance from the xmlhttprequest constructor, using the new keyword.
... add the following below your last line: let request = new xmlhttprequest(); now we need to open the request using the open() method.
...And 8 more matches
Object building practice - Learn web development
these contain the following, respectively: a very simple html document featuring an <h1> element, a <canvas> element to draw our balls on, and elements to apply our css and javascript to our html.
...let's start by adding the following constructor to the bottom of our code.
... drawing the ball first add the following draw() method to the ball()'s prototype: ball.prototype.draw = function() { ctx.beginpath(); ctx.fillstyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * math.pi); ctx.fill(); } using this function, we can tell the ball to draw itself onto the screen, by calling a series of members of the 2d canvas context we defined earlier (ctx).
...And 8 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
examples example 1: basic syntax the following example demonstrates setinterval()'s basic syntax.
... console.log(a); console.log(b); } example 2: alternating two colors the following example calls the flashtext() function once a second until the stop button is pressed.
... } function stoptextcolor() { clearinterval(nintervid); } </script> </head> <body onload="changecolor();"> <div id="my_box"> <p>hello world</p> </div> <button onclick="stoptextcolor();">stop</button> </body> </html> example 3: typewriter simulation the following example simulates typewriter by first clearing and then slowly typing content into the nodelist that matches a specified group of selectors.
...And 8 more matches
Value definition syntax - CSS: Cascading Style Sheets
bold [ thin && <length> ] this example matches the following values: bold thin 2vh bold 0 thin bold thin 3.5em but not: thin bold 3em, as bold is juxtaposed with the component defined by the brackets, it must appear before it.
... bold <length> , thin this example matches the following values: bold 1em, thin bold 0, thin bold 2.5cm, thin bold 3vh, thin but not: thin 1em, bold, as the entities must be in the expressed order bold 1em thin, as the entities are mandatory; the comma, a literal, must be present bold 0.5ms, thin, as the ms values are not <length> double ampersand separating two or more components, by a double ampersand, &&, means that all these entities are mandatory but may appear in any order.
... bold && <length> this example matches the following values: bold 1em bold 0 2.5cm bold 3vh bold but not: bold, as both components must appear in the value.
...And 8 more matches
Control flow and error handling - JavaScript
for example, do not write code like this: // prone to being misread as "x == y" if (x = y) { /* statements here */ } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment, like this: if ((x = y)) { /* statements here */ } falsy values the following values evaluate to false (also known as falsy values): false undefined null 0 nan the empty string ("") all other values—including all objects—evaluate to true when passed to a conditional statement.
... for example: var b = new boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates to false example in the following example, the function checkdata returns true if the number of characters in a text object is three.
... if no default clause is found, the program resumes execution at the statement following the end of switch.
...And 8 more matches
Manipulating documents - Learn web development
there are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: the window is the browser tab that a web page is loaded into; this is represented in javascript by the window object.
...inside your script element, add the following line: const link = document.queryselector('a'); now we have the element reference stored in a variable, we can start to manipulate it using properties and methods available to it (these are defined on interfaces like htmlanchorelement in the case of <a> element, its more general parent interface htmlelement, and node — which represents all nodes in a dom).
...add the following line below the previous one: link.textcontent = 'mozilla developer network'; we should also change the url the link is pointing to, so that it doesn't go to the wrong place when it is clicked on.
...And 7 more matches
Getting started with Svelte - Learn web development
nevertheless, svelte is particularly appropriate to tackle the following situations: web applications intended for low power devices: applications built with svelte have smaller bundle sizes, which is ideal for devices with slow network connections and limited processing power.
...to achieve this, svelte extends vanilla web technologies in the following ways: it extends html by allowing javascript expressions in markup and providing directives to use conditions and loops, in a fashion similar to handlebars.
... also see the following for more information: "what is npm" on nodejs.org "introducing npx" on the npm blog "the easiest way to get started with svelte" on the svelte blog creating your first svelte app the easiest way to create a starter app template is to just download the starter template application.
...And 7 more matches
Package management basics - Learn web development
type the following command, making sure you are inside the parcel-experiment directory: npm init you will now be asked some questions; npm will then create a default package.json file based on the answers: name: a name to identify the app.
... 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).
...create index.html in your test directory, and give it the following contents: <!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> <title>my test page</title> </head> <body> <script src="./index.js"></script> </body> </html> next, we need to add an index.js file in the same directory as index.html.
...And 7 more matches
TimerFirings logging
set the following environment variable to enable it.
... the following sample shows the basics of this output.
...tivitytracker -991946880[7f46c365ba00]: [6775] fn timer (one_shot 250 ms): presshell::spaintsuppressioncallback -991946880[7f46c365ba00]: [6775] fn timer (one_shot 160 ms): nsbrowserstatusfilter::timeouthandler -991946880[7f46c365ba00]: [6775] iface timer (one_shot 200 ms): 7f46964d7f80 -1340643584[7f46c365ec00]: [6775] obs timer (slack 1000 ms): 7f46a95a0200 each line has the following information.
...And 7 more matches
Index
MozillaTechXPCOMIndex
72 observer notifications xpcom, xpcom:add-ons the following are topics that you can observe during the course of an application.
...the following sections describe the steps you can take to organize the weblock component for distribution and installation.
...the following four sections tell the developer how to download and organize the gecko sdk and create a new project in which components like weblock can be created.
...And 7 more matches
FileSystemEntrySync - Web APIs
[ todo: specify what kind of metadata ] metadata getmetada () raises (fileexception); parameter none returns metadata exceptions this method can raise a fileexception with the following codes: exception description not_found_err the entry does not exist.
... you cannot do the following: move a directory inside itself or to any child at any depth move an entry into its parent if a name different from its current one isn't provided move a file to a path occupied by a directory or move a directory to a path occupied by a file move any element to a path occupied by a directory that is not empty.
... exceptions this method can raise a fileexception with the following codes: exception description encoding_err the name supplied is invalid, because at least one of the characters is reserved or illegal.
...And 7 more matches
Node - Web APIs
WebAPINode
*/ removeallchildren(document.body) recurse through child nodes the following function recursively calls a callback function for each node contained by a root node (including the root itself): function eachnode(rootnode, callback) { if (!callback) { const nodes = [] eachnode(rootnode, function(node) { nodes.push(node) }) return nodes } if (false === callback(rootnode)) { return false } if (rootnode.haschildnodes()) { const nodes = rootnode.childno...
... sample usage the following example prints the textcontent properties of each <span> tag in a <div> element named "box": <div id="box"> <span>foo</span> <span>bar</span> <span>baz</span> </div> const box = document.getelementbyid("box") eachnode(box, function(node) { if (null != node.textcontent) { console.log(node.textcontent) } }) the above will result in the following strings printing to the user's conso...
... realistic usage the following demonstrates a real-world use of the eachnode() function: searching for text on a web-page.
...And 7 more matches
Pointer events - Web APIs
some sensing devices can detect the close proximity of the input device, and the state is expressed as a hover following the mouse.
... the following sub-sections contain short descriptions of each interface and property.
... pointerevent interface the pointerevent interface extends the mouseevent interface and has the following properties.
...And 7 more matches
Numbers and dates - JavaScript
if the digits after the 0b are not 0 or 1, the following syntaxerror is thrown: "missing binary digits after 0b".
...if the digits after 0x are outside the range (0123456789abcdef), the following syntaxerror is thrown: "identifier starts immediately after numeric literal".
... the following table summarizes the number object's properties.
...And 7 more matches
Lexical grammar - JavaScript
only the following unicode code points are treated as line terminators in ecmascript, other line breaking characters are treated as white space (for example, next line, nel, u+0085 is considered as white space).
... the first way is the // comment; this makes all text following it on the same line into a comment.
... keywords reserved keywords as of ecmascript 2015 break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof new return super switch this throw try typeof var void while with yield future reserved keywords the following are reserved as future keywords by the ecmascript specification.
...And 7 more matches
Appendix D: Loading Scripts - Archive of obsolete content
(a standalone xul window can use an onload attribute.) example the following overlay will load the script “overlay.js” from the same directory as the overlay file into the window which it overlays.
... examples the following code will execute a simple script in a sandbox with the privilege level of the current content page.
...uate the script: components.utils.evalinsandbox(script, sandbox, // the javascript version "1.8", // the apparent script filename: "zz-9://plural/zed/alpha", // the apparent script starting line number: 42); the following code will execute a simple script loaded from a local file in the same directory as the current script.
...And 6 more matches
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
following standards is certainly not a new organizational phenomenon; organizations require their employees to follow common rules, or a common set of standards all the time.
...when auditors evaluate an organizations financial health, they do so by following the fasb rules.
...by following the guidelines that have been put into place, organizations like aol can enhance user experience, interoperability, code reuse, shared resources, and goodwill while reducing costs.
...And 6 more matches
Building up a basic demo with Three.js - Game development
let's create it, by adding the following line below our previous lines: var scene = new three.scene(); later, we will be using the .add() method, to add objects to this scene.
...the following lines put the camera in place in the 3d coordinate system, and point it in the direction of our scene, so we can finally see something: var camera = new three.perspectivecamera(70, width/height); camera.position.z = 50; scene.add(camera); add the above lines to your code, below those previously added.
...let's start, by defining the geometry for a cube shape, adding the following just above the render() function: var boxgeometry = new three.boxgeometry(10, 10, 10); in this case, we define a simple cube that is 10 x 10 x 10 units.
...And 6 more matches
Flexbox - Learn web development
the following simple layout requirements are either difficult or impossible to achieve with such tools, in any kind of convenient, flexible way: vertically centering a block of content inside its parent.
... try adding the following declaration to your <section> rule: flex-direction: column; you'll see that this puts the items back in a column layout, much like they were before we added any css.
...one way in which you can fix this is to add the following declaration to your <section> rule: flex-wrap: wrap; also, add the following declaration to your <article> rule: flex: 200px; try this now; you'll see that the layout looks much better with this included: we now have multiple rows — as many flexbox children are fitted onto each row as makes sense, and any overflow is moved down to the next line.
...And 6 more matches
Graceful asynchronous programming with Promises - Learn web development
note: the following example will not work if you just run it directly from the file (i.e.
... inside your <script> element, add the following line: let promise = fetch('coffee.jpg'); this calls the fetch() method, passing it the url of the image to fetch from the network as a parameter.
...this can be done like so — add the following lines below your first line of javascript.
...And 6 more matches
Build your own function - Learn web development
type the following in your browser's javascript console, on any page you like: alert('this is a message'); the alert function takes a single argument — the string that is displayed in the alert box.
... next, add the following inside the <script> element: function displaymessage() { } we start off with the keyword function, which means we are defining a function.
... finally, add the following code inside the curly braces: const html = document.queryselector('html'); const panel = document.createelement('div'); panel.setattribute('class', 'msgbox'); html.appendchild(panel); const msg = document.createelement('p'); msg.textcontent = 'this is a message box'; panel.appendchild(msg); const closebtn = document.createelement('button'); closebtn.textcontent = 'x'; panel.appendchild(closebtn); closebtn.onclick = function() { panel.parentnode.removechild(panel); } this is quite a lot of code to go...
...And 6 more matches
Third-party APIs - Learn web development
you'll find a line similar to the following in the mapquest api example: l.mapquest.key = 'your-api-key-here'; this line specifies an api or developer key to use in your application — the developer of the application must apply to get a key, and then include it in their code to be allowed access to the api's functionality.
...to do this, find the following line: layers: l.mapquest.tilelayer('map') try changing 'map' to 'hybrid' to show a hybrid-style map.
...add the following code to your example, again inside window.onload: l.marker([53.480759, -2.242631], { icon: l.mapquest.icons.marker({ primarycolor: '#22407f', secondarycolor: '#3b5998', shadow: true, size: 'md', symbol: 'a' }) }) .bindpopup('this is manchester!') .addto(map); as you can see, this at its simplest takes two parameters, an array containing the coordinates at which to displa...
...And 6 more matches
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
connecting the behavior in the footer to get the footer working, we need to implement the following thre areas of functionality: a pending todo counter.
...enter the following terminal command to do so: ember generate component-class footer next, go and find the newly-created todomvc/app/components/footer.js file and update it to the following: import component from '@glimmer/component'; import { inject as service } from '@ember/service'; export default class footercomponent extends component { @service('todo-data') todos; } now we need to go back to our todo-data.js file and add some functionality that will allow us to return the number of incomplete todos (useful for showing how many are left), and clear the completed todos ou...
... in todo-data.js, add the following getter underneath the existing all() getter to define what the incomplete todos actually are: get incomplete() { return this.todos.filter(todo => { return todo.iscompleted === false; }); } using array.filter(), we declare that "incomplete" todos are ones that have iscompleted equal to false.
...And 6 more matches
Ember interactivity: Events, classes and state - Learn web development
to create a header class to go with your header component, type this in to your terminal: ember generate component-class header this will create the following empty class file — todomvc/app/components/header.js: import component from '@glimmer/component'; export default class headercomponent extends component { } inside this file we will implement the event handler code.
... update the content to the following: import component from '@glimmer/component'; import { action } from '@ember/object'; export default class headercomponent extends component { @action onkeydown({ target, key }) { let text = target.value.trim(); let hasvalue = boolean(text); if (key === 'enter' && hasvalue) { alert(text); target.value = '' } } } the @action decorator is the only ember-specific code here (aside from extending from the component superclass, and the ember-specific items we are importing using javascript module syntax) — the rest of the file is vanilla javascript, and would work in any application.
... add the following import statement below the existing one: import { tracked } from '@glimmer/tracking'; now add the following class below the previous line you added: class todo { @tracked text = ''; @tracked iscompleted = false; constructor(text) { this.text = text; } } this class represents a todo — it contains a @tracked text property containing the text of the todo, and a @tracked iscomplete...
...And 6 more matches
Deploying our app - Learn web development
add the following line to your project now: "scripts": { ...
... you should now be able to run the following command in the root of your project directory to run the production build step (first quit the running process with ctrl + c if you need to): npm run build this should give you an output like the following, showing you the production files that were created, how big they are, and how long they took to build: dist/src.99d8a31a.js.map 446.15 kb 63ms dist/src.99d8a31a.js 172.51 kb 5.55s dist/stars.7f1dd035.svg 6.31 kb 145ms dist/asteriod2.3ead4904.svg 3.51 kb 155ms dist/asteriod1.698d75e9.svg 2.9 kb 153ms dist/src.84f2edd1.css.m...
...a quick way to verify this is to run the following command: git status you should get a status report of what files are being tracked, what files are staged, and so on — all terms that are part of the git grammar.
...And 6 more matches
How to implement a custom autocomplete search component
to do so you need the following: create an xpcom component that implements the 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.
...basic example for gecko 2.0 and up (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this example is your first best try because: it has no specific logic (it just returns a dummy array of choices) it doesn't care about compatibility with older gecko versions first copy the following javascript code into a file named basic_autocomplete.js into the components directory (or whatever components folder is appropriate in your case): warning: the uuid used below in chrome.manifest and assigned to class_id must be changed before use.
...And 6 more matches
Localizing without a specialized tool
with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation.
... folder structure throughout this document, we will be using the following folder structure in all examples: your working directory (root) mozilla-1.9.2 (en-us source, pulled from http://hg.mozilla.org/releases/mozilla-1.9.2) l10n-mozilla-1.9.2 (a directory containing localization directories, one dir per localization; often referred to as "l10n base") x-testing (a directory with your localization files) please either follow this structure closely or adjust all ...
...get the source change your current directory to your working directory with the following command: $ cd /path/to/your/working/directory first, you will need to check out the sources of mozilla-1.9.2 together with the en-us strings.
...And 6 more matches
Creating localizable web applications
you can use one or more of the following techniques: http accept-language headers, the ua string, ip geolocation.
...consider the following example: a filmreel-like slideshow showcasing highlighted features of the product or featured designs.
...consider the following example: snippet 1.
...And 6 more matches
pkfnc.html
syntax #include <pk11func.h> #include <certt.h> certcertificate *pk11_findcertfromnickname( char *nickname, void *wincx); parameters this function has the following parameters: nickname a pointer to the nickname in the certificate database or to the nickname in the token.
... syntax #include <pk11func.h> #include <certt.h> #include <keyt.h> seckeyprivatekey *pk11_findkeybyanycert( certcertificate *cert, void *wincx); parameters this function has the following parameters: cert a pointer to a certificate structure in the certificate database.
... syntax #include <pk11func.h> char *pk11_getslotname(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure.
...And 6 more matches
SpiderMonkey Build Documentation
refer the release notes under command line tools -> new features the release notes also states that this compatibility package will no longer be provided in the near future, so the build system on macos will have to be adapted to look for headers in the sdk until then, the following should help, open /library/developer/commandlinetools/packages/macos_sdk_headers_for_macos_10.14.pk this builds an executable named js in the directory build-release/dist/bin.
...thus, in addition to following the steps above, you should also create a debug build using these steps: cd js/src # this name should end with "_dbg.obj" to make the version control system ignore it.
...hence, the following instructions should only be relevant if you're on windows or compiling an older version of spidermonkey.
...And 6 more matches
Introduction to XPCOM for the DOM
pure virtual methods are declared with the following syntax: virtual nsresult functionfoo() = 0; an interface is thus simply a c++ class where all the member functions are declared as pure virtual functions.
...the c++ code is the following: class nsfoo : public nsifoo for those unfamiliar with object-oriented c++, this means that nsfoo is declared as "derived from" nsifoo, and that nsifoo is a "base class" of nsfoo.
...the goal is the following: find out whether an object (an instance of a class) implements a given interface.
...And 6 more matches
WebIDL bindings
adding webidl bindings to a class to add a webidl binding for interface myinterface to a class mozilla::dom::myinterface that's supposed to implement that interface, you need to do the following: if your interface doesn't inherit from any other interfaces, inherit from nswrappercache and hook up the class to the cycle collector so it will trace the wrapper cache properly.
... for example, this idl: [constructor, constructor(unsigned long somenumber)] interface myinterface { }; will require the following declarations in myclass: class myclass { // various nsisupports stuff or whatnot static already_addrefed<myclass> constructor(const globalobject& aglobal, errorresult& rv); static already_addrefed<myclass> constructor(const globalobject& aglobal, uint32_t asomenumber, ...
...for example, objectorlong would have the following methods: bool isobject() const; jsobject* getasobject() const; void settoobject(jscontext*, jsobject*); bool islong() const; int32_t getaslong() const; int32_t& setaslong() owning unions used on the stack should be declared as a rootedunion<uniontype>, for example, rootedunion<owningobjectorlong>.
...And 6 more matches
Using the application cache - HTML: Hypertext Markup Language
an application cache gives the following benefits: offline browsing users can navigate a site even when they are offline.
...in addition, the browser also sends a checking event to the window.applicationcache object, and fetches the manifest file, following the appropriate http caching rules.
... if the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by calling applicationcache.add()—are fetched into a temporary cache, following the appropriate http caching rules.
...And 6 more matches
Working with objects - JavaScript
to illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function: function showprops(obj, objname) { var result = ``; for (var i in obj) { // obj.hasownproperty() is used to filter out properties from the object's prototype chain if (obj.hasownproperty(i)) { result += `${objname}.${i} = ${obj[i]}\n`; } } return r...
...esult; } so, the function call showprops(mycar, "mycar") would return the following: mycar.make = ford mycar.model = mustang mycar.year = 1969 enumerate the properties of an object starting with ecmascript 5, there are three native ways to list/traverse object properties: for...in loops this method traverses all enumerable properties of an object and its prototype chain.
...however, this can be achieved with the following function: function listallproperties(o) { var objecttoinspect; var result = []; for(objecttoinspect = o; objecttoinspect !== null; objecttoinspect = object.getprototypeof(objecttoinspect)) { result = result.concat( object.getownpropertynames(objecttoinspect) ); } return result; } this can be useful to reveal "hidden" properties (properties in ...
...And 6 more matches
cfx - Archive of obsolete content
cfx supports the following global options: -h, --help - show a help message and exit -v, --verbose - enable lots of output "command-specific options" are documented alongside the commands.
... this command will create an skeleton add-on, as a starting point for your own add-on development, with the following file structure: my-addon data docs main.md lib main.js package.json readme.md tests test-main.js cfx run this command is used to run the add-on.
... for example, to pass the -jsconsole argument to firefox, which will launch the javascript error console, try the following: cfx run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --extra-packages=extra_packages extra packages to include, specified as a comma-separated list of package names.
...And 5 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
the following code shows blocks designated for internet explorer: .
... nextsibling returns the node immediately following the current one.
...for example, the following code assumes that the div node already exists in the dom by the time the script block executes: ...
...And 5 more matches
Tamarin build documentation - Archive of obsolete content
tamarin source versions the following instructions are for obtaining and building the tamarin central source code.
... supported platforms tamarin currently supports the following operating systems and/or architectures.
... use the following command to create a copy of the tamarin repository: $ hg clone http://hg.mozilla.org/tamarin-central tamarin-central tips for working with mercurial can be found here.
...And 5 more matches
Custom toolbar button - Archive of obsolete content
in the extensions directory, create a new directory with the following name.
... copy the name from here and paste it, to avoid typing errors: custom-toolbar-button@example.com perform the following steps in this new directory, creating two files and a directory there.
... copy the following content, making sure that you scroll to get all of it.
...And 5 more matches
XUL Questions and Answers - Archive of obsolete content
the following bugs were reported on this issue: bug 22942, bug 133698.
...the following is the code they wrote: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="test-window" title="check list test" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> <listbox rows="4"> <listhead> <listheader label="multi-column"/> </listhead> <listcols> <listcol flex="1"/> </list...
... using the following code sample, // get browsers object var browsers=document.getelementbyid('content').browsers; var numbrowsers=browsers.length; for (var i=0; numbrowsers>i; i++) { var thisuri=browsers[i].currenturi.spec; // do something with it.
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
an excellent semantic example might look something like the following: <h1>my heading</h1> <p>this is the first section of my document.</p> <p>i'll add another paragraph here too.</p> <ol> <li>here is</li> <li>a list for</li> <li>you to read</li> </ol> <h2>my subheading</h2> <p>this is the first subsection of my document.
...using presentational html and line breaks, something like the following: <font size="7">my heading</font> <br><br> this is the first section of my document.
...to do that, we had to add the following bit of javascript trickery: document.onkeydown = function(e) { if(e.keycode === 13) { // the enter/return key document.activeelement.click(); } }; here we add a listener to the document object to detect when a button has been pressed on the keyboard.
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
an excellent semantic example might look something like the following: <h1>my heading</h1> <p>this is the first section of my document.</p> <p>i'll add another paragraph here too.</p> <ol> <li>here is</li> <li>a list for</li> <li>you to read</li> </ol> <h2>my subheading</h2> <p>this is the first subsection of my document.
...using presentational html and line breaks, something like the following: <font size="7">my heading</font> <br><br> this is the first section of my document.
...to do that, we had to add the following bit of javascript trickery: document.onkeydown = function(e) { if(e.keycode === 13) { // the enter/return key document.activeelement.click(); } }; here we add a listener to the document object to detect when a button has been pressed on the keyboard.
...And 5 more matches
Advanced form styling - Learn web development
for example, let's take the following controls: <form> <p> <label for="search">search: </label> <input id="search" name="search" type="search"> </p> <p> <label for="text">text: </label> <input id="text" name="text" type="text"> </p> <p> <label for="date">date: </label> <input id="date" name="date" type="datetime-local"> </p> <p> <label for="radio">radio: </label> <input id="radio" name="...
...radio" type="radio"> </p> <p> <label for="checkbox">checkbox: </label> <input id="checkbox" name="checkbox" type="checkbox"> </p> <p><input type="submit" value="submit"></p> <p><input type="button" value="button"></p> </form> applying the following css to them removes system-level styling.
... the following live example shows you what they look like in your system — default on the left, and with the above css applied on the right (find it here also if you want to test it on other systems).
...And 5 more matches
Fetching data from the server - Learn web development
just inside the <script> element, add the following code.
...first of all, put the following beneath your previous code block — this is the empty shell of the function.
...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.
...And 5 more matches
Handling text — strings in JavaScript - Learn web development
creating a string to start with, enter the following lines: let string = 'the revolution will not be televised.'; string; just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value.
...try entering the following lines: let badstring = this is a test; let badstring = 'this is a test; let badstring = this is a test'; these lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar.
... the following will work if you previously defined the variable string — try it now: let badstring = string; badstring; badstring is now set to have the same value as string.
...And 5 more matches
Getting started with Ember - Learn web development
use cases generally, emberjs works well for building apps that desire either or both of the following traits: single page applications, including native-like web apps, and progressive web apps (pwas) ember works best when it is the entire front end of your application.
... now type the following into your terminal to install ember-cli: npm install -g ember-cli this tool provides the ember program in your terminal, which is used to create, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their options).
... to create a brand new application, type the following in your terminal.
...And 5 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
add the following line just inside the top of your todo(props) { … } component definition: const [isediting, setediting] = usestate(false); next, we're going to rethink the <todo /> component — from now on, we want it to display one of two possible “templates", rather than the single template it's used so far: the "view" template, when we are just viewing a todo; this is what we’ve used in rest of the...
...still in todo.js, put the following underneath the existing hook: const [newname, setnewname] = usestate(''); next, create a handlechange() function that will set the new name; put this underneath the hooks but before the templates: function handlechange(e) { setnewname(e.target.value); } now we'll update our editingtemplate's <input /> field, setting a value attribute of newname, and binding our handlechange() function to it...
...update it as follows: <input id={props.id} classname="todo-text" type="text" value={newname} onchange={handlechange} /> finally, we need to create a function to handle the edit form’s onsubmit event; add the following just below the previous function you added: function handlesubmit(e) { e.preventdefault(); props.edittask(props.id, newname); setnewname(""); setediting(false); } remember that our edittask() callback prop needs the id of the task we're editing as well as its new name.
...And 5 more matches
Strategies for carrying out testing - Learn web development
throughout the following sections, we'll build up a support chart in this format.
... this gives us the following support chart so far: a grade: chrome and firefox for windows/mac, safari for mac, edge and ie for windows (last two versions of each), ios safari for iphone/ipad, android stock browser (last two versions) on phone/tablet, chrome and firefox for android (last two versions) on phone tablet b grade: ie 9 for windows c grade: n/a if you live somewhere else, or are working on a site that will ...
... consider the following example (see the source code, and also the example running live): test criteria for this feature could be written like so: a and b grade: button should be activatable by the user's primary control mechanism, whatever it is — this should include mouse, keyboard, and touch.
...And 5 more matches
Displaying Places information using views
places provides the following built-in views: tree menu toolbar instantiating the three built-in views are simply standard xul elements with a special type attribute whose value is "places".
... the following example uses the built-in tree view to display bookmarks whose titles or urls contain "mozilla".
... if you would like your tree view to be styled in the same manner that firefox styles its uses of the view, you should include the following stylesheet.
...And 5 more matches
QA phase
preliminary instructions we will be using the following file directories for this example: your working directory (root)/ mozilla-aurora (en-us source, pulled from http://hg.mozilla.org/releases/mozilla-aurora )/ l10n-central (directory for l10n directories, one per l10n; often referred to as "l10n base")/ your-locale-code (a directory with your l10n files, in this example we'll use x-testing) example: root/mozilla-aurora & root/l10n...
... to copy this file to the appropriate directory, do the following: navigate to your working directory from your command-line terminal (i.e., where you created the folder structure described above).
... enter the following commands: mkdir -p l10n-central/x-testing/toolkit/ cp mozilla-aurora/toolkit/locales/defines.inc l10n-central/x-testing/toolkit/defines.inc tah-dah!
...And 5 more matches
sslerr.html
id not found in server's session cache." ssl_error_server_cache_not_configured -12185 "ssl server cache not configured and not disabled for this socket." ssl_error_renegotiation_not_allowed -12176 "renegotiation is not allowed on this ssl socket." received a malformed (too long or short or invalid content) ssl handshake: all the error codes in the following block indicate that the local socket received an improperly formatted ssl3 handshake message from the remote peer.
...l received a malformed client key exchange handshake message." ssl_error_rx_malformed_finished -12252 "ssl received a malformed finished handshake message." ssl_error_rx_malformed_new_session_ticket -12178 "ssl received a malformed new session ticket handshake message." received a malformed (too long or short) ssl record: all the error codes in the following block indicate that the local socket received an improperly formatted ssl3 record from the remote peer.
...formed_alert -12250 "ssl received a malformed alert record." ssl_error_rx_malformed_handshake -12249 "ssl received a malformed handshake record." ssl_error_rx_malformed_application_data -12248 "ssl received a malformed application data record." received an ssl handshake that was inappropriate for the current state: all the error codes in the following block indicate that the local socket received an ssl3 handshake message from the remote peer at a time when it was inappropriate for the peer to have sent this message.
...And 5 more matches
Web Replay
in practice, non-deterministic replay is allowed in the following areas: heap allocations can be performed by the ipc and debugger components and so can differ between recording and replay.
... this non-determinism is prevented from spreading too far with the following techniques: different pointer values can affect the internal layout of hash tables.
... recording a recording content process differs from a normal content process in the following ways: calls to certain functions are intercepted by hooking them (rewriting the machine code at their entry points to call a different function with the same signature), including the function used to dispatch mach messages.
...And 5 more matches
Mozilla internal string guide
all string classes support the following three ownership models dynamically: reference counted, copy-on-write, buffers (the default) adopted buffers (a buffer that the string class owns, but is not reference counted, because it came from somewhere else) dependent buffers, that is, an underlying buffer that the string class does not own, but that the caller that constructed the string guarantees will outlive the string instance in...
... the following is a list of the most common concrete classes.
... if you wish to make a copy of a string into a new character buffer (char16_t*/char*), the preferred way is to allocate it with one of the following methods: char16_t* tonewunicode(nsastring&) - allocates a char16_t*buffer from an nsastring.
...And 5 more matches
Plug-in Basics - Plugins
when the user opens a page that contains embedded data of a media type that invokes a plug-in, the browser responds with the following sequence of actions: check for a plug-in with a matching mime type load the plug-in code into memory initialize the plug-in create a new instance of the plug-in gecko can load multiple instances of the same plug-in on a single page, or in several open windows at the same time.
... the following stages outline the life of a plug-in from loading to deletion: when gecko encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it dynamically loads the plug-in code into memory, if it hasn't been loaded already, and it creates a new instance of the plug-in.
...the next section, how gecko finds plug-ins, describes these rules, and the following section, checking plug-ins by mime type, describes how you can use javascript to locate plug-ins yourself and establish which ones are to be registered for which mime types.
...And 5 more matches
@supports - CSS: Cascading Style Sheets
WebCSS@supports
the following example returns true if the browser's transform-origin property considers 5% 5% valid: @supports (transform-origin: 5% 5%) {} function syntax the second basic supports condition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized.
...the following example returns true if the browser supports the child combinator: @supports selector(a > b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one.
... the following example returns true if the browser's transform-origin property doesn't consider 10em 10em 10em valid: @supports not (transform-origin: 10em 10em 10em) {} as with any operator, the not operator can be applied to a declaration of any complexity.
...And 5 more matches
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
a first look our three properties control the following aspects of a flex item's flexibility: flex-grow: how much of the positive free space does this item get?
...the following code would set the flex-grow property to 2, flex-shrink to 1 and flex-basis to auto.
... in the following examples i am working with flex-direction set to row, therefore the size of items will always come from their width.
...And 5 more matches
Specificity - CSS: Cascading Style Sheets
selector types the following list of selector types increases by specificity: type selectors (e.g., h1) and pseudo-elements (e.g., ::before).
...when used with the following html ...
...when used with the following html ...
...And 5 more matches
Challenge solutions - Developer guides
solution add the following style declaration to the strong rule: font: 200% serif; if you use separate declarations for font-size and font-family, then the font-style setting on the first paragraph is not overridden.
... solution the following values are reasonable approximations of the named colors: strong { color: #f00; /* red */ background-color: #ddf; /* pale blue */ font: 200% serif; } .carrot { color: #fa0; /* orange */ } .spinach { color: #080; /* dark green */ } p { color: #00f; /* blue */ } content add an image challenge add a one rule to your stylesheet so that it displays the image at the start of each line.
... solution the following rule achieves this effect: ul { border: 10px solid lightblue; width: 100px; } layout default image position fixed image position challenge change your sample document, doc2.html, adding this tag to it near the end, just before </body>: <img id="fixed-pin" src="yellow-pin.png" alt="yellow map pin"> predict where the image will appear in your document.
...And 5 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
width image same as width attribute for <img> a few additional non-standard attributes are listed following the descriptions of the standard attributes.
...if you have an input whose name is set to guest and another whose name is hat-size, the following code can be used: let form = document.queryselector("form"); let guestname = form.elements.guest; let hatsize = form.elements["hat-size"]; when this code has run, guestname will be the htmlinputelement for the guest field, and hatsize the object for the hat-size field.
... non-standard attributes the following non-standard attributes are also available on some browsers.
...And 5 more matches
Global attributes - HTML: Hypertext Markup Language
in addition to the basic html global attributes, the following global attributes also exist: xml:lang and xml:base — these are inherited from the xhtml specifications and deprecated, but kept for compatibility purposes.
...it can have the following values: off or none, no autocapitalization is applied (all letters default to lowercase) on or sentences, the first letter of each sentence defaults to a capital letter; all other letters default to lowercase words, the first letter of each word defaults to a capital letter; all other letters default to lowercase characters, all letters should default to uppercase class a space-se...
...the attribute must take one of the following values: true or the empty string, which indicates that the element must be editable; false, which indicates that the element must not be editable.
...And 5 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
a “simple request” is one that meets all the following conditions: one of the allowed methods: get head post apart from the headers automatically set by the user agent (for example, connection, user-agent, or the other headers defined in the fetch spec as a “forbidden header name”), the only headers which are allowed to be manually set are those which the fetch spec defines as a “cors-safelisted request-header”, which are: ...
...what values webkit/safari consider “nonstandard” is not documented, except in the following webkit bugs: require preflight for non-standard cors-safelisted request headers accept, accept-language, and content-language allow commas in accept, accept-language, and content-language request headers for simple cors switch to a blacklist model for restricted accept headers in simple cors requests no other browsers implement these extra restrictions, because they’re not part of the sp...
... the following is an example of a request that will be preflighted: const xhr = new xmlhttprequest(); xhr.open('post', 'https://bar.other/resources/post-here/'); xhr.setrequestheader('x-pingother', 'pingpong'); xhr.setrequestheader('content-type', 'application/xml'); xhr.onreadystatechange = handler; xhr.send('<person><name>arun</name></person>'); the example above creates an xml body to send with the post r...
...And 5 more matches
Closures - JavaScript
lexical scoping consider the following example code: function init() { var name = 'mozilla'; // name is a local variable created by init function displayname() { // displayname() is the inner function, a closure alert(name); // use variable declared in the parent function } displayname(); } init(); init() creates a local variable called name and a function called displayname().
... closure consider the following code example: function makefunc() { var name = 'mozilla'; function displayname() { alert(name); } return displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() function above.
...you can attach them to buttons (in this case hyperlinks) as demonstrated in the following code example.
...And 5 more matches
Indexed collections - JavaScript
creating an array the following statements create equivalent arrays: let arr = new array(element0, element1, ..., elementn) let arr = array(element0, element1, ..., elementn) let arr = [element0, element1, ..., elementn] element0, element1, ..., elementn is a list of values for the array's elements.
... to create an array with non-zero length, but without any items, either of the following can be used: // this...
...the following example illustrates this behavior.
...And 5 more matches
JavaScript modules - JavaScript
the following is found in main.js, below the import lines: let mycanvas = create('mycanvas', document.body, 480, 320); let reportlist = createreportlist(mycanvas.id); let square1 = draw(mycanvas.ctx, 50, 50, 100, 'blue'); reportarea(square1.length, reportlist); reportperimeter(square1.length, reportlist); note: although imported features are available in the file, they are read only views of the feature t...
...we'll look at these in the following sections.
... so for example, both of the following would do the same job, albeit in a slightly different way: // inside module.js export { function1 as newfunctionname, function2 as anothernewfunctionname }; // inside main.js import { newfunctionname, anothernewfunctionname } from './modules/module.js'; // inside module.js export { function1, function2 }; // inside main.js import { function1 as newfunctionname, function2 as anothernewfunctionname } from './modules/module.js'; let's look at a real example.
...And 5 more matches
Tabbed browser - Archive of obsolete content
browser windows, then in a new window instead) "tab" new tab (if there aren't any browser windows, then in a new window instead) "tabshifted" same as "tab" but in background if default is to select new tabs, and vice versa "window" new window "save" save to disk (with no filename hint!) openuilink( url, e, ignorebutton, ignorealt, allowkeywordfixup, postdata, referrerurl ) the following code will open a url in a new tab, an existing tab, or an existing window based on which mouse button was pressed and which hotkeys (ex: ctrl) are being held.
...following this practice minimizes the proliferation of tabs and browsers created by your extension.
...the following code demonstrates how to re-use an existing tab that already displays the desired url/uri.
...And 4 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
the following picture shows the model that is the essence of this technote.
...we've separated this sample in two main components following the model.
...so the following piece of html defines an iframe element which is not visible to the user: <div style="visibility:hidden; position:absolute; top:-1000px; left:-1000px"> <iframe id="bridgeframe" src=""></iframe> </div> the javascript code located in the data loader component will be interacting with this iframe element, requesting data from the server.
...And 4 more matches
Creating a Help Content Pack - Archive of obsolete content
insert into it the following text: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:nc="http://home.netscape.com/nc-rdf#"> </rdf:rdf> if you're familiar with html or xml, you might recognize this as the container element for the whole document.
...(we're still not actually to the point where we're describing the actual data in each of these, so we'll just use some filler data for now.) add the following code inside the rdf:description element you just created: <nc:panellist> <rdf:seq> </rdf:seq> </nc:panellist> you'll create the relevant information descriptions within the rdf:seq element.
...each panel is specified by one rdf:description element with the following attributes: nc:panelid specifies the name of the panel, which may be any one of glossary, search, toc, or index.
...And 4 more matches
Binding Attachment and Detachment - Archive of obsolete content
in the following example, a binding is referenced that will be attached to all html checkbox elements.
... for example, given a binding d1, with an explicit inheritance chain of d1 -> d2 -> d3 if this element is attached to an element using element.style.mozbinding that already has a binding chain of s1 -> s2 -> s3 the resulting binding chain following the addition of the binding is d1 -> d2 -> d3 -> s1 -> s2 -> s3 the inheritance between d3 and s1 is implicit, meaning that there is no connection in the xbl documents between the two bindings.
... when a binding is attached, the following events occur: if required, anonymous content is cloned from the binding's content template and inserted around the bound element.
...And 4 more matches
Document Object Model - Archive of obsolete content
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.
...for example, the following code will display the text 'message' in an alert twice.
...to do this, we can do the following: alert(window.opener.gettext()); each window has an opener property which holds the window object that opened this one.
...And 4 more matches
Skinning XUL Files by Hand - Archive of obsolete content
following the instructions here, you are going to create a skin for a xul file and apply it by specifying classes for all of the interested elements.
...for example, when a button is defined as follows: <button class="plain" label="push me" /> then the following very simple style definition applies to that button.
... button.plain { border: 0px !important; } the global skin, in which styles for these several button classes and dozens of other elements are defined, is described in the following section.
...And 4 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
figure 4 assumes the following: the user has already decided to trust the server, either without authentication or on the basis of server authentication via ssl.
... types of certificates common types of certificates include the following: client ssl certificates.
...any of the binary formats can be imported in text form, which begins with the line: -----begin certificate----- following this line is the certificate data, which can be in any of the binary formats described.
...And 4 more matches
Mozilla XForms User Interface - Archive of obsolete content
these attributes are combined into following logical groups.
...it can have the following representations: text field - default representation.
...it can have the following presentations: text - default representation for data of most types, especially static text.
...And 4 more matches
RDF in Mozilla FAQ - Archive of obsolete content
var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // note that ds will load asynchronously, so assertions will not // be immediately available alternatively, you can create one directly using the xpcom component manager, as the following code fragment illustrates: // create an rdf/xml datasource using the xpcom component manager var ds = components .classes["@mozilla.org/rdf/datasource;1?name=xml-datasource"] .createinstance(components.interfaces.nsirdfdatasource); // the nsirdfremotedatasource interface has the interfaces // that we need to setup the datasource.
...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("er...
...for example, the following xul fragment illustrates how to add the bookmarks service as a datasource into a xul template.
...And 4 more matches
Move the ball - Game development
delete all the javascript you currently have inside your html file except for the first two lines, and add the following below them.
...now, let's draw the ball — add the following inside your draw() function: ctx.beginpath(); ctx.arc(50, 50, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); try your updated code now — the ball should be repainted on every frame.
... first, add the following two lines above your draw() function, to define x and y: var x = canvas.width/2; var y = canvas.height-30; next update the draw() function to use the x and y variables in the arc() method, as shown in the following highlighted line: function draw() { ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } now comes the important part: we want to add a small value t...
...And 4 more matches
Player paddle and controls - Game development
loading the paddle first, add the paddle variable we will be using in our game, right after the ball variable: var paddle; then, in the preload function, load the paddle image by adding the following new load.image() call: function preload() { // ...
... rendering the paddle, with physics next up, we will init our paddle by adding the following add.sprite() call inside the create() function — add it right at the bottom: paddle = game.add.sprite(game.world.width*0.5, game.world.height-5, 'paddle'); we can use the world.width and world.height values to position the paddle exactly where we want it: game.world.width*0.5 will be right in the middle of the screen.
...add the following line below the previous new one: paddle.anchor.set(0.5,1); the paddle is now positioned right where we want it to be.
...And 4 more matches
Plug-in Development Overview - Gecko Plugin API Reference
a basic overview of the plug-in development process is given in the following steps.
...the following sections describe platform-specific discovery and registration: ms windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins.
... for this the version stamp of the embedded resource of the plug-in dll should contain the following set of string/value pairs: mimetype: for mime types fileextents: for file extensions fileopenname: for file open template productname: for plug-in name filedescription: for description language: for language in use in the mime types and file extensions strings, multiple values are separated by the "|" character, for example: video/quicktime|audio/aiff|image/jpeg the version stamp ...
...And 4 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
underneath the preceding element in a horizontal writing mode, and above the following element (commonly known as a block-level element).
... 49 cors-safelisted request header cors, fetch a cors-safelisted request header is one of the following http headers: 50 cors-safelisted response header cors, fetch, glossary, http a cors-safelisted response header is an http header which has been safelisted so that it will not be filtered when responses are processed by cors, since they're considered safe (as the headers listed in access-control-expose-headers).
...not all http responses can be cached, these are the following constraints for an http response to be cached: 61 caldav caldav, glossary, infrastructure caldav (calendaring extensions to webdav) is a protocol standardized by the ietf and used to remotely access calendar data from a server.
...And 4 more matches
Styling tables - Learn web development
link the css to the html by placing the following line of html inside your <head>: <link href="style.css" rel="stylesheet" type="text/css"> spacing and layout the first thing we need to do is sort out the spacing/layout — default table styling is so cramped!
... to do this, add the following css to your style.css file: /* spacing */ table { table-layout: fixed; width: 100%; border-collapse: collapse; border: 3px solid purple; } thead th:nth-child(1) { width: 30%; } thead th:nth-child(2) { width: 20%; } thead th:nth-child(3) { width: 15%; } thead th:nth-child(4) { width: 35%; } th, td { padding: 20px; } the most important parts to note are as follows: a table-layout value of fixed is generally a good idea to set on your table, as it makes the table behave a bit more predictably by default.
... first, add the following <link> element into your html head, just above your existing <link> element: <link href='https://fonts.googleapis.com/css?family=rock+salt' rel='stylesheet' type='text/css'> now add the following css into your style.css file, below the previous addition: /* typography */ html { font-family: 'helvetica neue', helvetica, arial, sans-serif; } thead th, tfoot th { font-family: 'rock salt', c...
...And 4 more matches
Styling lists - Learn web development
in our example, we've set the ordered list to use uppercase roman numerals, with: ol { list-style-type: upper-roman; } this gives us the following look: you can find a lot more options by checking out the list-style-type reference page.
... 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 gives us the following result: list-style shorthand the three properties mentioned above can all be set using a single shorthand property, list-style.
...And 4 more matches
UI pseudo-classes - Learn web development
for example, if we apply the following css to the above html: input:required { border: 1px solid black; } input:optional { border: 1px solid silver; } the required controls would have a black border, and the optional control will have a silver border, like so: you can also try submitting the form without filling it in, to see the client-side validation error messages browsers give you by default.
... as in the previous example, we've got extra <span>s to generate content on, which we'll use to provide indicators of valid/invalid data: <div> <label for="fname">first name *: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> to provide these indicators, we use the following css: input + span { position: relative; } input + span::before { position: absolute; right: -20px; top: 5px; } input:invalid { border: 2px solid red; } input:invalid + span::before { content: '✖'; color: red; } input:valid + span::before { content: '✓'; color: green; } as before, we set the <span>s to position: relative so that we can position the generated content rel...
...both of these have the following html structure for the inputs: <p> <input type="radio" name="fruit" value="cherry" id="cherry"> <label for="cherry">cherry</label> <span></span> </p> for the :default example, we've added the checked attribute to the middle radio button input, so it will be selected by default when loaded.
...And 4 more matches
HTML basics - Learn web development
for example, take the following line of content: my cat is very grumpy if we wanted the line to stand by itself, we could specify that it is a paragraph by enclosing it in paragraph tags: <p>my cat is very grumpy</p> anatomy of an html element let's explore this paragraph element a bit further.
... elements can also have attributes that look like the following: attributes contain extra information about the element that you don't want to appear in the actual content.
... an attribute should always have the following: a space between it and the element name (or the previous attribute, if the element already has one or more attributes).
...And 4 more matches
Making decisions in your code — conditionals - Learn web development
else syntax basic if...else syntax looks like the following in pseudocode: if (condition) { code to run if condition is true } else { run some other code instead } here we've got: the keyword if followed by some parentheses.
... this code is pretty human-readable — it is saying "if the condition returns true, run code a, else run code b" you should note that you don't have to include the else and the second curly brace block — the following is also perfectly legal code: if (condition) { code to run if condition is true } run some other code however, you need to be careful here — in this case, the second block of code is not controlled by the conditional statement, so it always runs, regardless of whether the condition returns true or false.
... as a final point, you may sometimes see if...else statements written without the curly braces, in the following shorthand style: if (condition) code to run if condition is true else run some other code instead this is perfectly valid code, but using it is not recommended — it is much easier to read the code and work out what is going on if you use the curly braces to delimit the blocks of code, and use multiple lines and indentation.
...And 4 more matches
Useful string methods - Learn web development
try entering the following lines: let browsertype = 'mozilla'; browsertype.length; this should return the number 7, because "mozilla" is 7 characters long.
... to retrieve the last character of any string, we could use the following line, combining this technique with the length property we looked 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.
...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.
...And 4 more matches
Ember app structure and componentization - Learn web development
this already exists, and its contents currently look like so: {{!-- the following component displays ember's default welcome message.
...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.
... looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up the ui, but let's plan on splitting the html out into the following components: the component groupings are as follows: the main input / "new-todo" (red in the image) the containing body of the todo list + the mark-all-complete button (purple in the image) the mark-all-complete button, explicitly highlighted for reasons given below (yellow in the image) each todo is an individual component (green in the image) the footer (blue in the image) ...
...And 4 more matches
React interactivity: Events and state - Learn web development
write the following above your handlesubmit() function, inside form(): const [name, setname] = usestate('use hooks!'); what's going on in this line of code?
... tasks as state import usestate into app.js, so that we can store our tasks in state — update your react import line to the following: import react, { usestate } from "react"; we want to pass props.tasks into the usestate() hook – this will preserve its initial state.
... add the following right at the top of your app() function definition: const [tasks, settasks] = usestate(props.tasks); now, we can change our tasklist mapping so that it is the result of mapping tasks, instead of props.tasks.
...And 4 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
replace the existing <ul> element with the following simplified version to get an idea of how it works: <ul> {#each todos as todo, index (todo.id)} <li> <input type="checkbox" checked={todo.completed}/> {index}.
...replace your existing <ul> block with the following: <!-- todos --> <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading"> {#each todos as todo (todo.id)} <li class="todo"> <div class="stack-small"> <div class="c-cb"> <input type="checkbox" id="todo-{todo.id}" checked={todo.completed}/> <label for="todo-{todo.id}" class="todo-label"> {todo.name} </label> </div> ...
...in the following code they are assigned a value when the component is instantiated and the script is executed, but after that, their values are not modified: let totaltodos = todos.length let completedtodos = todos.filter(todo => todo.completed).length we could recalculate them after toggling and removing todos, but there's an easier way to do it.
...And 4 more matches
Configuring Build Options
please read the following directions carefully before building, and follow them in order.
... adding the following line to your mozconfig allows you to change the objdir: mk_add_options moz_objdir=@topsrcdir@/obj-@config_guess@ it is a good idea to have your objdir name start with obj so that mercurial ignores it.
... choose one of the following options to add to your mozconfig file: browser (firefox) ac_add_options --enable-application=browser note: this is the default mail (thunderbird) ac_add_options --enable-application=comm/mail mozilla suite (seamonkey) ac_add_options --enable-application=suite calendar (lightning extension, uses thunderbird) ac_add_options --enable-application=comm/mail ac_add_o...
...And 4 more matches
Application Translation with Mercurial
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 source code get the source code by downloading the following file: firefox desktop or firefox for android: download the mozilla-<branch>.hg file (e.g.
... copy the repository to your computer by running the following command: hg clone http://hg.mozilla.org/releases/l10n/mozilla-aurora/de/ de-mozilla-aurora this should proceed pretty fast.
...And 4 more matches
Bootstrapping a new locale
(you should "cd" to the directory before beginning.) in the terminal, type the following command: $ hg clone http://hg.mozilla.org/releases/mozilla-x.x.x/ where "x.x.x" is the existing release branch version.
... navigate to that level making sure you are *not* inside mozilla-1.9.x/ and then run the following commands.
...we'll first navigate to the directory called "browser" by running the following commands one after the other from your command line: $ cd [ab-cd]/browser/chrome/browser to see what is contained in "browser" type $ ls and, you should see the following output from your terminal: aboutcerterror.dtd pageinfo.dtd aboutdialog.dtd pageinfo.properties aboutprivatebrowsing.dtd pagereportfirsttime.dtd aboutrobots.dtd places aboutsessionrest...
...And 4 more matches
AsyncTestUtils extended framework
boilerplate add the following code to the top of your test file to import everything you need: load("../../mailnews/resources/loghelper.js"); load("../../mailnews/resources/asynctestutils.js"); load("../../mailnews/resources/messagegenerator.js"); load("../../mailnews/resources/messagemodifier.js"); load("../../mailnews/resources/messageinjection.js"); if the directory where you are adding the tests does not have a head_*.js file that has the two following lines, add them at the top of your test file (before the lines shown above): load("../../mailnews/resources/maildirservice.js"); load("../../m...
...ailnews/resources/mailtestutils.js"); at the bottom of the test file, add the following: var tests =[ // list your tests here ]; function run_test() { configure_message_injection({mode: "local"}); async_run_tests(tests); } asynchronous testing basics why do we need it?
...your test functions need to agree to the following contract: the asynchronous function contract a function should yield false or return false when something asynchronous is going on.
...And 4 more matches
JSS Provider Notes
apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension.
... the following example shows how you can specify which token is used for various jca operations: // lookup pkcs #11 tokens cryptomanager manager = cryptomanager.getinstance(); cryptotoken tokena = manager.gettokenbyname("tokena"); cryptotoken tokenb = manager.gettokenbyname("tokenb"); // create an rsa keypairgenerator using tokena manager.setthreadtoken(tokena); keypairgenerator rsakpg = keypairgenerator.g...
...dsakpg.initialize(1024); keypair dsapair = dsakpg.generatekeypair(); supported classes cipher dsaprivatekey dsapublickey keyfactory keygenerator keypairgenerator mac messagedigest rsaprivatekey rsapublickey secretkeyfactory secretkey securerandom signature what's not supported the following classes don't work very well: keystore: there are many serious problems mapping the jca keystore interface onto nss's model of pkcs #11 modules.
...And 4 more matches
Mozilla-JSS JCA Provider notes
apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension.
...the following example shows how you can specify which token is used for various jca operations: // lookup pkcs #11 tokens cryptomanager manager = cryptomanager.getinstance(); cryptotoken tokena = manager.gettokenbyname("tokena"); cryptotoken tokenb = manager.gettokenbyname("tokenb"); // create an rsa keypairgenerator using tokena manager.setthreadtoken(tokena); keypairgenerator rsakpg = keypairgenerator.getin...
...dsakpg.initialize(1024); keypair dsapair = dsakpg.generatekeypair(); supported classes cipher dsaprivatekey dsapublickey keyfactory keygenerator keypairgenerator mac messagedigest rsaprivatekey rsapublickey secretkeyfactory secretkey securerandom signature cipher supported algorithms notes aes des desede (des3) rc2 rc4 rsa the following modes and padding schemes are supported: algorithm mode padding des ecb nopadding cbc nopadding pkcs5 padding desede des3 ecb nopadding cbc nopadding pkcs5 padding ...
...And 4 more matches
Rhino Debugger
controlling execution the debugger provides the following facilities for you to control the execution of scripts you are debugging: step into to single step entering any function calls, you may do any of the following: select the debug->step into menu item on the menu bar press the step into button on the toolbar press the f11 key on the keyboard execution will resume.
... step over to single step to the next line in the current function, you may do any of the following: select the debug->step over menu item on the menu bar press the step over button on the toolbar press the f7 key on the keyboard execution will resume but control will return to the debugger at the next line in the current function or top-level script.
... step out to continue execution until the current function returns you may do any of the following: select the debug->step out menu item on the menu bar press the step out button on the toolbar press the f8 key on the keyboard execution will resume until the current function returns or a breakpoint is hit.
...And 4 more matches
JSAPI reference
reporterrorflagsandnumber js_reporterrorflagsandnumberuc js_reporterrornumberucarray added in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_geterrorreporter js_seterrorreporterobsolete since jsapi 52 js_errorfromexception js_geterrorprototype jsreport_is_exception jsreport_is_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript exceptions: js::createerror added in spidermonkey 38 js_isexceptionpending js_getpendingexception js_setpendingexception js_clearpendingexception js_throwstopiteration added in spidermonkey 1.8 js_isstopiteration added in spidermonkey 31 typedef jsexceptionstate js_saveexceptionstate js_restoreexceptionstate js_dropexce...
...spidermonkey 38 js::falsehandlevalue added in spidermonkey 38 jsval constants: jsval_null obsolete since jsapi 42 jsval_void obsolete since jsapi 42 jsval_true obsolete since jsapi 42 jsval_false obsolete since jsapi 42 jsval_zero obsolete since jsapi 42 jsval_one obsolete since jsapi 42 function and macros for checking the type of a jsval: enum jstype js_typeofvalue all of the following are deprecated.
... js_convertarguments obsolete since jsapi 38 js_convertargumentsva obsolete since jsapi 38 js_pusharguments obsolete since javascript 1.8.5 js_pushargumentsva obsolete since javascript 1.8.5 js_poparguments obsolete since javascript 1.8.5 js_addargumentformatter obsolete since jsapi 18 js_removeargumentformatter obsolete since jsapi 18 the following functions convert js values to various types.
...And 4 more matches
Starting WebLock
xxx what is example 2?following example 2, you change the class definition to support the nsiobserver interface and change ns_impl_isupports1 so that the queryinterface implementation knows that the component also supports nsiobserver.
... in short, to register the weblock component as an xpcom-startup observer, do the following: char* previous = nsnull; rv = catman->addcategoryentry("xpcom-startup", "weblock", weblock_contractid, pr_true, // persist category pr_true, // replace existing &previous); if (previous) nsmemory::free(previous); // free the memory the replace...
... in general, the weblock service interface needs to include the following functionality: lock - enable web locking so that any browser in the gecko application is restricted to the white list of website domains.
...And 4 more matches
Using XPCOM Utilities to Make Things Easier
though they overlap somewhat (e.g., high-level macros expand to other macros), they fall into the following general categories.
...the four required parts[other-parts] of the structure contain the following information: a human readable class name the class id (cid) the contract id (an optional but recommended argument) a constructor for the given object static const nsmodulecomponentinfo components[] = { { "pretty class name", cid, contract_id, constructor }, // ...
...many cids take the following form: #define ns_ioservice_cid \ { /* 9ac9e770-18bc-11d3-9337-00104ba0fd40 */ \ 0x9ac9e770, \ 0x18bc, \ 0x11d3, \ {0x93, 0x37, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \ } the next entry is the contract id string, which is also us...
...And 4 more matches
Plug-in Development Overview - Plugins
a basic overview of the plug-in development process is given in the following steps.
...the following sections describe platform-specific discovery and registration: ms windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins.
... for this the version stamp of the embedded resource of the plug-in dll should contain the following set of string/value pairs: mimetype: for mime types fileextents: for file extensions fileopenname: for file open template productname: for plug-in name filedescription: for description language: for language in use in the mime types and file extensions strings, multiple values are separated by the "|" character, for example: video/quicktime|audio/aiff|image/jpeg the version stamp ...
...And 4 more matches
Network request details - Firefox Developer Tools
the tabs at the top of this pane enable you to switch between the following pages: headers messages (only for websocket items) cookies params response cache timings security (only for secure pages) stack trace (only when the request has a stack trace, e.g.
... request information the following information is shown only when the section is expanded: scheme: the scheme used in the url host: the server involved in the request filename: the full path to the file requested address: the ip address of the host the following information is shown in both the collapsed and the expanded states: status: the http response code for the request.
...the full list of cookie attributes is shown—see the following screenshot showing response cookies with further attributes shown.
...And 4 more matches
Web Console remoting - Firefox Developer Tools
when page navigation starts the following packet is sent from the tab actor: { "from": tabactor, "type": "tabnavigated", "state": "start", "url": newurl, "nativeconsoleapi": true } the nativeconsoleapi property tells if the window.console object is native or not for the top level window object for the given tab - this is always true when navigation starts.
... when navigation stops the following packet is sent: { "from": tabactor, "type": "tabnavigated", "state": "stop", "url": newurl, "title": newtitle, "nativeconsoleapi": true|false } getcachedmessages(types, onresponse) the webconsoleclient.getcachedmessages(types, onresponse) method sends the following packet to the server: { "to": "conn0.console9", "type": "getcachedmessages", "messagetypes": [ "pageerror", "consoleapi" ] } the getcachedmessages packet allows one to retrieve the cached messages from before the web console was open.
...these will be explained in the following sections of this document.
...And 4 more matches
DirectoryEntrySync - Web APIs
the following creates an empty file called seekrits.txt in the root directory.
...the following creates a new directory called superseekrit in the root directory.
... parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist.
...And 4 more matches
Introduction to the DOM - Web APIs
your dom programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated dom methods to actually create new content, as in the longer example below.
... this following javascript will display an alert when the document is loaded (and when the whole dom is available for use): <body onload="window.alert('welcome to my home page!');"> another example.
... the following table briefly describes these data types.
...And 4 more matches
IDBObjectStoreSync - Web APIs
any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this method can raise a idbdatabaseexception with the following codes: value the value to store into the index.
... exceptions this method can raise a idbdatabaseexception with the following codes: serial_err if the data being stored could not be deserialized by the internal structured cloning algorithm.
... exceptions this method can raise a databaseexception with the following code: not_found_err if no records exist in this index for the requested key range.
...And 4 more matches
Basic concepts - Web APIs
you'll find the following useful: for an overview of the design and structure of indexeddb, see big concepts.
...so keep the following important concepts in mind: indexeddb databases store key-value pairs.
...each database must have the following: name.
...And 4 more matches
Using IndexedDB - Web APIs
basic pattern the basic pattern that indexeddb encourages is the following: open a database.
... creating and structuring the store using an experimental version of indexeddb in case you want to test your code in browsers that still use a prefix, you can use the following code: // in the following line, you should include the prefixes of implementations you want to test.
...idbtransaction || {read_write: "readwrite"}; // this line should only be needed if it is needed to support the object's constants for older browsers window.idbkeyrange = window.idbkeyrange || window.webkitidbkeyrange || window.msidbkeyrange; // (mozilla has never prefixed these objects, so we don't need window.mozidb*) beware that implementations that use a prefix may be buggy, or incomplete, or following an old version of the specification.
...And 4 more matches
Variable fonts guide - CSS: Cascading Style Sheets
this can generally be resolved fairly easily, but does require an extra step in writing your css: font-weight: 375; font-variation-settings: 'wght' 375; the following live example's css can be edited to allow you to play with font weight values.
... font-stretch: 115%; font-variation-settings: 'wdth' 115; the following live example's css can be edited to allow you to play with font width values.
... font-style: italic; font-variation-settings: 'ital' 1; font-synthesis: none; the following live example's css can be edited to allow you to play with font italics.
...And 4 more matches
CSS values and units - CSS: Cascading Style Sheets
when viewing css property value syntax in a css specification or the mdn property page, allowable keywords will be listed in the following form.
... the following values are the pre-defined keyword values allowed for float.
...for example, if you wanted to include a background image, you might use either of the following.
...And 4 more matches
Using media queries - CSS: Cascading Style Sheets
media queries are used for the following: to conditionally apply styles with the css @media and @import at-rules.
...for example, the styles nested inside the following query will never be used, because no speech-only device has a screen aspect ratio: @media speech and (aspect-ratio: 11/5) { ...
...for instance, the following rule will apply its styles if the user's device has either a minimum height of 680px or is a screen device in portrait mode: @media (min-height: 680px), screen and (orientation: portrait) { ...
...And 4 more matches
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, search field inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid pattern a regular expression the input's...
... spellcheck non-standard attributes the following non-standard attributes are available to search input fields.
...the following screenshot comes from chrome: in addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain.
...And 4 more matches
HTTP Public Key Pinning (HPKP) - HTTP
the following commands will help you extract the base64 encoded information from a key file, a certificate signing request, or a certificate.
...4 openssl ec -in my-ecc-key-file.key -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64 openssl req -in my-signing-request.csr -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 openssl x509 -in my-certificate.crt -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 the following command will extract the base64 encoded information for a website.
... apache adding a line similar to the following to your webserver's config will enable hpkp on your apache.
...And 4 more matches
Array.prototype.forEach() - JavaScript
the following example illustrates an alternative approach, using foreach().
... the following code logs a line for each element in an array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element) } // notice that index 2 is skipped, since there is no item at // that position in the array...
... [2, 5, , 9].foreach(logarrayelements) // logs: // a[0] = 2 // a[1] = 5 // a[3] = 9 using thisarg the following (contrived) example updates an object's properties from each entry in the array: function counter() { this.sum = 0 this.count = 0 } counter.prototype.add = function(array) { array.foreach((entry) => { this.sum += entry ++this.count }, this) // ^---- note } const obj = new counter() obj.add([2, 5, 9]) obj.count // 3 obj.sum // 16 since the thisarg parameter (this) is provided to foreach(), it is passed to callback each time it's invoked.
...And 4 more matches
stroke-linejoin - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following nine elements: <altglyph>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="0 0 18 12" xmlns="http://www.w3.org/2000/svg"> <!-- upper left path: effect of the "miter" value --> <path d="m1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="black" fill="none" stroke-linejoin="miter" /> <!-- center path: effect of the "round" value --> <path d="m7,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" ...
... --> <path d="m9,11 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="black" fill="none" stroke-linejoin="arcs" /> <!-- the following pink lines highlight the position of the path for each stroke --> <g id="highlight"> <path d="m1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="pink" fill="none" stroke-width="0.025" /> <circle cx="1" cy="5" r="0.05" fill="pink" /> <circle cx="3" cy="2" r="0.05" fill="pink" /> <circle cx="5" cy="5.5" r="0.05" fill="pink" /> </g> <use xlink:href="#highlight" x=...
... example html,body,svg { height:100% } <svg viewbox="0 0 6 6" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "arcs" value --> <path d="m1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3" stroke="black" fill="none" stroke-linejoin="arcs" /> <!-- the following pink lines highlight the position of the path for each stroke --> <g id="p"> <path d="m1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3" stroke="pink" fill="none" stroke-width="0.025" /> <circle cx="1" cy="5" r="0.05" fill="pink" /> <circle cx="3" cy="2" r="0.05" fill="pink" /> <circle cx="5" cy="5" r="0.05" fill="pink" /> </g> </svg> bevel the bevel value indicates that a...
...And 4 more matches
Understanding WebAssembly text format - WebAssembly
all code in a webassembly module is grouped into functions, which have the following pseudo-code structure: ( func <signature> <locals> <body> ) the signature declares what the function takes (parameters) and returns (return values).
... so given the following function: (func (param i32) (param f32) (local f64) local.get 0 local.get 1 local.get 2) the instruction local.get 0 would get the i32 parameter, local.get 1 would get the f32 parameter, and local.get 2 would get the f64 local.
...so for example, after executing the following function: (func (param $p i32) (result i32) local.get $p local.get $p i32.add) the stack contains exactly one i32 value — the result of the expression ($p + $p), which is handled by i32.add.
...And 4 more matches
Using the WebAssembly JavaScript API - WebAssembly
create a <script></script> element in your html file, and add the following code to it: var importobject = { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources.
... add the following to your script, below the first block: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the net result of this is that we call our exported webassembly function exported_func, which in turn calls our imported javascript function imported_func, which logs the value provided inside the webassembly instance (42) to the console...
... now add the following line to the top of your script, to create a memory instance: var memory = new webassembly.memory({initial:10, maximum:100}); the unit of initial and maximum is webassembly pages — these are fixed to 64kb in size.
...And 4 more matches
page-mod - Archive of obsolete content
for example, the following add-on displays an alert whenever the user visits any page hosted at "mozilla.org": var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscript: 'window.alert("page matches ruleset");' }); you can modify the document in your script: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscript: 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";' }); you can supply t...
... for example, the following add-on retrieves the html content of specific tags from documents that match the pattern.
... the following add-on creates a button which, when clicked, highlights all the div elements in the document loaded into the active tab: require("sdk/ui/button/action").actionbutton({ id: "highlight-divs", label: "highlight divs", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscript: 'var divs = document.getelementsbytagname("div");' + ...
...And 3 more matches
Canvas code snippets - Archive of obsolete content
code usable from web content getting the number of pixels of a certain color in a canvas the following function will return the number of pixels in a canvas that have the rgb color of r, g and b.
...as, r, g, b) { var cx = canvas.getcontext('2d'); var pixels = cx.getimagedata(0, 0, canvas.width, canvas.height); var all = pixels.data.length; var amount = 0; for (i = 0; i < all; i += 4) { if (pixels.data[i] === r && pixels.data[i + 1] === g && pixels.data[i + 2] === b) { amount++; } } return amount; }; getting the color of a pixel in a canvas this following snippet returns an object with the rgba values of the pixel at position x and y of the canvas.
...'clearrect', 'clip', 'closepath', 'drawimage', 'fill', 'fillrect', 'filltext', 'lineto', 'moveto', 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transform', 'translate']; var gettermethods = ['createpattern', 'drawfocusring', 'ispointinpath', 'measuretext', // drawfocusring not currently supported // the following might instead be wrapped to be able to chain their child objects 'createimagedata', 'createlineargradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap', 'linejoin', 'linewidth', 'miterlimit', 'shadowoffsetx', 'shadowoffsety', 'shadowblur', 'shadowcolor', 'strokestyle...
...And 3 more matches
Preferences - Archive of obsolete content
here are the idl definitions: void getcomplexvalue(in string aprefname, in nsiidref atype, [iid_is(atype), retval] out nsqiresult avalue); void setcomplexvalue(in string aprefname, in nsiidref atype, in nsisupports avalue); as you can see, both of them take a parameter, atype, which can have one of the following values (to be precise, you should pass components.interfaces.nsiwhatever instead of just nsiwhatever, which is undefined).
...you should do the following: add this line to some .properties file (for all of your locales), say to chrome://myext/locale/defaults.properties: extensions.myext.welcomemessage=localized default value add the default value for extensions.myext.welcomemessage, pointing to that properties file, by adding the following line to your file with default preferences (see below).
... the effect of default preferences on get methods when one of the get methods of nsiprefbranch (assuming it's a branch of the tree with current values) is called, it does the following: checks whether the current tree has a value for the preference and whether or not the preference is locked.
...And 3 more matches
StringView - Archive of obsolete content
47 : 65; }; /* base64 string to array encoding */ stringview.bytestobase64 = function (abytes) { var eqlen = (3 - (abytes.length % 3)) % 3, sb64enc = ""; for (var nmod3, nlen = abytes.length, nuint24 = 0, nidx = 0; nidx < nlen; nidx++) { nmod3 = nidx % 3; /* uncomment the following line in order to split the output in lines 76-character long: */ /* if (nidx > 0 && (nidx * 4 / 3) % 76 === 0) { sb64enc += "\r\n"; } */ nuint24 |= abytes[nidx] << (16 >>> nmod3 & 24); if (nmod3 === 2 || abytes.length - nidx === 1) { sb64enc += string.fromcharcode(stringview.uint6tob64(nuint24 >>> 18 & 63), stringview.uint6tob64(nuint24 >>> 12 & 63), stringview.uint6tob6...
...the following table shows the behavior of the stringview constructor.
...if you want to build a custom cycle through a variable-length-encoded stringview (utf-8, utf-16), you can use a code like the following, which does not make use of stringview.foreachchar().
...And 3 more matches
Promises - Archive of obsolete content
the following page contains examples of many promise-based replacement apis for common operations.
... the following examples make use of the task api, which harnesses generator functions to remove some of the syntactic clutter of raw promises, such that asynchronous promise code more closely resembles synchronous, procedural code.
... a task example like the following: components.utils.import("resource://gre/modules/task.jsm"); task.spawn(function* () { var response = yield request("login", { username: user, password: password }); if (response.messages) { try { yield publish({ username: user, messages: response.messages }); } catch (e) { self.reporterror("publication failed", e); } } }); can be converted to a pure promise-based equivalent as such: request("login", { username: user, password: password }) .then(response => { if (response.messages) return publish({ username: user, messages: response.messages }); }) .then(null, (e) => { self.reporterror("publication failed", e); }); file io file io in add-ons should...
...And 3 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
_ldap_xpcom= +moz_ldap_xpcom=1 moz_mail_news= moz_mork=1 moz_morkreader= and set --enable-extensions=pref in mozconfig file, in fedora source rpm it is: [root@b008-02 sources]# grep enable-extensions /root/rpmbuild/sources/thunderbird-mozconfig ac_add_options --enable-extensions=pref it seems worse this time , as even after applying those compilation options mentioned above, i now get the following error message while stating thunderbird with autoconfig (autoconf.js having pref('general.config.filename','thunderbird.cfg'); ) and thunderbird.cfg calling getldap* functions to retrieve cn and mail address of the current user.
... the displayerror() function does not work properly in thunderbird 3.1: see https://bugzilla.mozilla.org/show_bu...?id=502597#c34 a usable workaround is placing the following code at the top of your autoconfig script: // enable logging.
... 2 10:45 thunderbird -> /usr/local/thunderbirddebuglibs/thunderbird-3.0b3pre/thunderbird [root@b008-02 thunderbirddebuglibs]# find /usr/local/thunderbirddebuglibs/ -name prefcalls.js /usr/local/thunderbirddebuglibs/thunderbird-3.0b3pre/defaults/autoconfig/prefcalls.js old mozilla 1.x, possibly netscape 6/7 the following is for the record...
...And 3 more matches
JavaScript crypto - Archive of obsolete content
web sites which use ssl clientauth login could use the following code to refresh the page on token insertions and removals: <!doctype html> <p>...
...e the ca's enrollment page could look something like this: <!doctype html> <h2>request a cert</h2> <form name="reqform" method="post" action="http://your.ra.site.org"> <p><input type=hidden name=cert_request value=""> <p>name: <input type=text name=name value=""> <p>password: <input type=password name="password" value=""> <p><input type=submit name="send" value="submit"> </form> <script> /* the following values could be filled in by the server cgi */ var authenticator = "server_magic"; var keytransportcert = null; var crmfobject = null; var form = document.forms[0]; function validate() { // generate keys for nsm.
...st() { form.cert_request.value = crmfobject.request; form.submit(); } form.onsubmit = validate; </script> on completion of the request, the ca may submit a page that looks something like this: <!doctype html> <h2>certificate request successful</h2> <p>hit 'load' to load your certificate</p> <form name="reqform"> <p><input type=submit name="load" value="submit"></p> </form> <script> /* the following values could be filled in by the server cgi */ var nickname= "mycertnickname"; var cert = "mkjflakdjfiwjflaksufklasf ..."; var forcebackup = false; function loadcertificate() { window.crypto.importusercertificates(nickname, cert, forcebackup); return false; } document.forms[0].onsubmit = loadcertificate; </script> signing text domstring signtext(domstring stringtosign, ...
...And 3 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
first, a quick scan of the contents of the xpi file (which you can open using with any unzip utility) reveals the following high-level directory structure: install.js bin\ chrome\ components defaults\ icons\ plugins\ res\ note that this high-level structure parallels the directory structure of the installed browser very closely: as you will see in the installation script, the contents of the archive are installed onto the file system in much the same way that they are stored in the archive itself, th...
... most installation scripts, including the one discussed here, take the following basic form (in pseudo-code and with links to the sections in which these installation steps are documented): initinstall(); if (verify_space()) { err = add_dirs_and_files; register_files; if (err==success) { performinstall() }; else { cancelinstall() }; } as you can see in the code listing, the verification process at the top is on lines 1 to 18; the file addition process, here part of the main installation blo...
... the initinstall method takes the following parameters: the display name of the package, the name of the package as it appears in the client registry, and the version, which can be expressed as a number or as an installversion object.
...And 3 more matches
Result Generation - Archive of obsolete content
to navigate around, you could start at node a and navigate around the graph following the arrows to b, c or d.
...you could navigate to b, c and d and generate three blocks of output by following the arrows forward.
... or, you could start at d and follow two arrows back (and only following arrows backwards).
...And 3 more matches
Advanced Rules - Archive of obsolete content
the syntax of the content element is as follows: <content uri="?var"/> the question mark indicates that the text following it is a variable.
...let's say you have a list of cities described in the following rdf/xml fragment: <rdf:seq about="http://www.xulplanet.com/rdf/weather/cities"> <rdf:li resource="http://www.xulplanet.com/rdf/weather/city/paris"/> <rdf:li resource="http://www.xulplanet.com/rdf/weather/city/manchester"/> <rdf:li resource="http://www.xulplanet.com/rdf/weather/city/melbourne"/> <rdf:li resource="http://www.xulplanet.com/rdf/weather/city/kiev"/> </rdf:seq> <rdf:description about="http://www.xulplanet.com/rdf/w...
...to do this, use the member element as in the following: <tree id="citiestree" datasources="weather.rdf" ref="http://www.xulplanet.com/rdf/weather/cities"> <template> <rule> <conditions> <content uri="?list"/> <member container="?list" child="?city"/> </conditions> <rule> <template> </tree> the template builder starts by grabbing the value of the ref attribute, which in this case is http://www.xulplanet.com/rdf/weather/cities.
...And 3 more matches
XULRunner tips - Archive of obsolete content
the following prefs must also be set to make the xpinstall dialog, extension manager, and theme manager work: pref("xpinstall.dialog.confirm", "chrome://mozapps/content/xpinstall/xpinstallconfirm.xul"); pref("xpinstall.dialog.progress.skin", "chrome://mozapps/content/extensions/extensions.xul?type=themes"); pref("xpinstall.dialog.progress.chrome", "chrome://mozapps/content/extensions/extensions.xul?type=exten...
... save the dom_inspector-*.xpi package to a temporary directory unzip the package copy the following files: chrome/inspector.jar to the chrome directory of your xulrunner application components/inspector-cmdline.js to your components directory defaults/preferences/inspector.js to your preferences directory open your chrome.manifest file and add these lines: content inspector jar:inspector.jar!/content/inspector/ xpcnativewrappers=no locale inspector en...
...p the package." create a file in the extensions directory of your application with the same name as the dom inspector id (inspector@mozilla.org) containing one line of text -- the exact path to the root directory of dom inspector (where the install.rdf is) like this one: /home/username/.mozilla/firefox/numbersandletters/extensions/inspector@mozilla.org/ now create a javascript file with the following code and include it in the main window of your application: function startdomi() { // load the window datasource so that browser windows opened subsequent to dom // inspector show up in the dom inspector's window list.
...And 3 more matches
Mozilla's DOCTYPE sniffing - Archive of obsolete content
the goals that led to choosing this behavior were the following: almost all existing text/html pages on the web that need to be in quirks mode to be displayed correctly should be displayed using quirks mode.
... (almost all, rather than all, to allow for the following points as well.) authors writing web pages to current standards should be able to trigger strict mode.
... full standards mode the following trigger full standards mode: any document sent with an xml mime type such as text/xml, application/xml, or application/xhtml+xml (since sniffing only occurs for documents sent as text/html).
...And 3 more matches
Building up a basic demo with Babylon.js - Game development
add the following code to the bottom of your second <script> element: var engine = new babylon.engine(canvas); the babylon global object contains all the babylon.js functions available in the engine.
...let's create a scene by adding the following lines just below our previous code: var scene = new babylon.scene(engine); scene.clearcolor = new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray.
...add the following line below your camera definition: var light = new babylon.pointlight("light", new babylon.vector3(10, 10, 0), scene); the parameters are very similar to the previously defined camera: the name of the light, a position in 3d space and the scene to which the light is added.
...And 3 more matches
Grids - Learn web development
the following video provides a nice visual explanation of using css grid: defining a grid as a starting point, download and open the starting point file in your text editor and browser (you can also see it live here).
... change your track listing to the following definition, creating three 1fr tracks.
...change your track listing to the following: .container { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px; } you will now get 3 1fr tracks just as before.
...And 3 more matches
Introduction to CSS layout - Learn web development
our examples will all feature the same html, which is as follows: <h1>positioning</h1> <p>i am a basic block level element.</p> <p class="positioned">i am a basic block level element.</p> <p>i am a basic block level element.</p> this html will be styled by default using the following css: body { width: 500px; margin: 0 auto; } p { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); padding: 10px; margin: 10px; border-radius: 5px; } the rendered output is as follows: relative positioning relative positioning allows you to offset an item from the position in normal flow it would have by default.
...to do this, we could add the following rule to add relative positioning: .positioned { position: relative; top: 30px; left: 30px; } here we give our middle paragraph a position value of relative — this doesn't do anything on its own, so we also add top and left properties.
... adding this code will give the following result: relative positioning example <h1>relative positioning</h1> <p>i am a basic block level element.</p> <p class="positioned">this is my relatively positioned element.</p> <p>i am a basic block level element.</p> body { width: 500px; margin: 0 auto; } p { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); padding: 10px; margin: 10px; border-radius: 5px; } .positioned { position: relative; background: rgba(255,84,104,.3); border: 2px solid rgb(2...
...And 3 more matches
Positioning - Learn web development
</p> now add the following rule to the bottom of your css: .positioned { position: static; background: yellow; } if you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph.
...to try this out, add the following declarations to the .positioned rule in your css: top: 30px; left: 30px; note: the values of these properties can take any units you'd logically expect — pixels, mm, rems, %, etc.
...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.
...And 3 more matches
Getting started with HTML - Learn web development
for example, consider the following line of text: my cat is very grumpy if we wanted the text to stand by itself, we could specify that it is a paragraph by enclosing it in a paragraph (<p>) element: <p>my cat is very grumpy</p> note: tags in html are case-insensitive.
... the following is an example of the wrong way to do nesting: <p>my cat is <strong>very grumpy.</p></strong> the tags have to open and close in a way that they are inside or outside one another.
...a block-level element appears on a new line following the content that precedes it.
...And 3 more matches
HTML table basics - Learn web development
LearnHTMLTablesBasics
add the following inside your table tags: <td>hi, i'm your first cell.</td> if we want a row of four cells, we need to copy these tags three times.
... this should result in a table that looks something like the following: hi, i'm your first cell.
...to illustrate why they are useful, have a look at the following table example.
...And 3 more matches
Index - Learn web development
accessibility, beginner, html, learn, needscontent the following content describes specific features of html that can be used to make a web page more accessible to people with different disabilities.
... for example, take the following line of content: 40 how the web works beginner, client, dns, http, ip, infrastructure, learn, server, tcp, l10n:priority this theory is not essential to writing web code in the short term, but before long you'll really start to benefit from understanding what's happening in the background.
... 101 solve common problems in your javascript code beginner, javascript, learn the following links point to solutions to common problems you may encounter when writing javascript.
...And 3 more matches
Inheritance in JavaScript - Learn web development
defining a teacher() constructor function the first thing we need to do is create a teacher() constructor — add the following below the existing code: function teacher(first, last, age, gender, interests, subject) { person.call(this, first, last, age, gender, interests); this.subject = subject; } this looks similar to the person constructor in many ways, but there is something strange here that we've not seen before — the call() function.
... add the following line below your previous addition: teacher.prototype = object.create(person.prototype); here our friend create() comes to the rescue again.
...you can do so by going back to your source code and adding the following line at the bottom: object.defineproperty(teacher.prototype, 'constructor', { value: teacher, enumerable: false, // so that it does not appear in 'for in' loop writable: true }); now if you save and refresh, entering teacher.prototype.constructor should return teacher(), as desired, plus we are now inheriting from person()!
...And 3 more matches
Object prototypes - Learn web development
you can check out existing prototype properties for yourself — go back to our previous example and try entering the following into the javascript console: person.prototype the output won't show you very much because we haven't defined anything on our custom constructor's prototype!
...now try the following: object.prototype you'll see a large number of methods defined on object's prototype property, which are then available on objects that inherit from object, as shown earlier.
...you can check this by entering the following in the console: person2.__proto__ this will return the person1 object.
...And 3 more matches
Implementing feature detection - Learn web development
therefore, you can detect whether the browser supports geolocation or not by using something like the following: if ("geolocation" in navigator) { navigator.geolocation.getcurrentposition(function(position) { // show the location on a map, perhaps using the google maps api }); } else { // give the user a choice of static maps instead perhaps } it is probably better to use an established feature detection library however, rather than writing your own all the time.
...download the latest version (see manual installation), unzip the zip file, copy the html5shiv-printshiv.min.js and html5shiv.min.js files into your example directory, and link to one of the files by putting the following under your <title> element: <script src="html5shiv.min.js"></script> have a look at your example css files — you'll see that basic-styling.css handles all the styling that we want to give to every browser, whereas the other two css files contain the css we want to selectively apply to browser depending on their support levels.
... give it the following contents: const conditional = document.queryselector('.conditional'); const testelem = document.createelement('div'); if (testelem.style.flex !== undefined && testelem.style.flexflow !== undefined) { conditional.setattribute('href', 'flex-layout.css'); } else { conditional.setattribute('href', 'float-layout.css'); } here we are grabbing a reference to the second <link> element, and crea...
...And 3 more matches
Handling common JavaScript problems - Learn web development
for example, the following command installs jshint: npm install -g jshint you can then point these tools at javascript files you want to lint, for example: you can also use these tools with a task runner/build tool such as gulp or webpack to automatically lint your javascript during development.
...this is supposed to be fetched from an external .json file using the following xmlhttprequest call: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new xmlhttprequest(); request.open('get', requesturl); request.send(); let superheroes = request.response; populateheader(superheroes); showheroes(superheroes); but this fails.
... try inserting the following line just below line 31 (bolded above): console.log('response value: ' + superheroes); refresh the page in the browser, and you will get an output in the console of "response value:", plus the same error message we saw before the console.log() output shows that the superheroes object doesn't appear to contain anything.
...And 3 more matches
How Mozilla's build system works
when config.status runs, you'll see the following output: reticulating splines...
... to view information about the tiers, you can execute the following special make targets: command effect make echo-tiers show the final list of tiers.
...moz.build files are limited to performing the following actions: calling functions that are explicitly made available to the moz.build environment.
...And 3 more matches
Eclipse CDT
set an initial heap space of 1 gb and max heap space of 5 gb, say, by modifying the values of the following two lines in eclipse.ini: -xms1g -xmx5g if you fail to increase these limits, then you will likely find that eclipse either hangs when it tries to index the mozilla source or else that the code intelligence is very broken after the indexing "completes".
...it also used to be necessary to add the following two lines to your mozconfig to make the compiler output errors all on a single line, but that may not be needed anymore: export cflags="-fmessage-length=0" export cppflags="-fmessage-length=0" debugging to create a debug configuration, open the project properties window, and select "run/debug settings" on the left.
...this define is in nsdomclassinfoid.h, which is included via the following include chain: content/svg/content/src/nssvgellipseelement.cpp content/svg/content/src/nssvgpathgeometryelement.h content/svg/content/src/nssvggraphicelement.h content/svg/content/src/nssvgstylableelement.h content/svg/content/src/nssvgelement.h content/base/src/nsgenericelement.h obj-debug/dist/include/nsdomclassinfoid.h in nsdomclassinfoid.h the ns_dom_interface_map_entr...
...And 3 more matches
Getting Started with Chat
you will need to use the following information to configure the server connection: server: irc.mozilla.org port: 6667 (default) or 6697 (ssl) desktop clients desktop clients tens to allow the most detailed configuration.
...the following are some other options available to you: windows mac linux colloquy ● irssi ● ● ●* xchat ● ○ ● key: ● — binary or executable program available ○ — only available by downloading and compiling source code ●* — binary or executable may be available.
... commands the following is a list of commands you should be familiar with.
...And 3 more matches
Extending a Protocol
creating the protocol pecho.ipdl let's start by saving the following file to ./dom/ipc/pecho.ipdl.
... we need to add the following things: at the top of the file: include protocol pecho; after "manager pbrowser or pinprocess;", add: manages pecho; finally, under parent: add async pecho(); - this is the "constructor" part we talked about before, which will allow us to eventually send messages.
... defining windowglobalparent's alloc/deallocpechoparent() open up dom/ipc/windowglobalparent.h and we are going to add two things: at the top, add #include "mozilla/dom/echoparent.h" and then, as part of the windowglobalparent class definition, add the following two public methods: already_addrefed<echoparent> allocpechoparent(); bool deallocpechoparent(pechoparent* aactor); natrually, we will have to do the alloc/dealloc dance for the children too.
...And 3 more matches
IPDL Tutorial
the following ipdl code defines a very basic interaction of browser and plugin actors: async protocol pplugin { child: async init(nscstring pluginpath); async shutdown(); parent: async ready(); }; this code declares the pplugin protocol.
...the following artificial example shows how these specifiers are used and how these specifiers change the generated abstract actor classes.
... using struct mozilla::void_t from "ipc/ipcmessageutils.h"; union variant { void_t; bool; int; double; nscstring; ppluginscriptableobject; }; this union generates a c++ interface which includes the following: struct variant { enum type { tvoid_t, tbool, tint, tdouble, tnscstring, tpplugionscriptableobject }; type type(); void_t& get_void_t(); bool& get_bool(); int& get_int(); double& get_double(); nscstring& get_nscstring(); ppluginscriptableobject* get_ppluginscriptableobject(); }; aunion.type() can be used to determine the type of a union received in an ipdl message handler...
...And 3 more matches
gettext
consider the following code snippet: <?php $num = 1; printf(ngettext("%d user likes this.", "%d users like this.", $num), $num); ?> depending on the value of the $num variable, this code will either use the singular ("user likes) or the plural ("users like") form of the string.
...for english, the above code will produce the following output: 1 user likes this.
...for example, for english, the plural rule is of the following form: plural-forms: nplurals=2; plural=n != 1; the first part defines the number of different plural forms (2).
...And 3 more matches
Mozilla DOM Hacking Guide
as an example, on the window object, we can call all the methods defined on the following interfaces: nsidomwindow, nsidomjswindow, nsidomeventreciever, nsidomeventtarget, nsidomviewcss, and nsidomabstractview.
...for example, the html "area" element has the following interfaces in its flattened set: nsidomhtmlareaelement and nsidomnshtmlareaelement.
...the problem is the following: we have to add a new htmldomimplementation interface to the domimplementation dom object.
...And 3 more matches
DMD
for example, from javascript code you can do the following.
...with the following command.
...which processes get logged is controlled by the moz_dmd_log_process environment variable, which can take the following values.
...And 3 more matches
L20n Javascript API
ctx.registerlocalenegotiator(function(available, requested, deflocale) { return intl.prioritizelocales(available, requested, deflocale); }); negotiator is a function which takes the following arguments: available - all locales available to the context instance, requested - locales preferred by the user, deflocale - the default locale to be used as the ultimate fallback, callback - the function to call when the negotiation completes (useful for asynchronous negotiators).
... ctx.requestlocales('pl'); if registerlocales hasn't been called, the special i-default locale is used, which means that the following minimal code is valid and will result in a fully operational context instance.
...the error object is passed as the first argument to callback and can be one of the following: context.error, when there are problems with setting up resources (e.g.
...And 3 more matches
NSS Certificate Download Specification
the content field is the following asn.1 structure: certificatesequence ::= sequence of certificate see the section below on certificate chains for more information about how multiple certificates are handled.
...the text form begins with the following line: -----begin certificate----- following this line should be the certificate data, which can be in any of the binary formats described above.
...following the data should be the following line: -----end certificate----- in a text format download, nss ignores any text before the first begin certificate line, and ignores any text after the first end certificate line.
...And 3 more matches
Introduction to Network Security Services
so the nss library has the following forms: libnss3.so - unix shared library libnss3.sl - hp-ux shared library libnss.a - unix static library nss3.dll - windows shared library nss3.lib - windows import library binding to nss3.dll nss.lib - windows static library nss, ssl, and s/mime have all of the above forms.
... the following static libaries aren't included in any shared libraries libcrmf.a/crmf.lib provides an api for crmf operations.
... the following static libaries are included only in external loadable pkcs #11 modules: libnssckfw.a/nssckfw.lib provides an api for writing pkcs #11 modules.
...And 3 more matches
NSS API Guidelines
function typedefs should have the following format: layerbody(), with the same definitions for layer as public functions, and body is camel case english words.
... the arena_threadmark preprocessor definition (default in debug builds), and code it encloses, will add some checking for the following situation: thread a marks the arena, and allocates some memory from it.
...(frees are allowed.) the arena_destructor_list preprocessor definition, and the code it encloses, are an effort to make the following work together: arenas, letting you allocate stuff and then removing them all at once lazy creation of pure-memory objects from asn.1 blobs, for example use of nsspkixcertificate doesn't drag all the code in for all constituent objects, unless they're actually being used our agressive pointer-tracking facility all these are useful, but they don't combine well.
...And 3 more matches
NSS Tools certutil
syntax to run the certificate database tool, type the command certutil option [arguments ] where options and arguments are combinations of the options and arguments listed in the following section.
...in each category position use zero or more of the following attribute codes: p prohibited (explicitly distrusted) p trusted peer c valid ca t trusted ca to issue client certificates (implies c) c trusted ca to issue server certificates (ssl only) (implies c) u certificate can be used for authentication or signing w send warning (use with other attributes to include a warning when the certi...
...the contexts are the following: c (as an ssl client) v (as an ssl server) s (as an email signer) r (as an email recipient) -v valid-months set the number of months a new certificate will be valid.
...And 3 more matches
How to embed the JavaScript engine
a bare bones tutorial hello world sample embedding application the following code is a very simple application that shows how to embed spidermonkey and run a simple javascript script.
... spidermonkey 24 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object.
...ename = "noname"; int lineno = 1; bool ok = js_evaluatescript(cx, global, script, strlen(script), filename, lineno, rval.address()); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); } js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); return 0; } spidermonkey 31 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object.
...And 3 more matches
Bytecode Descriptions
the instruction immediately following any jsop::*eval instruction must be jsop::lineno.
...the following inequalities must hold: low <= high and firstresumeindex + high - low < resumeoffsets().size().
...┬──┬◡ノ(° -°ノ) this must be used only in the fixed sequence of instructions following a jstry_catch span (see "bytecode invariants" above), as that's the only way instructions would run with an exception pending.
...And 3 more matches
A Web PKI x509 certificate primer
generate the key using the following command: openssl genpkey -algorithm rsa -out key.pem -pkeyopt rsa_keygen_bits:2048 2048 is considered secure for the next 4 years.
...write extensions file by creating a new file with name openssl.ss.cnf with the following contents: basicconstraints = ca:false subjectaltname =dns:www.example.com extendedkeyusage =serverauth 4.
... cas apply to have their root certificates included by default in mozilla products by following the mozilla ca certificate policy and applying for inclusion as per ca:how_to_apply.
...And 3 more matches
Component Internals
component manifests and type library manifests are described in the following section, xpcom registry manifests.
...it specifies the following information: location on disk of registered components with file size class id to location mapping contract id to class id mapping the component manifest maps component files to unique identifiers for the specific implementations (class ids), which in turn are mapped to more general component identifiers (contract ids).
... type library manifests type library manifests contain the following information: location of all type library files mapping of all known interfaces to type libraries where these structures are defined using the data in these two manifests, xpcom knows exactly which component libraries have been installed and what implementations go with which interfaces.
...And 3 more matches
Creating the Component Code
basic structure of the weblock component source weblock1.cpp that defines these classes and the code you need to create a basic component has the following structure: * required includes and constants * weblock: public iweblock * weblockfactory: public nsifactory * weblockmodule: public nsimodule in xpcom, all of these classes also derive from the nsisupports base interface.
...for example, including nsicomponentmanager.idl without mozilla_strict_api defined will include the following headers, which are not supported across versions (unfrozen): nscomponentmanagerutils.h nscomponentmanagerobsolete.h these variables are picked up by files that do not specify themselves as mozilla_strict_api.
...they define the module and factory interfaces, and they contain a couple of important macros as well (see the following chapter for information about using these macros).
...And 3 more matches
XUL Overlays
MozillaTechXULOverlays
thus, given the following base: ...
...and given the following overlay: <?xml version="1.0"?> <overlay id="singleitemex" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <menupopup id="menu_filepopup"> <menu id="file_menu"> <menuitem name="super stream player"/> </menu> </menupopup> </overlay> the result will be: ...
...inserting the following processing instruction before the doctype declaration in a base file tells the layout engine to load the named overlay file: <?xul-overlay href="chrome://component/content/componentoverlay.xul"?> where component is the name of the package being overlayed (e.g., chrome://navigator/content/navigatoroverlay.xul).
...And 3 more matches
Working with ArrayBuffers
this feature is based on the following work: //github.com/realityripple/uxp/blob/master/js/src/ctypes/ctypes.cpp#3080 //github.com/realityripple/uxp/blob/master/js/src/vm/arraybufferobject.cpp#1301 example 1 - image data the following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to imagedata of canvas.
... the following codeblock provides a basic example of getting and setting uint8clampedarray and arraybuffer of imagedata: // context is a canvasrenderingcontext2d of some canvas var imagedata = context.getimagedata(x, y, w, h); var array = imagedata.data; // array is a uint8clampedarray var buffer = imagedata.data.buffer; // buffer is a arraybuffer // incomingbuffer is a typedarray var imagedata2 = context.createimagedata(w, h); imagedata2.data.set(incomingbuffer); further, if you have a byte array pixelbuffer, and you need to create imagedata from it.
... we start with the following: // pixelbuffer is a pointer to a rgba pixel buffer of 400x400 image.
...And 3 more matches
Debugger.Script - Firefox Developer Tools
each of the following is represented by a single jsscript object: the body of a function—that is, all the code in the function that is not contained within some nested function.
... accessor properties of the debugger.script prototype object a debugger.script instance inherits the following accessor properties from its prototype: isgeneratorfunction true if this instance refers to a jsscript for a function defined with a function* expression or statement.
... for example, suppose we have a script for the following source code: a=[] for (i=1; i < 10; i++) // it's hip to be square.
...And 3 more matches
Debugger - Firefox Developer Tools
accessor properties of the debugger prototype object a debugger instance inherits the following accessor properties from its prototype: enabled a boolean value indicating whether this debugger instance’s handlers, breakpoints, and the like are currently enabled.
... onerror(frame,report) spidermonkey is about to report an error inframe.report is an object describing the error, with the following properties: message the fully formatted error message.
... the valueglobal may be any of the following: a global object.
...And 3 more matches
DevTools API - Firefox Developer Tools
to use the gdevtools api from an add-on, it can be imported with following snippet const { gdevtools } = require("resource:///modules/devtools/gdevtools.jsm"); methods registertool(tooldefinition) registers a new tool and adds a tab to each existing toolbox.
... events following events are emitted by the gdevtools object via the eventemitter interface.
... constants the toolbox constructor contains following constant properties.
...And 3 more matches
Index - Firefox Developer Tools
the following list aims to help firebug users to find their way into the developer tools.
... 70 use the inspector api inspector, reference, référence(2), tools firefox add-ons may access the following objects from the chrome://browser/content/devtools/inspector/inspector.xul context: 71 use the inspector from the web console guide, inspector, tools the element that's currently selected in the page inspector can be referenced in the web console using the variable $0.
...currently it can be used to inspect the following storage types: 106 cache storage cache storage, devtools, firefox, guide, storage, storage inspector, tools, l10n:priority under the cache storage type within the storage inspector you can see the contents of any dom caches created using the cache api.
...And 3 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
the following figure shows the recently created text node object inside the document tree.
...the following code removes text node mytextnode (containing the word "world") from the second <p> element, myp.
...the following code attaches mytextnode to the recently created <p> element, mynewptagnode.
...And 3 more matches
Introduction to the File and Directory Entries API - Web APIs
usefulness of the api the file and directory entries api is an important api for the following reasons: it lets apps have offline and storage features that involve large binary blobs.
...the api is a better choice for apps that deal with blobs for the following reasons: the file and directory entries api offers client-side storage for use cases that are not addressed by databases.
... sample use cases the following are just a few examples of how you can use the file and directory entries api: apps with persistent uploader when a file or directory is selected for upload, you can copy the file into a local sandbox and upload a chunk at a time.
...And 3 more matches
HTML Drag and Drop API - Web APIs
identify what is draggable making an element draggable requires adding the draggable attribute and the ondragstart global event handler, as shown in the following code sample: <script> function dragstart_handler(ev) { // add the target element's id to the data transfer object ev.datatransfer.setdata("text/plain", ev.target.id); } window.addeventlistener('domcontentloaded', () => { // get the element by id const element = document.getelementbyid("p1"); // add the ondragstart event listener element.addeventlistener("dragstart"...
...the setdata() method is used to add an item to the drag data, as shown in the following example.
...however, an application may define a custom image with the setdragimage() method, as shown in the following example.
...And 3 more matches
IDBIndexSync - Web APIs
any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this method can raise a idbdatabaseexception with the following code: value the value to store into the index.
... exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key.
... exceptions this method can raise a idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key.
...And 3 more matches
Using Web Workers - Web APIs
worker feature detection for slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js): if (window.worker) { ...
... the error event has the following three fields that are of interest: message a human-readable error message.
...it accepts zero or more uris as parameters to resources to import; all of the following examples are valid: importscripts(); /* imports nothing */ importscripts('foo.js'); /* imports just "foo.js" */ importscripts('foo.js', 'bar.js'); /* imports two scripts */ importscripts('//example.com/hello.js'); /* you can import scripts from other origins */ the browser loads each listed script and executes it.
...And 3 more matches
Shorthand properties - CSS: Cascading Style Sheets
background properties a background with the following properties ...
... font properties the following declarations ...
...can be shortened to the following: font: italic bold .8em/1.2 arial, sans-serif; this shorthand declaration is actually equivalent to the longhand declarations above plus font-variant: normal and font-size-adjust: none (css2.0 / css3), font-stretch: normal (css3).
...And 3 more matches
Media buffering, seeking, and time ranges - Developer guides
a timeranges object consists of the following properties: length: the number of time ranges in the object.
... ------------------------------------------------------ |=============| |===========| | ------------------------------------------------------ 0 5 15 19 21 for this audio instance, the associated timeranges object would have the following available properties: myaudio.buffered.length; // returns 2 myaudio.buffered.start(0); // returns 0 myaudio.buffered.end(0); // returns 5 myaudio.buffered.start(1); // returns 15 myaudio.buffered.end(1); // returns 19 to try out and visualize buffered time ranges we can write a little bit of html: <p> <audio id="my-audio" controls> <source src="music.mp3" type="audio/mpeg"> </aud...
...we can find this point in the media using the following line of code: var seekableend = myaudio.seekable.end(myaudio.seekable.length - 1); note: myaudio.seekable.end(myaudio.seekable.length - 1) actually tells us the end point of the last time range that is seekable (not all seekable media).
...And 3 more matches
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
additional attributes in addition to the common attributes shared by all <input> elements, inputs of type file also support the following attributes: attribute description accept one or more unique file type specifiers describing file types to allow capture what source to use for capturing image or video data files a filelist listing the chosen files multiple a boolean which, if present, indicates that the user may choose more than one file accept the accept a...
... non-standard attributes in addition to the attributes listed above, the following non-standard attributes are available on some browsers.
...each unique file type specifier may take one of the following forms: a valid case-insensitive filename extension, starting with a period (".") character.
...And 3 more matches
itemscope - HTML: Hypertext Markup Language
in each of the following examples, the vocabulary is from schema.org.
... note: find more about itemtype attributes at http://schema.org/thing simple example html the following example specifies the itemscope attribute.
... <div itemscope itemtype="http://schema.org/movie"> <h1 itemprop="name">avatar</h1> <span>director: <span itemprop="director">james cameron</span> (born august 16, 1954)</span> <span itemprop="genre">science fiction</span> <a href="https://youtu.be/0ay1xikx7by" itemprop="trailer">trailer</a> </div> structured data the following table shows the structured data from the preceding example.
...And 3 more matches
Text formatting - JavaScript
'\xa9' // "©" unicode escape sequences the unicode escape sequences require at least four hexadecimal digits following \u.
...for example, the following code assigns hellolength the value 13, because "hello, world!" has 13 characters, each represented by one utf-16 code unit.
... the following table summarizes the methods of string objects.
...And 3 more matches
Functions - JavaScript
however, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example: /* declare the function 'myfunc' */ function myfunc(theobject) { theobject.brand = "toyota"; } /* * declare variable 'mycar'; * create and initialize a new object; * assign reference to it to 'mycar' */ var mycar = { brand: "honda", model: "accord", year: 1998 }; /* logs 'honda' */ console.log(mycar.brand); /* pass object reference to the function */ myfunc(mycar); /* *...
...expression compare the following: a function defined with the function constructor assigned to the variable multiply: var multiply = new function('x', 'y', 'return x * y'); a function declaration of a function named multiply: function multiply(x, y) { return x * y; } // there is no semicolon here a function expression of an anonymous function assigned to the variable multiply: var multiply = function(x, y) { return ...
...for example, the following would result in an error: var foo = new function("alert(anonymous);"); foo(); unlike functions defined by function expressions or by the function constructor, a function defined by a function declaration can be used before the function declaration itself.
...And 3 more matches
Array.prototype.map() - JavaScript
the callback function accepts the following arguments: currentvalue the current element being processed in the array.
... you can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it.
... // in browsers that support object.defineproperty, use the following: // object.defineproperty(a, k, { // value: mappedvalue, // writable: true, // enumerable: true, // configurable: true // }); // for best browser support, use the following: a[k] = mappedvalue; } // d.
...And 3 more matches
String.prototype.charAt() - JavaScript
examples displaying characters at different locations in a string the following example displays characters at different locations in the string "brave new world": var anystring = 'brave new world'; console.log("the character at index 0 is '" + anystring.charat() + "'"); // no index was provided, used 0 as default console.log("the character at index 0 is '" + anystring.charat(0) + "'"); console.log("the character at index 1 is '" + anystring.charat(1) + "'"); c...
...onsole.log("the character at index 2 is '" + anystring.charat(2) + "'"); console.log("the character at index 3 is '" + anystring.charat(3) + "'"); console.log("the character at index 4 is '" + anystring.charat(4) + "'"); console.log("the character at index 999 is '" + anystring.charat(999) + "'"); these lines display the following: the character at index 0 is 'b' the character at index 0 is 'b' the character at index 1 is 'r' the character at index 2 is 'a' the character at index 3 is 'v' the character at index 4 is 'e' the character at index 999 is '' getting whole characters the following provides a means of ensuring that going through a string loop always provides a whole character, even if the string contains characters that are not in the basic multi-lingual plan...
... { var code = str.charcodeat(i); if (number.isnan(code)) { return ''; // position not found } if (code < 0xd800 || code > 0xdfff) { return str.charat(i); } // high surrogate (could change last hex to 0xdb7f to treat high private // surrogates as single characters) if (0xd800 <= code && code <= 0xdbff) { if (str.length <= (i + 1)) { throw 'high surrogate without following low surrogate'; } var next = str.charcodeat(i + 1); if (0xdc00 > next || next > 0xdfff) { throw 'high surrogate without following low surrogate'; } return str.charat(i) + str.charat(i + 1); } // low surrogate (0xdc00 <= code && code <= 0xdfff) if (i === 0) { throw 'low surrogate without preceding high surrogate'; } var prev = str.charcodeat(i - 1); ...
...And 3 more matches
String.prototype.split() - JavaScript
const mystring = '' const splits = mystring.split() console.log(splits) // ↪ [""] the following example defines a function that splits a string into an array of strings using separator.
... console.log('the array has ', arrayofstrings.length, ' elements: ', arrayofstrings.join(' / ')) } const tempeststring = 'oh brave new world that has such people in it.' const monthstring = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec' const space = ' ' const comma = ',' splitstring(tempeststring, space) splitstring(tempeststring) splitstring(monthstring, comma) this example produces the following output: the original string is: "oh brave new world that has such people in it." the separator is: " " the array has 10 elements: oh / brave / new / world / that / has / such / people / in / it.
... the original string is: "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec" the separator is: "," the array has 12 elements: jan / feb / mar / apr / may / jun / jul / aug / sep / oct / nov / dec removing spaces from a string in the following example, split() looks for zero or more spaces, followed by a semicolon, followed by zero or more spaces—and, when found, removes the spaces and the semicolon from the string.
...And 3 more matches
parseInt() - JavaScript
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 assumed to be 16 and the rest of the string is parsed as a hexidecimal number.
...the following may have an octal result, or it may have a decimal result.
...And 3 more matches
Logical AND (&&) - JavaScript
short-circuit evaluation the logical and expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule: (some falsy expression) && expr is short-circuit evaluated to the falsy expression; short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place).
...see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( a() && b() ); // logs "called a" due to the function call, // then logs false (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).
... true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using and the following code shows examples of the && (logical and) operator.
...And 3 more matches
Logical OR (||) - JavaScript
short-circuit evaluation the logical or expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule: (some truthy expression) || expr is short-circuit evaluated to the truthy expression.
...see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( b() || a() ); // logs "called b" due to the function call, // then logs true (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).
... true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using or the following code shows examples of the || (logical or) operator.
...And 3 more matches
delete operator - JavaScript
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 true.
... the following snippet gives a simple example: var employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete employee.name); // returns true console.log(delete employee.age); // returns true // when trying to delete a property that does // not exist, true is returned console.log(delete employee.salary); // returns true non-configurable properties when a property is marked...
...delete employeedetails; // returns true function f() { var z = 44; // delete doesn't affect local variable names delete z; // returns false } delete and the prototype chain in the following example, we delete an own property of an object while a property with the same name is available on the prototype chain: function foo() { this.bar = 10; } foo.prototype.bar = 42; var foo = new foo(); // foo.bar is associated with the // own property.
...And 3 more matches
new operator - JavaScript
description the new keyword does the following things: creates a blank, plain javascript object; links (sets the constructor of) this object to another object; passes the newly created object from step 1 as the this context; returns this if the function doesn't return an object.
... when the code new foo(...) is executed, the following things happen: a new object is created, inheriting from foo.prototype.
...the following code adds a color property with value "original color" to all objects of type car, and then overwrites that value with the string "black" only in the instance object car1.
...And 3 more matches
break - JavaScript
the break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
... a break statement, with or without a following label, cannot be used within the body of a function that is itself nested within the current loop, switch, or label statement that the break statement is intended to break out of.
... examples break in while loop the following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x.
...And 3 more matches
Web video codec guide - Web media technologies
common codecs the following video codecs are those which are most commonly used on the web.
... motion compression of video typically works by comparing frames, finding where they differ, and constructing records containing enough information to update the previous frame to approximate the appearance of the following frame.
... here, only the differences between the first frame and the following frame are seen.
...And 3 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
to get these sitting side-by-side we have used the following rules: x-card { width: 100%; } x-card:nth-child(1), x-card:nth-child(2) { width: 30%; float: left; padding: 2rem; } x-card:nth-child(3) { width: 40%; float: left; height: 100%; overflow: auto; padding: 2rem; } so we're giving the first two columns a width of 30%, and the third a width of 40%, floating the columns all left.
...we opened up the brick.js file and wrapped the whole lot in the following: if (window.matchmedia("(max-width: 480px)").matches) { // the whole of brick.js goes here!
...you could use a min-width media query to fix the <body> width at a certain point: @media all and (min-width: 1400px) { body { width: 1400px; margin: 0 auto; } } but it's actually easier to just set the following rule instead, and get rid of the media query altogether: body { max-width: 1400px; margin: 0 auto; } orientation fail we also came across some problems with orientation: the mobile-app layout of our example app is designed for portrait orientation, and looks terrible when viewed on a device in landscape orientation.
...And 3 more matches
Content type - SVG: Scalable Vector Graphics
the following are examples of legal clock values: full clock values: 02:30:03 = 2 hours, 30 minutes and 3 seconds 50:00:10.25 = 50 hours, 10 seconds and 250 milliseconds partial clock value: 02:33 = 2 minutes and 33 seconds 00:10.5 = 10.5 seconds = 10 seconds and 500 milliseconds timecount values: 3.2h = 3.2 hours = 3 hours and 12 minutes 45min = 45 minutes 30s = 30 seconds 5ms =...
...for example, an svg file called somedrawing.svg located at http://example.com might have the following iri: http://example.com/somedrawing.svg an iri can also address a particular element within an xml document by including an iri fragment identifier as part of the iri.
...for example, the following iri can be used to specify the element whose id is "lamppost" within file somedrawing.svg: http://example.com/somedrawing.svg#lamppost iris are used in the xlink:href attribute.
...And 3 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
take a copy of the following simple c example, and save it in a file called hello.c in a new directory on your local drive: #include <stdio.h> int main(int argc, char ** argv) { printf("hello world\n"); } now, using the terminal window you used to enter the emscripten compiler environment, navigate to the same directory as your hello.c file, and run the following command: emcc hello.c -s wasm=1 -o hello.html ...
... first of all, save the following c code in a file called hello2.c, in a new directory: #include <stdio.h> int main(int argc, char ** argv) { printf("hello world\n"); } search for the file shell_minimal.html in your emsdk repo.
... now navigate into your new directory (again, in your emscripten compiler environment terminal window), and run the following command: emcc -o hello2.html hello2.c -o3 -s wasm=1 --shell-file html_template/shell_minimal.html the options we've passed are slightly different this time: we've specified -o hello2.html, meaning that the compiler will still output the javascript glue code and .html.
...And 3 more matches
ui/frame - Archive of obsolete content
frame supports the following events: attach, detach, load, ready, and message.
...frame supports the following events: attach, detach, load, ready, and message.
...frame supports the following events: attach, detach, load, ready, and message.
...And 2 more matches
ui/toolbar - Archive of obsolete content
toolbar supports the following events: attach, detach, show, and hide.
...toolbar supports the following events: attach, detach, show, and hide.
...toolbar supports the following events: attach, detach, show, and hide.
...And 2 more matches
jpm-mobile - Archive of obsolete content
jpm usage is: jpm-mobile [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number installation jpm-mobile is distributed using the node package manager npm, so to get jpm-mobile you need to have npm installed, if you haven't already.
... jpm-mobile run this command runs a new instance of firefox with the add-on installed: jpm-mobile run jpm-mobile run accepts the following options: --adb /path/to/adb provides the path to adb.
... jpm-mobile run -b fennec you can get the package name by following command.
...And 2 more matches
Localization - Archive of obsolete content
hello_id= <blink>hello!</blink> localizing element attributes this feature is new in firefox 39 you can localize certain attributes of elements with an l10n-id by setting its value with l10n-id.attributename in the properties file like: hello_id.accesskey= h the following attributes are supported: accesskey alt label title placeholder further the localization of the aria attributes aria-label, aria-valuetext and aria-moz-hint are supported with the same aliases as on firefox os: arialabel ariavaluetext ariamozhint using localized strings in javascript to reference localized strings from your main add-on code, you do this: var _ = require("sdk/l10...
...in this scheme a language maps each distinct range of numbers on to one of up to six forms, identified by the following categories: zero, one, two, few, many, and other.
...the following "en-us" and "fr" ".properties" files include placeholders: # en-us translations hello_id= hello %s!
...And 2 more matches
Extension Versioning, Update and Compatibility - Archive of obsolete content
formatting prior to firefox 4 prior to firefox 4 you could only use the following tags, any other tags have themselves and their contents completely stripped: h1, h2 and h3 for general headings p for paragraphs ul and ol for lists.
...the following tags are interpreted normally: h1, h2 and h3 for general headings p, div, pre and blockquote for block formatting ul, ol, li, dl, dt and dd for lists b, i, em, strong, u, q, sub, sup and code for text formatting br and hr for line breaking the head, style and script tags and any of their contents are completely stripped.
... other tags aren't included in the result but do have their contents displayed, so the following snippet: <span><q>text</q></span> would be rendered exactly the same as: <q>text</q> sample file <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html lang="en-us" dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> <h2>my extension</h2> <ul> <li>this update fixes some stability related issues.</li> </ul> </html> what end-user sees the content of updateinfourl will be displayed to user in the add-ons page, in a list of all available updates.
...And 2 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
install quicknote from the following url and relaunch firefox.
...install mozlab from the following url and relaunch firefox.
...if you want to use terapad2, for example, insert the following: c:\app\tpad090\terapad.exe /jl=%l %f table 1: parameters used in mozunit parameter description %f filename %l line number %c column number the author uses meadow, which is opened using gnuserv.
...And 2 more matches
The Essentials of an Extension - Archive of obsolete content
a localized description and name can be added with the following code: <em:localized> <description> <em:locale>es-es</em:locale> <em:name>xul school hola mundo</em:name> <em:description>bienvenido a xul school!</em:description> </description> </em:localized> the es-es locale string indicates that this is the spanish (es) localization for spain (es).
...the dtd file was included in the xul file with the following code: <!doctype overlay system "chrome://xulschoolhello/locale/browseroverlay.dtd" > and in the dtd file you can see the association between keys and localized strings: <!entity xulschoolhello.hello.label "hello world!"> <!entity xulschoolhello.hellomenu.accesskey "l"> <!entity xulschoolhello.helloitem.accesskey "h"> notice that on the xul file you enclose the string ...
...you can easily recognize the access keys on windows because the letter that corresponds to the access key is underlined, as in the following image: most user interface controls have the accesskey attribute, and you should use it.
...And 2 more matches
Source Navigator - Archive of obsolete content
let me know if this is wrong..) it can generate a class hierarchy quite easily (unfortunately, not for classnames which are defined by macro.) installing source navigator in ubuntu execute the following line in a terminal window: sudo apt-get install sourcenav this should install source-navigator.
... one can check whether the installation is complete by executing: $ which snavigator /usr/bin/snavigator importing the source execute the following: snavigator.
... this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a new project bin.proj before documenting this.
...And 2 more matches
Creating regular expressions for a microsummary generator - Archive of obsolete content
for example, the following regular expression matches--and looks exactly like--the beginning of the url: http:// but some characters are special in regular expressions.
...so we remove the item number, leaving us with the following regular expression: ^http://cgi\.ebay\.com/ws/ebayisapi\.dll\?viewitem&item= accommodating variations in query parameters we now have a regular expression that matches all four example urls.
... for example, the following is an equally valid url for the same auction item: http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&foo=bar&item=170019463424 to accommodate these variations in query parameters, we can insert a period followed by an asterisk (.*) between "viewitem&" and "item=" to match any characters that might appear between those two strings: ^http://cgi\.ebay\.com/ws/ebayisapi\.dll\?viewitem&.*item= the...
...And 2 more matches
Dehydra Object Reference - Archive of obsolete content
each member of the array has the following properties: { name: string, value: string or number, if applicable } see an example on enforcing final classes.
...the following properties are usually available: property type description .name string the function or variable name.
...the following additional properties are available on functions: property type description .isvirtual true or "pure" true for virtual methods, or "pure" for pure virtuals (e.g.
...And 2 more matches
Java in Firefox Extensions - Archive of obsolete content
the following technique only works in javascript code linked from or contained in xul files.
...the following approach is taken from the extension xquseme (note you must use the latest version, currently still in the sandbox, as prior versions only worked with liveconnect before java 6 update 11) which borrows some of the code of the java firefox extension in order to grant full privileges to java within a firefox extension, but it is easier to understand and doesn't require creation of a xpcom componen...
...// guid of extension getitemlocation("test@yoursite"); //the path logic would work if we include em:unpack for ff 4.x, for ff 3.x since things are unpacked by default things work // get path to the jar files (the following assumes your jars are within a // directory called "java" at the root of your extension's folder hierarchy) // you must add this utilities (classloader) jar to give your extension full privileges var extensionurl = "file:///" + extensionpath.path.replace(/\\/g,"/"); var classloaderjarpath = extensionurl + "/java/javafirefoxextensionutils.jar"; // add the paths for all the other jar files that you...
...And 2 more matches
Additional Navigation - Archive of obsolete content
the resulting data will look like the following: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg) here is the example.
...another thing that you cannot have is a triple where both variables would be unknown as in the following: <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?category" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> </query> in this case when the template builder gets to the triple, neither the ?category nor the ?title variables can be filled in so the builder doesn't know what to generate.
... source navigation triples may also be used to navigate up the graph as well as downwards, following the graph arrows in the reverse direction.
...And 2 more matches
Styling a Tree - Archive of obsolete content
« previousnext » the following describes how to style a tree.
... set the property on a row or cell, as in the following example: <treerow properties="makeitblue"> css selectors for the tree the style sheet can take this property and use it to change the appearance of the row for unread messages or labels.
...the following is the syntax that needs to be used: treechildren::-moz-tree-row(makeitblue) { background-color: blue; } this style which has a complex selector is used to style the background color of rows that have the 'makeitblue' property.
...And 2 more matches
Trees and Templates - Archive of obsolete content
« previousnext » the following describes how to use a template with a tree.
...the following example uses the history datasource: <tree datasources="rdf:history" ref="nc:historybydate" flags="dont-build-content"> as described in the previous section, the tree may use a tree builder for template generation instead of the normal content builder.
...template-built tree example the following example demonstrates a template-built tree, in this case for the file system.
...And 2 more matches
XUL accessibility guidelines - Archive of obsolete content
by following these principles and practices, you will be able to write your xul applications in such a way that all users, including those with physical, sensory, or communicative disabilities, with be able to use and enjoy them.
...refer to the following resources when setting keyboard shortcuts.
... the following example shows a javascript function that can be called before destroying an element to check for focus and move it if necessary.
...And 2 more matches
XULRunner 2.0 Release Notes - Archive of obsolete content
the following directory is recommended: c:\program files\mozilla xulrunner\2.0 .
...the following directory is recommended: /opt/xulrunner/2.0 .
...the following directory is recommended: /opt/xulrunner/2.0 .
...And 2 more matches
Debugging a XULRunner Application - Archive of obsolete content
see also debugging javascript prefs setting the following prefs will make your debugging life much easier!
...add the following code to your xul app: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); // don't specify a window type parameter below if "navigator:browser" // is suitable for your app.
... for xulrunner version 37+ the code to enable the debugger has changed: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); debuggerserver.addbrowseractors(); debuggerserver.allowchromeprocess = true; } let dbglistener=debuggerserver.createlistener(); dbglistener.portorpath=6000; dbglistener.open(); add the following to your prefs.js: (in recent ffox, edit about:config instead) pref("devtools.debugger.remote-enabled", true); in firefox, go to tools > web developer > connect...
...And 2 more matches
2006-10-20 - Archive of obsolete content
he stated that he was able to pre-package the extensions that he wanted by following this walkthrough and a little bit of help from this post.
...he can be contacted via: email: preed@mozilla.com irc: preed on irc.mozilla.org phone: 650.903.0800 x256 uploading language packs to amo on october 17th benjamin smedberg brought the following to the attention of the localizers and the build team: that he is planning to upload the firefox 2 language packages currently located at http://releases.mozilla.org/pub/mozi...rc3/win32/xpi/ to addons.mozilla.org in the next few days.
...you can do this by replying to the following post.
...And 2 more matches
-ms-filter - Archive of obsolete content
syntax the -ms-filter property is specified as a string that contains a list of one or more items, separated by spaces, of the following types: filters transitions procedural surfaces formal syntax filter: <-ms-filter-function>+ -ms-filter: [ "'" <-ms-filter-function># "'" ] | [ '"' <-ms-filter-function># '"' ] where <-ms-filter-function> = <-ms-filter-function-progid> | <-ms-filter-function-legacy> where <-ms-filter-function-progid> = 'progid:' [ <ident-token> '.' ]* [ <ident-token> | <function-token> <any-value> ')' ] ...
... examples the following example shows how to use the -ms-filter attribute in internet explorer 8.
... code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_8.htm -ms-filter: 'progid:dximagetransform.microsoft.motionblur(strength=50), progid:dximagetransform.microsoft.basicimage(mirror=1)'; the following example shows how to use an inline style sheet to set the filter on an image.
...And 2 more matches
XForms Custom Controls - Archive of obsolete content
it is possible to re-enable this by following the steps on using remote xul.
...to really grasp the following information, a good understanding of xforms, xbl, javascript and css is needed.
...why do you need this you will probably find that your need for customization will fall into one of the following categories: custom presentation - xforms controls as rendered by the mozilla xforms processor do not provide the right look and feel for you.
...And 2 more matches
Common causes of memory leaks in extensions - Extensions
consider the following example code that could be part of your browser.xul overlay: gbrowser.addeventlistener("domcontentloaded", function(evt) { var contentdoc = evt.originaltarget; var i = 0; // refresh the title once each second setinterval(function() { contentdoc.title = ++i; }, 1000); }, false); one would normally expect that the interval (or timer) would be destroyed as soon as the document unlo...
...for example, the following code snippets — part of a bootstrap.js — will leak: function leakref() {} function modifydocument(document) { var a = document.createelement("a"); document.body.appendchild(a); // the new dom node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootstrap compartment.
... window.addeventlistener("leaky", leakref, true); // the following line still fails to avoid the leak, as usecapture differs // and removeeventlistener will not remove anything.
...And 2 more matches
Paddle and keyboard controls - Game development
add the following variables near the top of your code, beside your other variables: var paddleheight = 10; var paddlewidth = 75; var paddlex = (canvas.width-paddlewidth) / 2; here we're defining the height and width of the paddle and its starting point on the x axis for use in calculations further on down the code.
...add the following just below your drawball() function: function drawpaddle() { ctx.beginpath(); ctx.rect(paddlex, canvas.height-paddleheight, paddlewidth, paddleheight); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } allowing the user to control the paddle we can draw the paddle wherever we want, but it should respond to the user's actions.
...we will need the following: two variables for storing information on whether the left or right control button is pressed.
...And 2 more matches
Track the score and win - Game development
add the following into your javascript, after the rest of your variables: var score = 0; you also need a drawscore() function, to create and update the score display.
... add the following after the collisiondetection() function: function drawscore() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("score: "+score, 8, 20); } drawing text on a canvas is similar to drawing a shape.
...add the following highlighted line to your code: function collisiondetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { var b = bricks[c][r]; if(b.status == 1) { if(x > b.x && x < b.x+brickwidth && y > b.y && y < b.y+brickheight) { dy = -dy; b.status = 0; score++; ...
...And 2 more matches
2D maze game with device orientation - Game development
let’s set it up: our starting point is the index.html file with the following content.
...e'); this.gametitle.anchor.set(0.5,0); this.startbutton = this.add.button(ball._width*0.5, 200, 'button-start', this.startgame, this, 2, 0, 1); this.startbutton.anchor.set(0.5,0); this.startbutton.input.usehandcursor = true; }, startgame: function() { this.game.state.start('howto'); } }; to create a new button there's add.button method with the following list of optional arguments: top absolute position on canvas in pixels.
...let’s focus on the keyboard first by adding the following to the create() function : this.keys = this.game.input.keyboard.createcursorkeys(); as you can see there’s a special phaser function called createcursorkeys(), which will give us an object with event handlers for the four arrow keys to play with: up, down, left and right.
...And 2 more matches
Accessible multimedia - Learn web development
we will first need to store references to each of the controls — add the following to the top of your javascript file: const playpausebtn = document.queryselector('.playpause'); const stopbtn = document.queryselector('.stop'); const rwdbtn = document.queryselector('.rwd'); const fwdbtn = document.queryselector('.fwd'); const timelabel = document.queryselector('.time'); next, we need to grab a reference to the video/audio player itself — add this line below the previous line...
...add the following, again at the bottom of your javascript: player.removeattribute('controls'); doing it this way round rather than just not including the controls attribute in the first place has the advantage that if our javascript fails for any reason, the user still has some controls available.
...we can get this to toggle between play and pause with a simple conditional function, like the following.
...And 2 more matches
Advanced styling effects - Learn web development
e class="simple"> <p><strong>warning</strong>: the thermostat on the cosmic transcender has reached a critical level.</p> </article> now the css: p { margin: 0; } article { max-width: 500px; padding: 10px; background-color: red; background-image: linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,0.25)); } .simple { box-shadow: 5px 5px 5px rgba(0,0,0,0.7); } this gives us the following result: you'll see that we've got four items in the box-shadow property value: the first length value is the horizontal offset — the distance to the right the shadow is offset from the original box (or left, if the value is negative).
...1px black, inset 2px 3px 5px rgba(0,0,0,0.3), inset -2px -3px 5px rgba(255,255,255,0.5); } button:focus, button:hover { background-image: linear-gradient(to bottom right, #888, #eee); } button:active { box-shadow: inset 2px 2px 1px black, inset 2px 3px 5px rgba(0,0,0,0.3), inset -2px -3px 5px rgba(255,255,255,0.5); } this gives us the following result: here we've set up some button styling along with focus/hover/active states.
...10px; } article div:first-child { position: absolute; top: 10px; left: 0; background: url(https://mdn.mozillademos.org/files/13090/colorful-heart.png) no-repeat center 20px; background-color: green; } article div:last-child { background-color: purple; position: absolute; bottom: -10px; right: 0; z-index: -1; } .multiply-mix { mix-blend-mode: multiply; } this gives us the following results: you can see here that the multiply mix blend has blended together not only the two background images, but also the color from the <div> below it too.
...And 2 more matches
Test your skills: Selectors - Learn web development
selectors one without changing the html, use css to do the following things: make h1 headings blue.
... selectors two without changing the html, make the following changes to the look of the content in this example: give the element with an id of special a yellow background.
... selectors three in this example, try making the following changes without adding to the html.
...And 2 more matches
CSS values and units - Learn web development
in the following example we have set the color of our heading using a keyword, and the background using the rgb() function: h1 { color: black; background-color: rgb(197,93,161); } a value in css is a way to define a collection of allowable sub-values.
...the following are all classed as numeric: data type description <integer> an <integer> is a whole number such as 1024 or -55.
... absolute length units the following are all absolute length units — they are not relative to anything else and are generally considered to always be the same size.
...And 2 more matches
Beginner's guide to media queries - Learn web development
media types the possible types of media you can specify are: all print screen speech the following media query will only set the body to 12pt if the page is printed.
...for example, to change the body text color to red if the viewport is exactly 600 pixels, you would use the following media query.
...to change the body text color if the device is in landscape orientation, use the following media query.
...And 2 more matches
Getting started with CSS - Learn web development
to link styles.css to index.html add the following line somewhere inside the <head> of the html document: <link rel="stylesheet" href="styles.css"> this <link> element tells the browser that we have a stylesheet, using the rel attribute, and the location of that stylesheet as the value of the href attribute.
...using your code editor add the following to your css file: h1 { color: red; } save your html and css files and reload the page in a web browser.
...add the following to your css file: .special { color: orange; font-weight: bold; } save and refresh to see what the result is.
...And 2 more matches
Your first form - Learn web development
it's beyond the scope of this article to cover the user experience of forms, but if you want to dig into that topic you should read the following articles: smashing magazine has some good articles about forms ux, including an older but still relevant extensive guide to web form usability article.
...we will use the following html elements: <form>, <label>, <input>, <textarea>, and <button>.
... in terms of html code we need something like the following to implement these form widgets: <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">name:</label> <input type="text" id="name" name="user_name"> </li> <li> <label for="mail">e-mail:</label> <input type="email" id="mail" name="user_email"> </li> <li> <label for="msg">message:</label> <textarea id="msg" name="user_message"></textarea...
...And 2 more matches
JavaScript basics - Learn web development
is the standard for introductory programming examples.) important: if you haven't been following along with the rest of our course, download this example code and use it as a starting point.
... following that, the code set the value of the myheading variable's textcontent property (which represents the content of the heading) to hello world!.
...in the following table you can see some of the simplest operators, along with some examples to try in the javascript console.
...And 2 more matches
Creating hyperlinks - Learn web development
</p> this gives us the following result: i'm creating a link to the mozilla homepage.
...</p> this gives us the following result and hovering over the link displays the title as a tooltip.
...it normally makes sense to link to a specific heading, so this would look something like the following: <h2 id="mailing_address">mailing address</h2> then to link to that specific id, you'd include it at the end of the url, preceded by a hash/pound symbol (#), for example: <p>want to write us a letter?
...And 2 more matches
Introduction to events - Learn web development
in the following example, we have a single <button>, which when pressed, makes the background change to a random color: <button>change color</button> button { margin: 10px }; the javascript looks like so: const btn = document.queryselector('button'); function random(number) { return math.floor(math.random() * (number+1)); } btn.onclick = function() { const rndcol = 'rgb(' + random(255) + ',' + random(...
...the following works just the same: const btn = document.queryselector('button'); function bgchange() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } btn.onclick = bgchange; there are many different event handler properties available.
...now try changing btn.onclick to the following different values in turn, and observing the results in the example: btn.onfocus and btn.onblur — the color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button.
...And 2 more matches
Looping code - Learn web development
he might use the following loop to achieve this: a loop usually has one or more of the following features: a counter, which is initialized with a certain value — this is the starting point of the loop ("start: i have no food", above).
... in pseudocode, this would look something like the following: loop(food = 0; foodneeded = 10) { if (food >= foodneeded) { exit loop; // we have enough food; let's go home } else { food += 2; // spend an hour collecting 2 more food // loop will then run again } } so the amount of food needed is set at 10, and the amount the farmer currently has is set at 0.
... if we weren't using a loop here, we'd have to repeat the following code for every circle we wanted to draw: ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); this would get very boring and difficult to maintain very quickly.
...And 2 more matches
Arrays - Learn web development
paste the following code into the console: let shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles']; shopping; in the above example, each element is a string, but in an array we can store various data types — strings, numbers, objects, and even other arrays.
... enter the following into your console: shopping[0]; // returns "bread" you can also modify an item in an array by simply giving a single array item a new value.
...try the following: shopping.length; // should return 5 this has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array.
...And 2 more matches
Basic math in JavaScript — numbers and operators - Learn web development
type the following lines into your browser's console: let lotsofdecimal = 1.766584958675746364; lotsofdecimal; let twodecimalplaces = lotsofdecimal.tofixed(2); twodecimalplaces; converting to number data types sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it.
...you can test this by typing in the following: typeof mynumber; to fix the calculation, you can do this: number(mynumber) + 3; arithmetic operators arithmetic operators are the basic operators that we use to do sums in javascript: operator name purpose example + addition adds two numbers together.
...the following will return an error: 3++; so, you can only increment an existing variable.
...And 2 more matches
Storing the information you need — Variables - Learn web development
the following would work: var myname = 'chris'; var myname = 'bob'; but the following would throw an error on the second line: let myname = 'chris'; let myname = 'bob'; you'd have to do this instead: let myname = 'chris'; myname = 'bob'; again, this is a sensible language decision.
...try entering the following lines into your console: myname = 'bob'; myage = 40; an aside on variable naming rules you can call a variable pretty much anything you like, but there are limitations.
...try entering the following lines into your console: let mynamearray = ['chris', 'bob', 'jim']; let mynumberarray = [10, 15, 40]; once these arrays are defined, you can access each value by their location within the array.
...And 2 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
you should see an error message along the following lines: this is a pretty easy error to track down, and the browser gives you several useful bits of information to help you out (the screenshot above is from firefox, but other browsers provide similar information).
... have a look at line 78, and you'll see the following code: loworhi.textcontent = 'last guess was too high!'; this line is trying to set the textcontent property of the loworhi constant to a text string, but it's not working because loworhi does not contain what it's supposed to.
...add the following code on line 49: console.log(loworhi); note: console.log() is a really useful debugging function that prints a value to the console.
...And 2 more matches
Adding features to our bouncing balls demo - Learn web development
the following screenshot gives you an idea of what the finished program should look like: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do.
...you should then make the following changes: we want the evil circle to not be filled in, but rather just have an outer line (stroke).
...the following code block should be put inside the method definition: let _this = this; window.onkeydown = function(e) { if (e.key === 'a') { _this.x -= _this.velx; } else if (e.key === 'd') { _this.x += _this.velx; } else if (e.key === 'w') { _this.y -= _this.vely; } else if (e.key === 's') { _this.y += _this.vely; } } so when a key is pressed, the event object's...
...And 2 more matches
Object-oriented JavaScript for beginners - Learn web development
i\'m ' + obj.name + '.'); }; return obj; } you can now create a new person by calling this function — try the following lines in your browser's javascript console: const salva = createnewperson('salva'); salva.name; salva.greeting(); this works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and return it?
... replace your previous function with the following: function person(name) { this.name = name; this.greeting = function() { alert('hi!
... add the following lines below your previous code addition: let person1 = new person('bob'); let person2 = new person('sarah'); save your code and reload it in the browser, and try entering the following lines into your js console: person1.name person1.greeting() person2.name person2.greeting() cool!
...And 2 more matches
Starting our Svelte Todo list app - Learn web development
create a file named src/components/todos.svelte with the following content: <h1>svelte to-do list</h1> change the title element in public/index.html to contain the text svelte to-do list: <title>svelte to-do list</title> open src/app.svelte and replace its contents with the following: <script> import todos from './components/todos.svelte' </script> <todos /> in development mode, svelte will issue a warning in the browser console whe...
...copy and paste the following into our todos.svelte component file, replacing the existing content: <!-- todos.svelte --> <div class="todoapp stack-large"> <!-- newtodo --> <form> <h2 class="label-wrapper"> <label for="todo-0" class="label__lg"> what needs to be done?
... further down, you can find the following <ul> element: <ul role="list" classname="todo-list stack-large" aria-labelledby="list-heading"> the role attribute helps assistive technology explain what kind of semantic value an element has — or what its purpose is.
...And 2 more matches
Creating our first Vue component - Learn web development
at the top of your <script> tag, add the following to import your todoitem component: import todoitem from './components/todoitem.vue'; inside your component object, add the components property, and inside it add your todoitem component to register it.
...the data property is where you can manage local state in a component, it lives inside the component object alongside the props property and has the following structure: data() { return { key: value } } you'll note that the data property is a function.
...both of the following are equivalent: <input type="checkbox" id="todo-item" v-bind:checked="isdone" /> <input type="checkbox" id="todo-item" :checked="isdone" /> you're free to use whichever pattern you would like.
...And 2 more matches
Handling common accessibility problems - Learn web development
to do that, we had to add the following bit of javascript trickery: document.onkeydown = function(e) { if(e.keycode === 13) { // the enter/return key document.activeelement.onclick(e); } }; here we add a listener to the document object to detect when a button has been pressed on the keyboard.
...we got the following results: axe is also installable using npm, and can be integrated with task runners like grunt and gulp, automation frameworks like selenium and cucumber, unit testing frameworks like jasmin, and more besides (again, see the main axe page for details).
...the basic ones you'll need for web page testing are in the following table.
...And 2 more matches
Theme concepts
package your theme and submit it to amo, following these instructions.
... updating static themes if your static theme is hosted on amo, you can upload a new version using the developer hub with the following steps: visit the product page for your theme through the developer hub select "upload new version" on the left upload your packaged file for validation or modify it using the theme generator for self-hosted static themes, a new version can be updated through amo by following the above steps or be handled by you through an updateurl or external application updates.
... for example, the following code, from the dynamic theme example defines the content for the day and night elements of the dynamic theme: const themes = { 'day': { images: { theme_frame: 'sun.jpg', }, colors: { frame: '#cf723f', tab_background_text: '#111', } }, 'night': { images: { theme_frame: 'moon.jpg', }, colors: { frame: '#000', tab_background_text: '#ff...
...And 2 more matches
Creating a Language Pack
while in that directory, issue the following command: $ make merge-x-testing locale_mergedir=$(pwd)/mergedir x-testing: browser chrome browser aboutcerterror.dtd // add and localize this file ...
... $ make wget-en-us en_us_binary_url=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora if you're building on mac 64 bit, you'll need to change the command slightly: $ make wget-en-us en_us_binary_url=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora moz_pkg_platform=mac at some point, you should see the following 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.
... at the end of the process, you should see the following success message.
...And 2 more matches
Debugging on Mac OS X
the .lldbinit file in the source tree imports many useful mozilla specific lldb settings, commands and formatters into lldb, but you may need to take one of the following steps to make sure this file is used.
... if you are using lldb on the command line (independently of xcode) and you will always run it from either the top source directory, the object directory or else the dist/bin subdirectory of the object directory, then adding the following setting to your $home/.lldbinit is sufficient: settings set target.load-cwd-lldbinit true however, if you will run lldb from a different directory, or if you will be running it indirectly by debugging in xcode (xcode always runs lldb from "/"), then this setting will not help you.
... instead, add the following to your $home/.lldbinit: # this automatically sources the mozilla project's .lldbinit as soon as lldb # starts or attaches to a mozilla app (that's in an object directory).
...And 2 more matches
Error codes returned by Mozilla APIs
the following tables list errors that can occur when calling various mozilla apis.
...for example, by using components.results.ns_error_not_initialized general errors the following errors are general and can occur when using any component.
... file errors the following table lists the errors that could occur when using files.
...And 2 more matches
Storage access policy: Block cookies from trackers
consider the following examples: hostname on the list hostname of resource matched example.com example.com yes example.com a.b.example.com yes blah.example.com example.com no a.b.example.com c.d.example.com no blah.example.com foo.blah.example.com yes what does the storage access policy block?
...specifically, firefox does this by imposing the following restrictions: cookies: block cookie request headers and ignore set-cookie response headers.
...if a user interacts with the pop-up window following a redirect, the origin of the content loaded in the pop-up window is given storage access on the opener document.
...And 2 more matches
HTTP Cache
//github.com/realityripple/uxp/blob/master/netwerk/base/public/nsiloadcontextinfo.idl it is a helper interface wrapping following four arguments into a single one: private-browsing boolean flag anonymous load boolean flag app id number (0 for no app) is-in-browser boolean flag helper functions to create nsiloadcontextinfo objects: c++ consumers: functions at loadcontextinfo.h exported header js consumers: resource://gre/modules/loadconte...
... other parallel openers of the same cache entry are blocked (wait) for invocation of their oncacheentryavailable until one of the following occurs: the writer simply throws the entry away: other waiting opener in line gets the entry again as "new", the cycle repeats.
... adding a new storage should there be a need to add a new distinct storage for which the current scoping model would not be sufficient - use one of the two following ways: [preffered] add a new <your>storage method on nsicachestorageservice and if needed give it any arguments to specify the storage scope even more.
...And 2 more matches
PromiseWorker.jsm
the following sections tell you which content to use in your worker and main thread files, in order to use promiseworker objects.
... by convention, the last argument may be an object options with some of the following fields: outexecutionduration {number|null} a parameter to be filled with the duration of the off main thread execution for this call.
... supported built-in javascript error are following: evalerror internalerror rangeerror referenceerror syntaxerror typeerror urierror in addition to them, stopiteration is also supported (note that stopiteration is deprecated).
...And 2 more matches
SourceMap.jsm
according to the spec, source maps have the following attributes: version: which version of the source map spec this map is following.
...the only argument is an object with the following properties: line: the line number in the generated source.
... and an object is returned with the following properties: source: the original source file, or null if this information is not available.
...And 2 more matches
Localization and Plurals
if you don't know how many plural forms you need, check the pluralrule number in chrome/global/intl.properties, and look up the corresponding entry in the following list of plural rules.
... examples the following are some examples for various languages and a brief thought processes.
...just put the following line somewhere that will be evaluated before you want to use pluralform.
...And 2 more matches
Localizing with Mercurial
mercurial on linux you can easily install mercurial from the command line by issuing one of the following commands.
... your config file should have the following settings: [ui] username = your real name <user@example.com> merge = internal:merge [defaults] commit = -v [diff] git = 1 showfunc = 1 unified = 8 to configure hg, follow these steps: create a new file in your favorite text editor.
... here's how to get (or clone) your en-us source files for the first time: run the following command in the command line to get the source en-us files for firefox: hg clone https://hg.mozilla.org/mozilla-central/ this will create a clone of the mozilla-central repository in the directory mozilla-central.
...And 2 more matches
BloatView
you can set these environment variables to any of the following values.
... combining and sorting bloat logs you can view one or more bloat logs in your browser by running the following program.
...logn > htmlfile this will produce an html file that contains a table similar to the following (but with added javascript so you can sort the data by column).
...And 2 more matches
NSS_3.12_release_notes.html
nss 3.12 release notes 17 june 2008 newsgroup: mozilla.dev.tech.crypto contents introduction distribution information new in nss 3.12 bugs fixed documentation compatibility feedback introduction network security services (nss) 3.12 is a minor release with the following new features: sqlite-based shareable certificate and key databases libpkix: an rfc 3280 compliant certificate path validation library camellia cipher support tls session ticket extension (rfc 5077) nss 3.12 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1.
...nss 3.12 libraries have the following versions: sqlite3: 3.3.17 nssckbi: 1.70 softokn3 and freebl3: 3.12.0.3 other nss libraries: 3.12.0.3 new in nss 3.12 3 new shared library are shipped with nss 3.12: nssutil sqlite nssdbm 1 new include file is shipped with nss3.12: utilrename.h new functions in the nss shared library: cert_checknamespace (see cert.h) cert_encodecertpoliciesextension (see cert.h) cert_encodeinfoaccessex...
...ert ssl_error_bad_cert_hash_value_alert ssl_error_rx_unexpected_new_session_ticket ssl_error_rx_malformed_new_session_ticket new tls cipher suites (see sslproto.h): tls_rsa_with_camellia_128_cbc_sha tls_dhe_dss_with_camellia_128_cbc_sha tls_dhe_rsa_with_camellia_128_cbc_sha tls_rsa_with_camellia_256_cbc_sha tls_dhe_dss_with_camellia_256_cbc_sha tls_dhe_rsa_with_camellia_256_cbc_sha note: the following tls cipher suites are declared but are not yet implemented: tls_dh_dss_with_camellia_128_cbc_sha tls_dh_rsa_with_camellia_128_cbc_sha tls_dh_anon_with_camellia_128_cbc_sha tls_dh_dss_with_camellia_256_cbc_sha tls_dh_rsa_with_camellia_256_cbc_sha tls_dh_anon_with_camellia_256_cbc_sha tls_ecdh_anon_with_null_sha tls_ecdh_anon_with_rc4_128_sha tls_ecdh_anon_with_3des_ede_cbc_sha tls_ecdh_anon_with_...
...And 2 more matches
NSS Tools ssltap
the options for the command are the following: -v print a version string for the tool.
...the following are well-known port numbers: http 80 https 443 smtp 25 ftp 21 imap 143 imaps 993 (imap over ssl) nntp 119 nntps 563 (nntp over ssl) examples you can use the ssl debugging tool to intercept any connection information.
...the simplest way to use the debugging tool is to execute the following command from a command shell: ssltap www.netscape.com:80 the program waits for an incoming connection on the default port 1924.
...And 2 more matches
Getting SpiderMonkey source code
downloading gzipped spidermonkey source code you can download gzipped spidermonkey source code from the following urls: http://ftp.mozilla.org/pub/spidermonkey/releases/ http://ftp.mozilla.org/pub/spidermonkey/prereleases/ here is a command-line example of downloading and unzipping spidermonkey source code version 59.0: mkdir mozilla cd mozilla wget http://ftp.mozilla.org/pub/spidermonkey/prereleases/59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell.
... the following command line downloads the entire mozilla repository, including the full change history and a lot of gecko and firefox source code that isn't part of spidermonkey.
... getting the latest spidermonkey source code from git the following command line downloads the entire mozilla repository, including the full change history and a lot of gecko and firefox source code that isn't part of spidermonkey.
...And 2 more matches
Hacking Tips
the backtrace contains in the following order, the stack depth, the interpreter frame pointer (see js/src/vm/stack.h, stackframe class) or (nil) if compiled with ionmonkey, the file and line number of the call location and under parentheses, the jsscript pointer and the jsbytecode pointer (pc) executed.
...7 0x7fffefbbc250 typein:2 (0x7fffef1231c0 @ 24) #25158 0x7fffefbbc1c8 typein:3 (0x7fffef1231c0 @ 47) #25159 0x7fffefbbc140 typein:2 (0x7fffef1231c0 @ 24) #25160 0x7fffefbbc0b8 typein:3 (0x7fffef1231c0 @ 47) #25161 0x7fffefbbc030 typein:5 (0x7fffef123280 @ 9) note, you can do the exact same exercise above using lldb (necessary on osx after apple removed gdb) by running lldb -f js then following the remaining steps.
...to work-around this issue you can use the recording feature of gdb, to step one instruction, and settle back to where you came from with the following set of gdb commands: (gdb) record full (gdb) si (gdb) record goto 0 (gdb) record stop if you have a core file, you can use the gdb unwinder the same way, or do everything from the command line as follow: $ gdb -ex 'enable unwinder .* spidermonkey' -ex 'bt 0' -ex 'thread apply all backtrace' -ex 'quit' out/dist/bin/js corefile the gdb unwinder is supposed to be loaded by dist/bin/js-gdb.py a...
...And 2 more matches
Shell global objects
console an object that has following property: log evaluate and print expressions to stdout.
...if options is given, it may have any of the following properties: samezoneas the compartment will be in the same zone as the given object (defaults to a new zone) invisibletodebugger the global will be invisible to the debugger (default false) principal if present, its value converted to a number must be an integer that fits in 32 bits; use that as the new compartment's principal.
...the following keys' string values will be used to determine whether the corresponding types may be serialized (value allow, the default) or not (value deny).
...And 2 more matches
XForms Accessibility
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 --enable-extensions=default,xforms,schema-validation how to test there are two approaches to test xforms accessibility.
... you can try the following link to test xforms accessibility: visual xforms elements in xhtml document at bugzilla.mozilla.org visual xforms elements in xul document at bugzilla.mozilla.org you can see xforms sample tests at mozilla xforms project there are set of tests at beaufour.dk w3c's xforms test at w3.org keyboard navigation issues navigation sequence though xforms spec declares navindex attribute to define the navigation sequence (see 1.0 specs or 1.1 specs) but rich schwerdtfeger (distinguished engineer, swg accessibility arc...
...it can have the following presentations: text - see the docs.
...And 2 more matches
Places utilities for JavaScript
utils.js is accessible at the following url: http://mxr.mozilla.org/mozilla-centr...ntent/utils.js this file includes utility functions used by a lot of the bookmarking, tagging, and annotation services that are built into firefox.
... return array of objects, each containing the following properties: name, flags, expires, mimetype, type, value getannotationsforitem() fetch all annotations for an item, including all properties of each annotation which would be required to recreate it.
... return type return array of objects, each containing the following properties: name, flags, expires, mimetype, type, value setannotationsforuri() annotate a uri with a batch of annotations.
...And 2 more matches
Setting up the Gecko SDK
the following four sections tell the developer how to download and organize the gecko sdk and create a new project in which components like weblock can be created.
...the sdk is available for windows, linux, and mac operating systems, and versions for other operating systems are being developed, and can be retrieved from as a single archive from the following platform-specific locations (need correction for last version (now 1.9.2.8).
... most of the changes you make in the following steps apply to all configurations of the project (both debug and optimized), so select "all configurations" from the settings for dropdown menu: on the c/c++ tab, select the preprocessor category.
...And 2 more matches
nsIFile
void appendrelativenativepath(in acstring relativefilepath); void appendrelativepath(in astring relativefilepath); nsifile clone(); boolean contains(in nsifile infile); void copyto(in nsifile newparentdir, in astring newname); void copytofollowinglinks(in nsifile newparentdir, in astring newname); void copytofollowinglinksnative(in nsifile newparentdir, in acstring newname); native code only!
... copytofollowinglinks() this method copies a source file to a new location if it does not already exist.
... void copytofollowinglinks( in nsifile newparentdir, in astring newname ); parameters newparentdir this parameter specifies the parent directory to copy the file into.
...And 2 more matches
MailNews fakeserver
a handler will contain the following methods: <caption> handler methods </caption> name arguments returns notes [command] rest of sent line server's response the name is normalized to be uppercase.
...the server presents the following api to the handler: <caption> server api </caption> name arguments returns description closesocket none nothing closes the socket and stops the test.
...the server provides the following api to xpcshell tests: <caption> nsmailserver xpcshell api </caption> name arguments returns description performtest none nothing runs until the test is forcibly aborted or stopped normally isstopped none if the server is stopped helper for performtest istestfinished none if the test is finished helper for performtest playtransaction none the transaction the transaction is an object wi...
...And 2 more matches
Mozilla
android-specific test suites there are several android-specific test suites that run on the firefox for android codebase: api change rules until further notice, the following rules govern api changes: application cache implementation overview this happens in nshttpchannel::opencacheentry().
... error codes returned by mozilla apis the following tables list errors that can occur when calling various mozilla apis.
... mozilla quirks mode behavior the following is a rough list of the differences that exist between mozilla's standards mode and quirks mode behavior.
...And 2 more matches
UI Tour - Firefox Developer Tools
the ui is split vertically into three panels source list pane source pane the contents of the third pane depend on the current state of the debugger and may include the following sections: toolbar watch expressions breakpoints call stack scopes xhr breakpoints event listener breakpoints dom mutation breakpoints source list pane the source list pane lists all the javascript source files loaded into the page, and enables you to select one to debug.
... for files, the following context menu options are available: copy source uri copies the full identifier of the file to the clipboard.
... for folders and groups, the following context menu options are available: collapse all collapses all subfolders of the item.
...And 2 more matches
Debugger.Memory - Firefox Developer Tools
accessor properties of the debugger.memory.prototype object ifdbg is a debugger instance, then <i>dbg</i>.memory is a debugger.memory instance, which inherits the following accessor properties from its prototype: trackingallocationsites a boolean value indicating whether this debugger.memory instance is capturing the javascript execution stack when each object is allocated.
...it has the following properties: collections the collections property’s value is an array.
...for each collection slice that occurred, there is an entry in the collections array with the following form: { "starttimestamp":timestamp, "endtimestamp":timestamp, } here the timestamp values are timestamps of the gc slice’s start and end events.
...And 2 more matches
about:debugging - Firefox Developer Tools
note: if the version of firefox on your remote device is more than one major version older than the version running on your computer, you may see a message like the following: in firefox 76 and above, the message can look like the following: see connection for firefox for android 68 for more information.
...when you do, it is added to the network locations list along with the devices, as shown below: this firefox the this firefox tab combines the features of extensions, tabs, and workers into a single tab with the following sections: temporary extensions displays a list of the extensions that you have loaded using the load temporary add-on button.
... you can use the following buttons: inspect loads the extension in the debugger.
...And 2 more matches
CanvasRenderingContext2D - Web APIs
drawing text the following methods draw text.
... line styles the following methods and properties control how lines are drawn.
... text styles the following properties control how text is laid out.
...And 2 more matches
HTMLElement - Web APIs
in addition, the following handlers are specific to htmlelement.
... working draft added the following properties: offsetparent, offsettop, offsetleft, offsetwidth, and offsetheight.
... living standard added the following properties: translate, itemscope, itemtype, itemid, itemref, itemprop, properties, and itemvalue.
...And 2 more matches
HTMLFormElement - Web APIs
you can then use any of the following syntaxes to get an individual form: document.forms[index] returns the form at the specified index into the array of forms.
... elements that are considered form controls the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms.
... living standard the following method has been added: requestautocomplete().
...And 2 more matches
HTMLImageElement - Web APIs
living standard the following properties have been added: srcset, currentsrc and sizes.
... the following properties are now obsolete: name, border, align, hspace, vspace, and longdesc.
... the following properties are now unsigned long, instead of long: height, and width.
...And 2 more matches
HTMLInputElement - Web APIs
when there's no selection, this returns the offset of the character immediately following the current text input cursor position.
... valueasnumber double: returns the value of the element, interpreted as one of the following, in order: a time value a number nan if conversion is impossible autocapitalize string: defines the capitalization behavior for user input.
... the following properties are now obsolete: align and usemap.
...And 2 more matches
HTMLSelectElement.add() - Web APIs
examples creating elements from scratch var sel = document.createelement("select"); var opt1 = document.createelement("option"); var opt2 = document.createelement("option"); opt1.value = "1"; opt1.text = "option: value 1"; opt2.value = "2"; opt2.text = "option: value 2"; sel.add(opt1, null); sel.add(opt2, null); /* produces the following, conceptually: <select> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> */ the before parameter is optional.
... so the following is accepted.
... append to an existing collection var sel = document.getelementbyid("existinglist"); var opt = document.createelement("option"); opt.value = "3"; opt.text = "option: value 3"; sel.add(opt, null); /* takes the existing following select object: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> and changes it to: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> */ the before parameter is optional.
...And 2 more matches
KeyboardEvent - Web APIs
constants the keyboardevent interface defines the following constants.
... keyboard locations the following constants identify which part of the keyboard the key event originates from.
... events the following events are based on the keyboardevent type.
...And 2 more matches
MediaDevices.getUserMedia() - Web APIs
the following requests both audio and video without any specific requirements: { audio: true, video: true } if true is specified for a media type, the resulting stream is required to have that type of track in it.
...the following expresses a preference for 1280x720 camera resolution: { audio: true, video: { width: 1280, height: 720 } } the browser will try to honour this, but may return other resolutions if an exact match is not available, or the user overrides it.
...the following demands a minimum resolution of 1280x720: { audio: true, video: { width: { min: 1280 }, height: { min: 720 } } } if no camera exists with this resolution or higher, then the returned promise will be rejected with overconstrainederror, and the user will not be prompted.
...And 2 more matches
Using the Notifications API - Web APIs
in its simplest form, we just include the following: notification.requestpermission().then(function(result) { console.log(result); }); this uses the promise-based version of the method.
...we did this using the following: function checknotificationpromise() { try { notification.requestpermission().then(); } catch(e) { return false; } return true; } we basically try to see if the .then() method is available on requestpermission().
... for example, in the to-do-list example we use the following snippet to create a notification when required (found inside the createnotification() function): var img = '/to-do-notifications/img/icon-128.png'; var text = 'hey!
...And 2 more matches
PaymentRequest.PaymentRequest() - Web APIs
each item in the array contains the following fields: supportedmethods for early implementations of the spec, this was a sequence of identifiers for payment methods that the merchant website accepts.
...this parameter contains the following fields: total the total amount of the payment request.
...this parameter contains the following fields: additionaldisplayitems an array of items to be appended to the details.displayitems property.
...And 2 more matches
Using the User Timing API - Web APIs
the method takes one argument, the name of the mark, as shown in the following example.
...the following examples shows how to use each of these methods (performance.getentries(), performance.getentriesbytype(entrytype), and performance.getentriesbyname(name, entrytype) ) to retrieve one or more marks.
...the following example demostrates both uses of this method.
...And 2 more matches
WebGL best practices - Web APIs
in practice, effectively all systems support at least the following: max_cube_map_texture_size: 4096 max_renderbuffer_size: 4096 max_texture_size: 4096 max_viewport_dims: [4096,4096] max_vertex_texture_image_units: 4 max_texture_image_units: 8 max_combined_texture_image_units: 8 max_vertex_attribs: 16 max_varying_vectors: 8 max_vertex_uniform_vectors: 128 max_fragment_uniform_vectors: 64 aliased_point_size_range: [...
... for example, it is possible for the following to never complete without context loss: sync = glfencesync(gl_sync_gpu_commands_complete, 0); glclientwaitsync(sync, 0, gl_timeout_ignored); webgl doesn't have a swapbuffers call by default, so a flush can help fill the gap, as well.
...the essl3 spec says this under "error handling": the implementation should report errors as early a possible but in any case must satisfy the following: all lexical, grammatical and semantic errors must have been detected following a call to gllinkprogram errors due to mismatch between the vertex and fragment shader (link errors) must have been detected following a call to gllinkprogram errors due to exceeding resource limits must have been detected following any draw call or a call to glvalidateprogram a call to glvalidateprogram must rep...
...And 2 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
webvtt body the structure of a webvtt consists of the following components, some of them optional, in this order: an optional byte order mark (bom).
... example 12 - karaoke style text 1 00:16.500 --> 00:18.500 when the moon <00:17.500>hits your eye 1 00:00:18.500 --> 00:00:20.500 like a <00:19.000>big-a <00:19.500>pizza <00:20.000>pie 1 00:00:20.500 --> 00:00:21.500 that's <00:00:21.000>amore the following tags are the html tags allowed in a cue and require opening and closing tags (e.g., <b>text</b>).
...following interface can be used to expose webvtt cues in dom api: enum autokeyword { "auto" }; enum directionsetting { "" /* horizontal */, "rl", "lr" }; enum linealignsetting { "start", "center", "end" }; enum positionalignsetting { "line-left", "center", "line-right", "auto" }; enum alignsetting { "start", "center", "end", "left", "right" }; [constructor(double starttime, double endtime, domstring text)...
...And 2 more matches
Inputs and input sources - Web APIs
gaze tracking (following the movements of the eye to choose targets).
... for example, the generic-trigger-squeeze-touchpad profile name can be used to locate the following json profile data by locating the profileid field that has the value generic-trigger-squeeze-touchpad.
... when the user points a device along a target ray in your 3d space and then triggers a select action, the following events are sent to the active xrsession: a selectstart event, indicating that the user has performed the activity that begins the primary action.
...And 2 more matches
Using XMLHttpRequest - Web APIs
some cases where dealing with non-text response types may involve some manipulation and analysis are outlined in the following sections.
...if you are using the post method the server will receive a string similar to one of the following three examples, depending on the encoding type you are using: method: post; encoding type: application/x-www-form-urlencoded (default): content-type: application/x-www-form-urlencoded foo=bar&baz=the+first+line.%0d%0athe+second+line.%0d%0a method: post; encoding type: text/plain: content-type: text/plain foo=bar baz=the first 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.
...And 2 more matches
Cognitive accessibility - Accessibility
all of the following guidelines help more than just people with cognitive disabilities.
... for example, being able to extend the expiration time on an application requiring an authentication code sent to a mobile device via text message helps with the following scenarios: people with attention or anxiety disorders.
...this is especially important and helpful for people with short attention spans who may become confused when following a long series of navigation steps.
...And 2 more matches
Getting Started - Developer guides
the two major features of ajax allow you to do the following: make requests to the server without reloading the page receive and work with data from the server step 1 – how to make an http request in order to make an http request to the server with javascript, you need an instance of an object with the necessary functionality.
...for example, use the following before calling send() for form data sent as a query string: httprequest.setrequestheader('content-type', 'application/x-www-form-urlencoded'); step 2 – handling the server response when you sent the request, you provided the name of a javascript function to handle the response: httprequest.onreadystatechange = nameofthefunction; what should this function do?
...in the following example, we differentiate between a successful and unsuccessful ajax call by checking for a 200 ok response code.
...And 2 more matches
Standard metadata names - HTML: Hypertext Markup Language
WebHTMLElementmetaname
standard metadata names defined in the html specification the html specification defines the following set of standard metadata names: application-name: the name of the application running in the web page.
... standard metadata names defined in other specifications the css color adjustment specification defines the following metadata name: color-scheme: specifies one or more color schemes with which the document is compatible.
... the value of the content property for color-scheme may be one of the following: normal the document is unaware of color schemes and should simply be rendered using the default color palette.
...And 2 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
javascript has a boolean type, with possible values true and false (both of which are keywords.) any value can be converted to a boolean according to the following rules: false, 0, empty strings (""), nan, null, and undefined all become false.
... let a; let name = 'simon'; the following is an example of scope with a variable declared with let: // myletvariable is *not* visible out here for (let myletvariable = 0; myletvariable < 5; myletvariable++) { // myletvariable is only visible in here } // myletvariable is *not* visible out here const allows you to declare variables whose values are never intended to change.
... details: { color: 'orange', size: 12 } }; attribute access can be chained together: obj.details.color; // orange obj['details']['size']; // 12 the following example creates an object prototype(person) and an instance of that prototype(you).
...And 2 more matches
Regular expressions - JavaScript
the following pages provide lists of the different special characters that fit into each category, along with descriptions and examples.
... if you want to look at all the special characters that can be used in regular expressions in a single table, see the following: special characters in regular expressions.
... in the following example, the script uses the exec() method to find a match in a string.
...And 2 more matches
Array.prototype.filter() - JavaScript
you can work around this by inserting the following code at the beginning of your scripts, allowing use of filter() in ecma-262 implementations which do not natively support it.
... } } } } else{ while (++i !== len){ // checks to see if the key was set if (i in this){ kvalue = t[i]; if (func.call(thisarg, t[i], i, t)){ res[c++] = kvalue; } } } } res.length = c; // shrink down array to proper size return res; }; } examples filtering out all small values the following example uses filter() to create a filtered array that has all elements with values less than 10 removed.
... function isbigenough(value) { return value >= 10 } let filtered = [12, 5, 8, 130, 44].filter(isbigenough) // filtered is [12, 130, 44] find all prime numbers in an array the following example returns all prime numbers in the array: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log(array.filter(isprime)); // [2, 3, 5, 7, 11, 13] filtering invalid entries from json the following example uses filter() to create a filtered json of all elements with non-zero, numeric id.
...And 2 more matches
Intl.DateTimeFormat() constructor - JavaScript
the following unicode extension keys are allowed: nu numbering system.
... options optional an object with some or all of the following properties: datestyle the date formatting style to use when calling format().
...see the following paragraphs for information about the use of this property.
...And 2 more matches
handler.construct() - JavaScript
syntax const p = new proxy(target, { construct: function(target, argumentslist, newtarget) { } }); parameters the following parameters are passed to the construct() method.
... interceptions this trap can intercept these operations: new proxy(...args) reflect.construct() invariants if the following invariants are violated, the proxy will throw a typeerror: the result must be an object.
... examples trapping the new operator the following code traps the new operator.
...And 2 more matches
String.prototype.replace() - JavaScript
specifying a string as a parameter the replacement string can include the following special replacement patterns: pattern inserts $$ inserts a "$".
... (the exact number of arguments depends on whether the first argument is a regexp object—and, if so, how many parenthesized submatches it specifies.) the following example will set newstring to 'abc - 12345 - #$*%': function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(' - '); } let newstring = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newstring); // abc - 12345 - #$*% examples defining the regular expression in replace() in the following...
...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'.
...And 2 more matches
eval() - JavaScript
in the following example, the string constructor is specified and eval() returns a string object rather than evaluating the string.
...but, in the code using eval(), the browser cannot assume this since what if your code looked like the following: function date(n){ return ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"][n%7 || 0]; } function loosejsonparse(obj){ return eval("(" + obj + ")"); } console.log(loosejsonparse( "{a:(4-1), b:function(){}, c:new date()}" )) thus, in the eval() version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local va...
...consider the following example where the property of the object to be accessed is not known until the code is executed.
...And 2 more matches
this - JavaScript
since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.
... function f1() { return this; } // in a browser: f1() === window; // true // in node: f1() === globalthis; // true in strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example: function f2() { 'use strict'; // see strict mode return this; } f2() === undefined; // true in the second example, this should be undefined, because f2 was called directly and not as a method or property of an object (e.g.
...calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the inherited class: this = new base(); warning: referring to this before calling super() will throw an error.
...And 2 more matches
async function - JavaScript
for example, the following: async function foo() { return 1 } ...is equivalent to: function foo() { return promise.resolve(1) } the body of an async function can be thought of as being split by zero or more await expressions.
... in the following example, we successively await two promises.
... for example, in the following code an unhandled promise rejection error will be thrown, even if a .catch handler has been configured further along the promise chain.
...And 2 more matches
The "codecs" parameter in common media types - Web media technologies
both video and audio tracks can be described using the codecs parameter with the following mime types: base mime types supporting the iso bmff codecs parameter mime type description audio/3gpp 3gp audio (rfc 3839: mime type registrations for 3rd generation partnership project (3gp) multimedia files) video/3gpp 3gp video (rfc 3839: mime type registrations for 3rd generation partnership project (3gp) multimedia files) audio/3gp2 3gp2 ...
... avc profiles the following are the avc profiles and their profile numbers for use in the codecs parameter, as well as the value to specify for the constraints component, cc.
...each of these components is described in the following table.
...And 2 more matches
Mobile first - Progressive web apps (PWAs)
i installed the volo automation tool by running the following on the command line sudo npm install -g volo (you'll also need to get node.js too if you don't already have it) i then created my sample project using volo create myapp mozilla/mortar-app-stub this creates a sample project inside a directory called myapp.
...i had to make sure both of these were not direct children of the <article>, otherwise the following would not work: #bottom, #top { font-size: 0.8em; position:absolute; right: 1em; text-decoration: none; } #top { color: white; top: 0.5em; } #bottom { bottom: 0.5em; } i also set their parents to be positioned relatively, so they would become the positioning contexts of the absolutely positioned elements (you don't want them to be positioned relative to the <body> element.) add...
...to create something more suitable for desktop, i put in the following media queries: @media (min-width: 480px) { #bottom, #top { display: none; } article, nav { display: block; } nav ul { text-align: center; } nav li { display: inline; } nav li a { border-right: 1px solid #ad66d5; border-bottom: none; display: inline-block; padding: 0 5px; font-size: 1.6em; } nav li:last-child a { border-right: none; } } @media (min-width: 600px) { html { background: #eee; height: 100%; } body { width: 600px; height: inherit; margin: 0 auto; background: url(../img/firefo...
...And 2 more matches
stroke-linecap - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <path>, <polyline>, <line>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="0 0 6 6" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the (default) "butt" value --> <line x1="1" y1="1" x2="5" y2="1" stroke="black" stroke-linecap="butt" /> <!-- effect of the "round" value --> <line x1="1" y1="3" x2="5" y2="3" stroke="black" stroke-linecap="round" /> <!-- effect of the "square" value...
... --> <line x1="1" y1="5" x2="5" y2="5" stroke="black" stroke-linecap="square" /> <!-- the following pink lines highlight the position of the path for each stroke --> <path d="m1,1 h4 m1,3 h4 m1,5 h4" stroke="pink" stroke-width="0.025" /> </svg> usage notes value butt | round | square default value butt animatable yes butt the butt value indicates that the stroke for each subpath does not extend beyond its two endpoints.
... example html,body,svg { height:100% } <svg viewbox="0 0 6 4" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "butt" value --> <path d="m1,1 h4" stroke="black" stroke-linecap="butt" /> <!-- effect of the "butt" value on a zero length path --> <path d="m3,3 h0" stroke="black" stroke-linecap="butt" /> <!-- the following pink lines highlight the position of the path for each stroke --> <path d="m1,1 h4" stroke="pink" stroke-width="0.025" /> <circle cx="1" cy="1" r="0.05" fill="pink" /> <circle cx="5" cy="1" r="0.05" fill="pink" /> <circle cx="3" cy="3" r="0.05" fill="pink" /> </svg> round the round value indicates that at the end of each subpath the stroke will be extended by a half circle with a...
...And 2 more matches
XPath snippets - XPath
node-specific evaluator function the following custom utility function can be used to evaluate xpath expressions on given xml nodes.
...scripts in a web document which might be accessed by edge or internet explorer users should replace the call to new xpathevaluator() with the following fragment: // xpathevaluator is implemented on objects that implement document var xpe = anode.ownerdocument || anode; in that case the creation of the xpathnsresolver can be simplified as: var nsresolver = xpe.creatensresolver(xpe.documentelement); note however that creatensresolver should only be used if you are sure the namespace prefixes in the xpath expression match those in the d...
... sample usage assume we have the following xml document (see also how to create a dom tree and parsing and serializing xml): example: an xml document to use with the custom evaluatexpath() utility function <?xml version="1.0"?> <people> <person first-name="eric" middle-initial="h" last-name="jung"> <address street="321 south st" city="denver" state="co" country="usa"/> <address street="123 main st" city="arlington" state="ma"...
...And 2 more matches
Private Properties - Archive of obsolete content
consider the following example: function point(x, y) { this._x = x; this._y = y; } the properties _x and _y are intended to be private, and should only be accessed by member functions.
...before explaining how weakmaps work, the following looks at how ordinary objects can be used as hash maps, by creating a simple image cache: let images = {}; function getimage(name) { let image = images[name]; if (!image) { image = loadimage(name); images[name] = image; } return image; } now suppose there's a need to associate a thumbnail with each image.
...a weakmap is very similar to an ordinary hash map, but differs from it in two crucial ways: it can use ordinary objects as keys it does not maintain a strong reference to its values to understand how weakmaps are used in practice, the following rewrites the thumbnail cache using a weakmap: let thumbnails = new weakmap(); function getthumbnail(image) { let thumbnail = thumbnails.get(image); if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails.set(image, thumbnail); } return thumbnail; } this version suffers from none of the problems we mentioned earlier.
...to illustrate this, the following reimplements the class point using namespaces: const { ns } = require("sdk/core/namespace"); var internal = ns(); function point(x, y) { internal(this).x = x; internal(this).y = y; } point.prototype.getx = function () { return internal(this).x; }; point.prototype.setx = function (x) { internal(this).x = x; }; point.prototype.gety = function () { return internal(this).y; ...
panel - Archive of obsolete content
the following add-on adds a button which displays a panel when clicked.
... the position object has one or more of the following properties: top, right, bottom and left.
...this may take one of the following values: "start": load content scripts immediately after the document element for the panel is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the panel has been loaded, ...
...this may have one of the following values: "start": load content scripts immediately after the document element for the panel is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the panel has been loaded, at the time the ...
passwords - Archive of obsolete content
they contain the following properties: username the username.
... it contains the following properties: username the username.
... so: given a form at http://www.example.com/login with the following html: <form action="http://login.example.com/foo/authenticate.cgi"> <div>please log in.</div> <label>username:</label> <input type="text" name="uname"> <label>password:</label> <input type="password" name="pword"> </form> the corresponding values for the credential (excluding username and password) should be: url: "http://www.example.com" formsubmiturl: "http://logi...
...they contain the following properties: username the username.
ui/sidebar - Archive of obsolete content
events attach this event is emitted when a worker is attached to a sidebar, as a result of any of the following: calling the sidebar's show() method, when the sidebar is not shown in the currently active window changing the sidebar's url property the user switching the sidebar on using the "sidebar" submenu in firefox, when the sidebar is not shown in the currently active window the user opening a new window from a window that has the sidebar showing it is passed a worker as an argument, which defi...
... detach this event is emitted when a worker is detached from a sidebar, as a result of either of the following: calling the sidebar's hide() method, when the sidebar is being shown in the currently active window the user switching the sidebar off using the "sidebar" submenu in firefox, when the sidebar is being shown in the currently active window the detach listener receives a worker object as a parameter.
...er(worker) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: require("sdk/self").data.url("sidebar.html"), onattach: attachworker, ondetach: detachworker }); show this event is emitted when the sidebar is shown, as a result of any of the following: calling the sidebar's show() method, when the sidebar is not shown in the currently active window changing the sidebar's url property the user switching the sidebar on using the "sidebar" submenu in firefox, when the sidebar is not shown in the currently active window the user opening a new window from a window that has the sidebar showing hide this event is emitted when the sidebar is ...
...hidden, as a result of either of the following: calling the sidebar's hide() method, when the sidebar is being shown in the currently active window the user switching the sidebar off using the "sidebar" submenu in firefox, when the sidebar is being shown in the currently active window ...
Enhanced Extension Installation - Archive of obsolete content
c:\program files\mozilla firefox\extensions extension metadata the extension system stores metadata in both of the two locations, in the following files: <location>/extensions/extensions.rdf - an xml/rdf datasource listing all the extensions installed at that location.
... extension metadata the following files are now used to hold metadata: <profile>/extensions.ini -active items this file contains a list of active extension directories (i.e.
...the following information is stored for each entry: the persistent descriptor of the path where the item lives.
...the startup process discovered the .autoreg file, before pending operations are finalized the extension system reads the extensions-startup.manifest and scans all of the install locations looking for items that match the following criteria: item in install location is not listed in startup manifest (new item being installed by just appearing in the install location).
Install Manifests - Archive of obsolete content
id the id of the extension, which must be one of the following: guid (firefox 1.0) a string formatted like so: extensionname@example.org the latter format is significantly easier to generate and manipulate.
... <em:localized> <description> <em:locale>de-de</em:locale> <em:name>tab sidebar</em:name> <em:description>zeigt in einer sidebar vorschaubilder der inhalte aller offenen tabs an.</em:description> </description> </em:localized> the following properties which are described elsewhere in this page can be included in the localized property: name description creator homepageurl developer translator contributor more documentation can be found at localizing extension descriptions.
...if an extension includes the following then it must request unpacking: binary xpcom components plugins search plugins dlls loaded with ctypes dictionaries window icons examples <description about="urn:mozilla:install-manifest"> <em:id>extension@mysite.com</em:id> <em:unpack>true</em:unpack> ...
... the add-on manager will substitute the following values into this url in case you wish to generate the response rdf dynamically, such as using php or cgi: %req_version% the version of the request.
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
in the following you will find a brief description how to do so; a more detailed one can be found under setting up an extension development environment.
...if you keep in mind the following three points at the very least, the next section, developing a simple extension, should help flesh out your understanding.
...in the interest of space, i’m not including all the code here, but you can download it from the following url: fixme: include code from xuldev: translate it and attach it to the chapter document init method the init method is as shown in listing 17.
...the following all assumes that you’ve disabled the xul cache as discussed in the section “setting up your development environment”.
Setting Up a Development Environment - Archive of obsolete content
run the following command: make that's it.
... you can clean up the bin directory by just running the following command (again, from the src directory): make clean you can also run these commands from komodo.
...long story short, if you want to run it from a command line, you need to run: export ostype; make install and in the command in komodo, you should enter the following: bash -c "export ostype; make install" the export command won't work correctly unless you use "bash -c".
...follow the instructions, and add something like the following to your makefile: # the directory where the signature sources are located.
Session store API - Archive of obsolete content
after that, the following steps are taken for each tab being restored: either an existing tab is reused or a new tab is created.
... saving a value with a tab the following code will attach a key/value pair to a tab, so that when the tab is restored, that pair is still associated with it.
... fetching a saved value you can fetch a value associated with a tab at any time (whether the tab is in the process of being restored or not), using code similar to the following: var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var retrieveddata = ss.gettabvalue(currenttab, "key-name-here"); after this code executes, the variable retrieveddata contains the value saved for the key "key-name-here".
... deleting a value associated with a tab to delete a value from a tab, you can use code similar to the following: var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; ss.deletetabvalue(currenttab, "key-name-here"); remarks the window value save and restore functions work exactly like the tab-based functions by similar names.
Case Sensitivity in class and id Names - Archive of obsolete content
(for a detailed explanation of what html 4.01 says, see the following section, "why so case-sensitive?") the only way to avoid this particular problem is to make sure that your class and id names have consistent case throughout the entire document, and with respect to your css and javascript.
...in section 7.5.2, which defines class and ids, we find the following text: id = name [cs] this attribute assigns a name to an element.
...thus, the mozilla team, committed to following open standards as closely as possible, implemented both class and id names as case-sensitive values.
...an "illegal" example is given in the specification, preceded by the text: "the following example is illegal with respect to uniqueness since the two names are the same except for case." <p><a name="xxx">...</a> <p><a name="xxx">...</a> we could freely substitute id for name and the point would be the same, since name and id share the same name space (see section 12.2.3).
MMgc - Archive of obsolete content
finalizers may not perform any of the following actions: fire any write barriers dereference a pointer to any gc object, including member variables (except see below about rcobject references) allocate any gc memory (gc::alloc), explicitly free gc memory (gc::free) change the set of gc roots (create a gcroot object or derivative) cause itself to become reachable if a finalized object holds a reference to an rcobject, it may safely call decre...
...the following flash animation illustrates the working of a mark/sweep collector: (temporarily not working) <gflash>600 300 gc.swf</gflash> one pass the mark sweep algorithm described above decomposes into clearmarks/mark/finalize/sweep.
...illustration of write barriers the following flash animation demonstrates how a write barrier works.
...this approach was not chosen for the following reasons: coordinating the marking thread and the main thread will require locking and may suffer due to lock overhead/contention supporting mac classic's cooperative threads makes this approach harder flash's frame based architecture gives us a very natural place to do this work we have better control over how much time is spent marking without threads when smp systems become more prevalent it ...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
in the simplest case, we might add a style like this: td img {display: block;} consider this rule when applied to the following markup: <table cellspacing="0" cellpadding="0" border="0" width="500"> <tr><td><img src="nav1.gif"><img src="nav2.gif"><img src="nav3.gif"><img src="nav4.gif"><img src="nav5.gif"></td></tr> <tr><td style="background: red;"> <img src="smallred.gif" height="1" width="1"></td></tr> <tr><td> <p style="margin: 0.5em;">this is text in another cell of the table.
...thus you might have: tr.decoration img {display: block;} ...along with the following change in the markup: <tr class="decoration"><td style="background: red;"> <img src="smallred.gif" height="1" width="1"> </td></tr> the result is that of only making the spacer gif block-level, thus leaving the other images alone.
...for example, you could try the following: td img {vertical-align: bottom;} this will cause the bottom edges of the images to be aligned with the bottom of the line box, instead of the baseline.
...should this property be adopted, then any browser supporting it could emulate traditional "shrinkwrap" behavior without risking other layout upset with the following rule: td {line-box-contain: font replaced;} /* proposed for css3 */ there are other possible fixes contained within the current css3 working drafts, such as line-height-policy.
Using Dehydra - Archive of obsolete content
example: printing the location of type declarations save the following c++ code dumptypes.cc: typedef int myint; struct foo { int i; char *c; }; save the following analysis script dumptypes.js: function process_type(t) { print("type found: " + t.name + " location: " + t.loc); } function input_end() { print("hello, world!"); } compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/dumptypes.js -o/dev/null -c dumptypes.cc note:for g++4.5 and up use -fplugin-arg-gcc_dehydra-script= rather than -fplugin-arg it should print the following results: type found: ...
... see documentation for: process_type, input_end, print, .loc property example: using attributes to mark a class as "final" save the following code as final.cc: // this class should not be subclassed!
... class __attribute__((user("final"))) myclass { }; // this subclass should be an error class subclass : public myclass { }; save the following analysis script final.js: /** * helper function: returns true if a class is marked with the "final" attribute.
... */ function isfinal(c) { if (!c.attributes) return false; for each (let a in c.attributes) if (a.name == 'user' && a.value == 'final') return true; return false; } function process_type(t) { if (t.bases) for each (let base in t.bases) if (isfinal(base.type)) error("class " + t.name + " extends final class " + base.type.name, t.loc); } compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/final.js -o/dev/null -c final.cc it should print the following results and return with an error code: final.cc:8: error: class subclass extends final class myclass see documentation for: process_type, error, .bases property, .attributes property ...
Mozilla Application Framework in Detail - Archive of obsolete content
the following architectural diagram depicts necko and its interaction with subsystems: necko is powerful, stable and robust, with current development focused on performance and standards-compliance.
...it is a development environment that provides the following features for the cross-platform software developer: component management file abstraction object message passing memory management this component object model makes virtually all of the functionality of gecko available as a series of components, or reusable cross-platform libraries, that can be accessed from the browser or scripted from any mozilla application.
...the xpinstall api makes the following functionality available as high-level javascript objects: an install trigger that initiates installations windows registry access mozilla registration interfaces for registering new mozilla software facilities for detecting and maintaining application versions high-level objects for manipulating local directories and files complete reference documentation, including useful example installa...
...tions the following snippet from an xpinstall installation gives you some idea about how easy it is to write cross-platform installations that use the mozilla browser: // register chrome registerchrome(package | delayed_chrome, getfolder("chrome","xmlterm.jar"), "content/xmlterm/"); registerchrome(skin | delayed_chrome, getfolder("chrome","xmlterm.jar"), "skin/modern/xmlterm/"); registerchrome(locale | delayed_chrome, getfolder("chrome","xmlterm.jar"), "locale/xmlterm/"); if (getlasterror() == success) performinstall(); else { alert("error detected: "+getlasterror()); cancelinstall(); } other features a resource description framework (rdf) parser with support for creating rdf graphs programmatically or by parsing files, compositing multiple sources into a single rdf graph, querying a...
Table Layout Strategy - Archive of obsolete content
in the following the basic table layout strategy is discussed.
... the words the table layout is width oriented and knows the following widths: minimum content width - min the minimum width that is required to layout the content, all linebreak possibilities will be used percent width - pct the cell width specified in percent, fixed width - fix the cell width specified as px, mm etc., proportional width - prop the cell width specified via 1*, 2* etc.
... min_con des_con fix min_adj des_adj fix_adj pct pct_adj min_pro final the width parameter have the following meaning: #define width_not_set -1 #define num_widths 10 #define num_major_widths 3 // min, des, fix #define min_con 0 // minimum width required of the content + padding #define des_con 1 // desired width of the content + padding #define fix 2 // fixed width either from the content or cell, col, etc.
... special cases note: the following examples are not shown correctly due to technical constraints on wiki content.
Tamarin-central rev 703:2cee46be9ce0 - Archive of obsolete content
testing summary acceptance tests have passed on the following supported platforms: * windows, 32 & 64 bit * mac ox x ppc & intel, 32 bit * linux, 32 bit * windows mobile arm version asc-4200 of the actionscript compiler was used for all tests.
... performance testsuite time metric the following is a comparison of the current tamarin-central (tc-703) versus the prior build (tc-700) as well as current against the vm in flash player 10.
...% fastertc-703 vs flash10: 148.7% fastertc-703 vs tc-700: 0.1% slowertc-703 vs flash10: 5.2% faster linux (ubuntu linux, 2.13 ghz dual core)tc-703 vs tc-700: 6.0% fastertc-703 vs flash10: 1.7% fastertc-703 vs tc-700: 89.5% fastertc-703 vs flash10: 182.0% fastertc-703 vs tc-700: 6.1% fastertc-703 vs flash10: 1.4% faster performance testuite memory metric the following is a comparison of the current tamarin-central (tc-703) versus the prior build (tc-700).
...14.6% largertc-703 vs tc-700: 16.4% largertc-703 vs tc-663: 2.1% larger windows (xp pro, 2.13ghz dual core)tc-703 vs tc-700: 3.2% largertc-703 vs tc-663: 7.6% largertc-703 vs tc-700: 3.9% largertc-703 vs tc-663: 12.4% largertc-703 vs tc-700: 3.3% largertc-703 vs tc-663: 21.4% larger linux (ubuntu linux, 2.13 ghz dual core)n/an/an/a vm code size the following is a comparison of the current tamarin-central compiled size (tc-703) versus the prior build (tc-700) as well as the current build against the vm in flash player 10.
execute - Archive of obsolete content
method of install object syntax int execute ( string xpisourcepath [, boolean blocking]); int execute ( string xpisourcepath, string args [, boolean blocking]); parameters the execute method has the following parameters: xpisourcepath the pathname of the file to extract and execute.
...the following line, for example, passes the "-c" command-line parameter to the executable: err = file.execute(myfile, "-c", true); when you want to pass more than one parameter to the executable itself, however, you must format the args string in a particular way so that the parameters can be broken up and passed separately as required.
...the following parsing rules apply: double quotes are treated as quotes; single quotes are ignored by the executable but legal in the execute() method.
... this means that in order to pass three command-line arguments (-c, -d, and -s) to the executable, you should format the args string as follows: err = file.execute(myfile, '"-c""-d""-s"', true); //technically, given the rules above, you could also pass the same //arguments with the following line, but the result is much less //readable: err = file.execute(myfile, "\"-c\"\"-d\"\"-s\"", true); also see the note about binaries on the macintosh platform in addfile.
A XUL Bestiary - Archive of obsolete content
the chrome url, which appears in place of the http url in pointers like the following global skin processing instruction: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> specifies a chrome to be loaded by the gecko rendering engine.
...so the following structure obtains: navigator/ content/ default/ navigator.xul ...
... locale/ us-en/ navigator.dtd to load chrome information stored in a new package directory like this, you can use the following chrome url, chrome://navigator/skin/mynewskin/newskin.css which in turn loads the graphics in that subdirectory as needed.
...for a widget like the menu that appears in the following example, menu is the element and both value and the id are attributes.
Extensions - Archive of obsolete content
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.
...for example, the following may be used to insert a command just after the 'select all' command: <popup id="contentareacontextmenu"> <menuitem label="select links" oncommand="thumbnails.selectalllinks();" insertafter="context-selectall"/> </popup> see firefox context menu for a list of the ids of the items found on the firefox context menu.
...the following are the most common properties that you can check.
... in the following example, the menuitem is hidden unless the target is an image or a link.
Panels - Archive of obsolete content
for example, the following panel displays a textbox for entering a name.
...for other types of elements, you need to use a different technique as in the following example.
...for instance, to attach the popup defined above to a label, use the following code: <label value="search" popup="search-panel"/> the result is a search button which opens a panel for entering the search term.
...for example, the following would open a panel underneath a button: panel.openpopup(button, "after_start", 0, 0, false, false); likewise, the openpopupatscreen method will open a panel at a specific screen position.
Positioning - Archive of obsolete content
the following assumes a left to right user interface.
... the following table shows the valid values, corresponding explicit (ie, 2 word) alignment values and an example of the alignment.
...for example, the following might be used with the above example to open the popup: menupopup.openpopup(label, "end_before", 0, 0, false, false); note that the position has been set to 'end_before', as above.
...in the following example, the menupopup has a 2ex margin above it, so when opened, the popup will be placed a distance of 2ex below the bottom of the button.
Adding Methods to XBL-defined Elements - Archive of obsolete content
for example, the following javascript function would be written as an xbl method like so: function getmaximum(num1,num2) { if (num1 <= num2) return num2; else return num1; } xbl: <method name="getmaximum"> <parameter name="num1"/> <parameter name="num2"/> <body> if (num1 &lt;= num2) return num2; else return num1; </body> </method> this function, getmaximum, returns the largest of the values, each pa...
...for example, the following code will probably fail: var element = document.createelement("my_element"); element.getmaximum() // this will fail by the way, it is safe to call methods from the constructor, other methods on the object and event handlers.
... the following example creates a row of buttons: <binding id="buttonrow"> <content> <button label="yes"/> <button label="no"/> <button label="sort of"/> </content> </binding> to refer to each button, you can use the getanonymousnodes() function, passing it a reference to the element the binding is bound to as the parameter.
...for example, we could move the show and hide buttons into the xbl file and do the following: example 1: source <binding id="labeledbutton"> <content> <xul:label xbl:inherits="value=title"/> <xul:label xbl:inherits="value"/> <xul:button label="show" oncommand="document.getbindingparent(this).showtitle(true);"/> <xul:button label="hide" oncommand="document.getbindingparent(this).showtitle(false);"/> </content> <implementation> <method name="showtitle"> <p...
Adding Properties to XBL-defined Elements - Archive of obsolete content
for example, the following field is given a default value equal to the current time: <field name="currenttime"> new date().gettime(); </field> properties sometimes you will want to validate the data that is assigned to a property.
...the following decribes what happens in a typical case: there are two elements, one called 'banana' and the other 'orange'.
...when the following line of script is executed: banana.size = orange.size; the onget script is called for the size property of the orange.
...the following example maps a property to an attribute on an element.
Creating a Skin - Archive of obsolete content
creating a custom skin package to create a skin, do the following: (if you are using firefox 1.5 or later, see manifest files instead of below) create a directory somewhere where you want to place the skin files.
... add a line to the file 'chrome/installed-chrome.txt of the following form: skin,install,url,file:///stuff/blueswayedshoes/ where the last part points to the directory you created.
... the following style rules added to findfile.css will cause the changes shown in the accompanying image.
...if following the example in this section, just copy the files to your new skin and change the urls accordingly.
Element Positioning - Archive of obsolete content
the following css properties can be used.
...the following example demonstrates this: example 2 : source view <window orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <hbox> <button label="yes" flex="1"/> <button label="no"/> <button label="i really don't know one way or the other"/> </hbox> </window> the window will initially appear like in the image earlier.
...you can use the following values: start this positions elements at the left edge for horizontal boxes and at the top edge for vertical boxes.
...the following shows this attribute in use: example 6: source view <button label="push me please!" crop="right" flex="1"/> notice how the text on the button has had the right side of it cropped after the window is made smaller.
tree - Archive of obsolete content
ArchiveMozillaXULtree
(default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column.
... interfaces nsiaccessibleprovider, nsidomxultreeelement, nsidomxulmultiselectcontrolelement script examples to have alternating colors for each row, use the style rules like the following: treechildren::-moz-tree-row(selected) { background-color: #ffffaa; } treechildren::-moz-tree-row(odd) { background-color: #eeeeee; } treechildren::-moz-tree-row(odd, selected) { background-color: #ffffaa; } treechildren::-moz-tree-cell-text(selected) { color: #000000; } treechildren::-moz-tree-cell-text(odd, selected) { color: #000000; } if using a content tree view, use the following to get ...
...the value of the id attribute for each of the selected rows of a tree: var idlist = []; var rangecount = tree.view.selection.getrangecount(); for (var i = 0; i < rangecount; i++) { var start = {}; var end = {}; tree.view.selection.getrangeat(i, start, end); for (var c = start.value; c <= end.value; c++) { idlist.push(tree.view.getitematindex(c).firstchild.id); } } the following returns a array of the indicies of the rows where the value is checked in a checkbox type column: function getcellchecked(tree, columnid) { var arr = []; var column = tree.columns.getnamedcolumn(columnid); for (var i = 0; i < tree.view.rowcount; i++) { if (tree.view.getcellvalue(i, column) == 'true') arr.push(i); } return arr; } to get the text value for a specific column (for example ...
...column 'age') from the currently focused row in the tree: var t = document.getelementbyid('mytree'); document.title = t.view.getcelltext(t.currentindex,t.columns.getnamedcolumn('age')); to select the checkbox and display the cell's text value, you can use code like the following.
window - Archive of obsolete content
it can have one of the following values: maximized the window is maximized, and occupies the full size of the screen.
...a filename following the system keyword in a doctype declaration may silently fail to load and the only error message will be an undefined entity error on the next xul element.
... to add a favicon to the address bar and browser tab (ie dialog is not a popup) then use the following code snippet to use the html namespace and link.
...xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> <!-- icon from chrome --> <html:link rel="icon" href="chrome://myextension/content/path/to/favicon.png"/> <!-- from a remote site --> <html:link rel="icon" href="http://www.mozilla.org/favicon.ico"/> since firefox 3.6 the above listed code does not work correctly - it produces the following message: "warning: xul box for box element contained an inline link child, forcing all its children to be wrapped in a block".
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.1 .
...the following directory is recommended: /opt/xulrunner/1.8.0.1 .
... windows run the following command from the start menu -> run or from a command prompt: "c:\program files\mozilla xulrunner\1.8.0.1\xulrunner\xulrunner.exe" --install-app "c:\documents and settings\user\desktop\myapplication.xpi" the application will be installed to c:\program files\vendorname\applicationname mac os x run the following command in a command prompt: /library/frameworks/xul.framework/xulrunner-bin --install-...
...app ~/desktop/myapplication.xpi the application will be installed to /applications/vendor/appicationname linux run the following command in a command prompt: /opt/xulrunner/1.8.0.1/xulrunner/xulrunner --install-app ~/desktop/myapplication.xpi the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application.
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.4 .
...the following directory is recommended: /opt/xulrunner/1.8.0.4 .
... windows run the following command from the start menu -> run or from a command prompt: "c:\program files\mozilla xulrunner\1.8.0.4\xulrunner\xulrunner.exe" --install-app "c:\documents and settings\user\desktop\myapplication.xpi" the application will be installed to c:\program files\vendorname\applicationname mac os x run the following command in a command prompt: /library/frameworks/xul.framework/xulrunner-bin --ins...
...tall-app ~/desktop/myapplication.xpi the application will be installed to /applications/vendor/applicationname linux run the following command in a command prompt: /opt/xulrunner/1.8.0.4/xulrunner/xulrunner --install-app ~/desktop/myapplication.xpi the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application.
XULRunner 1.9.1 Release Notes - Archive of obsolete content
the following directory is recommended: c:\program files\mozilla xulrunner\1.9.1 .
...the following directory is recommended: /opt/xulrunner/1.9.1 .
... windows run the following command from the start menu -> run or from a command prompt: "c:\program files\mozilla xulrunner\1.9.1\xulrunner\xulrunner.exe" --install-app "c:\documents and settings\user\desktop\myapplication.xpi" the application will be installed to c:\program files\vendorname\applicationname mac os x run the following command in a command prompt: /library/frameworks/xul.framework/xulrunner-bin --install-ap...
...p ~/desktop/myapplication.xpi the application will be installed to /applications/vendor/applicationname linux run the following command in a command prompt: /opt/xulrunner/1.9.1/xulrunner/xulrunner --install-app ~/desktop/myapplication.xpi the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application.
XULRunner 1.9.2 Release Notes - Archive of obsolete content
the following directory is recommended: c:\program files\mozilla xulrunner\1.9.2 .
...the following directory is recommended: /opt/xulrunner/1.9.2 .
... windows run the following command from the start menu -> run or from a command prompt: "c:\program files\mozilla xulrunner\1.9.2\xulrunner\xulrunner.exe" --install-app "c:\documents and settings\user\desktop\myapplication.xpi" the application will be installed to c:\program files\vendorname\applicationname mac os x run the following command in a command prompt: /library/frameworks/xul.framework/xulrunner-bin --install-ap...
...p ~/desktop/myapplication.xpi the application will be installed to /applications/vendor/applicationname linux run the following command in a command prompt: /opt/xulrunner/1.9.2/xulrunner/xulrunner --install-app ~/desktop/myapplication.xpi the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application.
XULRunner 1.9 Release Notes - Archive of obsolete content
the following directory is recommended: c:\program files\mozilla xulrunner\1.9 .
...the following directory is recommended: /opt/xulrunner/1.9 .
... windows run the following command from the start menu -> run or from a command prompt: "c:\program files\mozilla xulrunner\1.9\xulrunner\xulrunner.exe" --install-app "c:\documents and settings\user\desktop\myapplication.xpi" the application will be installed to c:\program files\vendorname\applicationname mac os x run the following command in a command prompt: /library/frameworks/xul.framework/xulrunner-bin --install...
...-app ~/desktop/myapplication.xpi the application will be installed to /applications/vendor/applicationname linux run the following command in a command prompt: /opt/xulrunner/1.9/xulrunner/xulrunner --install-app ~/desktop/myapplication.xpi the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application.
Mozilla release FAQ - Archive of obsolete content
regarding shells, i would like to recommend the following: if you are using unix, use bash-family shells for the build because of the better control over redirection (in case you want to log errors and messages) if you are using win32, using the default shell cmd.exe (as opposed to 4dos or 4nt) will probably yield better results.
...this list will be updated with time, but (according to netscape.public.mozilla.general) the following platforms have been built successfully: solaris 2.4, 2.5, 2.6 freebsd 2.2, 3.0 linux/intel and alpha 2.0, 2.1 macos winnt 4.0 irix 5.3, 6.2, 6.3, 6.4 win95, win98 digital unix 4.0 netbsd openbsd bsdi hp/ux 9.05, 10.20, 11.0 (see 2.7) hurd .03 dg/ux mac os x i'm *still* having problems getting mozilla to build on my platform!
...please send stats to me in the following format: cpu/mhz, architecture, ram, disk type, os version, compiler version, build type, tree date -- build time example: 21164/533, alpha, 512m edo, ultra2 scsi, linux kernel 2.2.11, gcc 2.95, non-debug, 19 august 1999 cvs -- 25 minutes how do i run the binary on unix?
...mozilla has (at least) the following new features: xml support a highly configurable appearance (courtesy of xul) publicly available source code :) http compression exists on more platforms mathml support (somewhat limited at the moment) a significantly faster rendering engine better html support (css 1 and partial css 2, dom 1 and partial dom 2) plug-in jvm support tabbed browsing message filtering an irc c...
2006-11-03 - Archive of obsolete content
summary: mozilla.dev.builds - october 28th to november 3rd 2006 no such file or directory (build problem on winxp) november 2nd: kenoa complained that when he is compiling using cygwin on win32 he gets the following error no such file or directory1: /cygdrive/c/mozilla/mail/config/mozconfig client.mk:339: /cygdrive/c/mozilla/.mozconfig.mk: no such file or directory he claims that the file ".mozconfig" exists in /cygdrive/c/mozilla/mail/config/mozconfig the disable-crypto cause problem originally posted on november 2nd: gxk is building minimo using the code base from sept.
... when he builds using the disable.crypto option he encounters the following problem: no rule to make target `../../dist/lib/components/libpipboot.a', needed by `minimo'.
...he has created the following bug entry https://bugzilla.mozilla.org/show_bug.cgi?id=331404.
...paul reed responds to boris with the following explanation on why he is taking down one of two the linux build servers.
The First Install Problem - Archive of obsolete content
the following write-up describes how a plugin installer can write keys to the win32 system registry to enable gecko-based browsers to discover the plugin at runtime.
... add the following values to the newly created key -- some are string values (reg_sz), and some are actually subkeys.
... the mimetypes subkeys contain the following string (reg_sz) value: "description" -- this is the actual description of the mimetype, very much as it appears in the dll (e.g.
...for example, in our case, a prospective invocation might look like: <object classid="@mycompany.com/myapplication,version=5.01" data="myfile.typ" codebase="http://myurl.com/myplugin/myplugin.xpi" type="application/x-myapp"></object> the use of both "type" and "classid" attributes here offers the following user benefit: if there is another mimetype handler for application/x-myapp, only myapplication gets invoked.
Using the W3C DOM - Archive of obsolete content
unsupported dom-related properties the following ie proprietary document object properties are not supported in the w3c document object model: document.layers[] id_attribute_value document.all document.all.id_attribute_value document.all[id_attribute_value] the following form related properties (originally from internet explorer) are not supported in the w3c document object model: formname.inputname.value inputname.value formctrln...
...for example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an inch: // in the html: <div id="inset">sample text</div> document.getelementbyid("inset").style.marginleft = ".5in"; note: internet explorer 5 through 7 have a flawed implementation of getelementbyid(), which returns the first element with a matching name or id (id versus name when using getelement...
... manipulating document style and content changing an element's style using the dom the following table describes standards-based methods for accessing and updating style rules defined for various html elements in a web page.
... the following examples show how to modify the text of a span element that already exists in the html file.
Browser Detection and Cross Browser Support - Archive of obsolete content
consider the following example: // wrong approach - do not use!
...a similar error can be seen in the following example: // wrong approach - do not use!
...in the following example, the branch tag is a.b.c.
...as we saw earlier, the vendor/version appear in the user agent string following the gecko version.
handler.enumerate() - Archive of obsolete content
syntax var p = new proxy(target, { enumerate(target) { } }); parameters the following parameter is passed to the enumerate method.
... interceptions this trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a typeerror: the enumerate method must return an object.
... examples the following code traps for...in statements.
... var p = new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant.
Reference - Archive of obsolete content
i checked this by doing alert(math.constructor) //shows that object is its constructor alert(object.constructor) //shows that function is its constructor alert(function.constructor) //shows that function is its constructor note : the function.constructor seems to keep on refering to itself, if you do the following you get same results which suggests that this is indeed the top level object.
... alert(function.constructor.constructor) alert(function.constructor.constructor.constructor.constructor) function == object however the following statement suggests that function is object.
...which still suggests that function is object object.prototype.myfunction = function() {}; o = new function(); alert(o.myfunction); //available in function o = new object(); alert(o.myfunction); //available in object but the following statement is again quite shocking to all the above if we create a prototype method for function , and create instances of function and object it shows that the method is only available in function.
...while also holding in account the previous example where it was avalable in both instances when prototyping object it should be : function->object->instance or (function=object)->instance and ofcourse function == object return false ;) and the following statements also tells me that function == object although math is only an instance of object...
Windows Media in Netscape - Archive of obsolete content
the following javascript illustrates one approach using object detection of activexobject and geckoactivexobject to determine if the windows media activex control is supported and available for use.
...for the sake of brevity, we've made the following code snippet shorter to illustrate the relevant points about the api: var player; try { if(window.activexobject) { player = new activexobject("wmplayer.ocx.7"); } else if (window.geckoactivexobject) { player = new geckoactivexobject("wmplayer.ocx.7"); } } catch(e) { // handle error -- no wmp 7 or 9 control // can use wmp 6 also if necessary, but this is legacy software nowaday...
...for example if (window.activexobject) { // internet explorer only script } server-side detection using user-agent strings netscape 7.1's user agent string on windows has the general pattern: mozilla/5.0 (windows; u; <em>operating system version</em>; <em>language</em>; rv:1.4) gecko/20030624 netscape/7.1 (ax<em>[;optional comments]</em>) the "vendor comment" (ax) following the "vendor version" netscape/7.1 is an indicator that the browser supports the windows media player activex control.
...for example, the following uses dhtml behaviors to associate a set of behaviors with a span element, which is then interrogated for its version number (the script attempts to verify that the windows media player control is at version 9): <span style="behavior:url(#default#clientcaps)" id="cc"></span> <script language=javascript> var cv = cc.getcomponentversion( "{6bf52a52-394a-11d3-b153-00c04f79faa6}", "componentid" )...
Archive of obsolete content
list of former mozilla-based applications the following is a list of all known applications that at one point used mozilla technologies or that are no longer being actively maintained.
... list of mozilla-based applications the following is a list of all known active applications that are built using mozilla technologies.
... table reflow internals key: tamarin tracing build documentation the following instructions are for obtaining and building the tamarin tracing source code.
...due to a limitation of the present implementation of nspr io on nt, programs must follow the following guideline: using ssh to connect to cvs using web standards in your web pages using workers in extensions this article shows you how to use worker threads in extensions to perform tasks in the background without blocking the user interface.
Building up a basic demo with A-Frame - Game development
add the following html before the <a-cube> element: <a-sky color="#dddddd"></a-sky> at this point, if you save the code and refresh your browser you can already see the cube on the screen with our custom background: here's the code we have created so far: you can also check it out on github.
...edit the <a-entity> defining the torus to look like the following: <a-entity geometry=" primitive: torus; radius: 1; radiustubular: 0.1; segmentstubular: 12;" material=" color: #eaeff2; roughness: 0.1; metalness: 0.5;" rotation="10 0 0" position="-3 1 0"> </a-entity> in the new material attribute, we set up the color of the material, then its roughness (a rougher material will scatter reflected light in more directions tha...
...add a new <script> element at the end of the <body> element, just after the <a-scene> element, then add the following javascript code inside it: var scene = document.queryselector('a-scene'); var cylinder = document.createelement('a-cylinder'); cylinder.setattribute('color', '#ff9500'); cylinder.setattribute('height', '2'); cylinder.setattribute('radius', '0.75'); cylinder.setattribute('position', '3 1 0'); scene.appendchild(cylinder); we're getting a reference to the scene handler first, then we create the cylinder element as an a-frame entity.
...add the following <a-animation> element to your torus: <a-entity geometry=" primitive: torus; radius: 1; radiustubular: 0.1; segmentstubular: 12;" material=" color: #eaeff2; roughness: 0.1; metalness: 0.5;" rotation="10 0 0" position="-3 1 0"> <a-animation attribute="scale" to="1 0.5 1" direction="alternate" dur="2000" repeat="indefinite" easing="linea...
Animations and tweens - Game development
next, we will load the spritesheet — put the following line at the bottom of your preload() function: game.load.spritesheet('ball', 'img/wobble.png', 20, 20); instead of loading a single image of the ball we can load the whole spritesheet — a collection of different images.
... loading the animation next up, go into your create() function, find the line that loads the ball sprite, and below it put the call to animations.add() seen below: ball = game.add.sprite(50, 250, 'ball'); ball.animations.add('wobble', [0,1,0,2,0,1,0,2,0], 24); to add an animation to the object we use the animations.add() method, which contains the following parameters the name we chose for the animation an array defining the order in which to display the frames during the animation.
...add the following function just before your closing </script> tag: function ballhitpaddle(ball, paddle) { ball.animations.play('wobble'); } the animation is played every time the ball hits the paddle.
...go to your ballhitbrick() function, find your brick.kill(); line, and replace it with the following: var killtween = game.add.tween(brick.scale); killtween.to({x:0,y:0}, 200, phaser.easing.linear.none); killtween.oncomplete.addonce(function(){ brick.kill(); }, this); killtween.start(); let's walk through this so you can see what's happening here: when defining a new tween you have to specify which property will be tweened — in our case, instead of hiding the bricks instantly when hi...
Visual JS GE - Game development
installing modules navigate to server_instance/, then in the node.js command prompt or console enter the following installation commands: npm install mysql npm install delivery npm install express npm install mkdirp npm install socket.io npm install nodemailer@0.7.0 setting up config.js you will find config.js in the server_instance folder: all node.js applications use the same folder — server_instance.
...w: module.exports = { version : "0.5", path_of_node_app : "d:/path_to_server_instance_folder/server/" , // edit here path_of_www : "d:/xamp/htdocs/project_instance/", // path_to_www edit here editor_port : "1013", reg_path : "users/", account_port : 3666 , destroy_session_after_x_mseconds : 20000, }; local node.js application tools (uses in developer mode only) the following section provides information about the tools involved in visual-js game engine.
... after this has finished processing, restart the web page by entering the following in the console: resource.test_res.
...contains the following tools.
Images, media, and form elements - Learn web development
sizing images as you already know from following these lessons, everything in css generates a box.
... if you are following these lessons in order then you may not have looked at layout yet.
... to force the image to stretch to fill the grid cell it is in, you'd have to do something like following: img { width: 100%; height: 100%; } this would however stretch the image, so probably isn't what you'd want to do.
...t, textarea { box-sizing: border-box; padding: 0; margin: 0; } other useful settings in addition to the rules mentioned above, you should also set overflow: auto on <textarea>s to stop ie showing a scrollbar when there is no need for one: textarea { overflow: auto; } putting it all together into a "reset" as a final step, we can wrap up the various properties discussed above into the following "form reset" to provide a consistent base to work from.
Responsive design - Learn web development
for example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least 800 pixels wide.
... the following example demonstrates a simple responsive design using media queries and a flexible grid.
...this is still an approach used today, and in most stylesheets, you will find the following css somewhere: img { max-width: 100%; } there are obvious downsides to this approach.
... the viewport meta tag if you look at the html source of a responsive page, you will usually see the following <meta> tag in the <head> of the document.
Fundamental text and font styling - Learn web development
the list of actual web safe fonts will change as operating systems evolve, but it's reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the microsoft core fonts for the web initiative in the late 90s and early 2000s): name generic type notes arial sans-serif it's often considered best practice to also add helvetica as a preferred alternative to arial as, although their font faces are almost identical, helvetica is con...
... a font-family example let's add to our previous example, giving the paragraphs a sans-serif font: p { color: red; font-family: helvetica, arial, sans-serif; } this gives us the following result: <h1>tommy the cat</h1> <p>well i remember it as though it were a meal ago...</p> <p>said tommy the cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat.
...once you've become used to using the above, you should also explore the following: font styles: font-variant: switch between small caps and normal font alternatives.
...these are written in the following order: font-style, font-variant, font-weight, font-stretch, font-size, line-height, and font-family.
How do I use GitHub Pages? - Learn web development
here's what you'd type if you've put your website in a directory called test-site on your desktop: cd desktop/test-site when the command line is pointing inside your website directory, type the following command, which tells the git tool to turn the directory into a git repository: git init an aside on command line interfaces the best way to upload your code to github is via the command line — this is a window where you type in commands to do things like create files and run programs, rather than clicking inside a user interface.
...your screen should look like this: click create repository; this should bring you to the following page: uploading your files to github on the current page, you are interested in the section …or push an existing repository from the command line.
...the command should look something like this: git remote add origin https://github.com/chrisdavidmills/my-repository.git next, type the following two commands, pressing enter after each one.
...then, you need to enter the following commands (pressing enter after each one) to push those changes to github: git add --all git commit -m 'another commit' git push you can replace another commit with a more suitable message to describe what change you just made.
What are browser developer tools? - Learn web development
(an added bonus: this method straight-away highlights the code of the element you right-clicked.) the inspector: dom explorer and css editor the developer tools usually open by default to the inspector, which looks something like the following screenshot.
...in the following image, the highlight on the number 18 shows that the line has a breakpoint set.
... this will give you a window like the following: to see what happens, try entering the following snippets of code into the console one by one (and then pressing enter): alert('hello!'); document.queryselector('html').style.backgroundcolor = 'purple'; const mywordmark = document.createelement('img'); mywordmark.setattribute('src','https://blog.mozilla.org/press/wp-content/themes/onemozilla/img/mozilla-wordmark.png'); docume...
...nt.queryselector('h1').appendchild(mywordmark); now try entering the following incorrect versions of the code and see what you get.
Basic native form controls - Learn web development
the following screenshot shows default, focused and disabled text input types in firefox 71 and safari on macos and in chrome 79 and edge 18 on windows 10.
... the following screenshots show default, focused and disabled checkboxes in firefox 71 and safari 13 on macos and chrome 79 and edge 18 on windows 10: note: any checkboxes and radio buttons with the checked attribute on load match the :default pseudo class, even if they are no longer checked.
...<ul> <li> <label for="soup">soup</label> <input type="radio" id="soup" name="meal" value="soup" checked> </li> <li> <label for="curry">curry</label> <input type="radio" id="curry" name="meal" value="curry"> </li> <li> <label for="pizza">pizza</label> <input type="radio" id="pizza" name="meal" value="pizza"> </li> </ul> </fieldset> the following screenshots show unchecked and checked radio buttons, radio buttons that have focus, and disabled unchecked and checked radio buttons — on firefox 71 and safari 13 on macos and chrome 79 and edge 18 on windows 10.
... the following examples show default, focused, and disabled button input types — in firefox 71 and safari 13 on macos and chrome 79 and edge 18 on windows 10.
The HTML5 input types - Learn web development
the following firefox for android keyboard screenshot provides an example: due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user (this means it may include letters, etc.).
... the following screenshot (from firefox for android) provides an example: with the number input type, you can constrain the minimum and maximum values allowed by setting the min and max attributes.
...the last minute of the previous millenium can be expressed in the following different ways, for example: 1999/12/31, 23:59 or 12/31/99t11:59pm.
...the following screenshot taken on firefox for macos provides an example: and here is a live example for you to try out: the value returned is always a lowercase 6-value hexidecimal color.
How to build custom form controls - Learn web development
if you want to learn more about this topic, you should check out the following helpful resources: uxmatters.com uxdesign.com the ux design section of smashingmagazine note: also, in most systems there is a way to open the <select> element with the keyboard to look at all the available choices (this is the same as clicking the <select> element with a mouse).
...the following is just an example of what is possible, and will match the screenshot at the beginning of this article.
... warning: the following is educational code, not production code, and should not be used as-is.
...the features we plan to use are the following: classlist addeventlistener() foreach queryselector() and queryselectorall() beyond the availability of those specific features, there is still one issue remaining before starting.
CSS basics - Learn web development
(if you haven't been following our project, pause here to read dealing with files and html basics.) open your index.html file.
... paste the following line in the head (between the <head> and </head> tags): <link href="styles/style.css" rel="stylesheet"> save index.html and load it in your browser.
... add the following lines (shown below), replacing the font-family assignment with your font-family selection from what will your website look like?.
... following that, we set the heading text to be the same color as the html background color.
Choosing the right approach - Learn web development
single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes no (unless it is the same one) no code example the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui.
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no no yes see promise.all(), below code example the following code fetches an image from the server and displays it inside an <img> element; see it live also, and see also the source code: fetch('coffee.jpg') .then(response => response.blob()) .then(myblob => { let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log('there has bee...
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no no no yes code example the following example fetches several resources from the server, and uses promise.all() to wait for all of them to be available before then displaying all of them — see it live, and see the source code: function fetchanddecode(url, type) { // returning the top level promise, so the result of the entire chain is returned out of the function return fetch(url).then(response => { // depending on what ty...
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no no yes yes (in combination with promise.all()) code example the following example is a refactor of the simple promise example we saw earlier that fetches and displays an image, written using async/await (see it live, and see the source code): async function myfetch() { let response = await fetch('coffee.jpg'); let myblob = await response.blob(); let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; ...
Introducing asynchronous JavaScript - Learn web development
that means that the following (pseudocode) wouldn't work: let response = fetch('myimage.png'); let blob = response.blob(); // display your image blob in the ui somehow that's because you don't know how long the image will take to download, so when you come to run the second line it will throw an error (possibly intermittently, possibly every time) because the response is not yet available.
...the following example is fairly similar to what we've seen before (see it live, and the source).
... it worked :) if this confuses you, then consider the following smaller example: console.log("registering click handler"); button.addeventlistener('click', () => { console.log("get click"); }); console.log("all done"); this is very similar in behavior — the first and third console.log() messages will be shown immediately, but the second one is blocked from running until someone clicks the mouse button.
... to see this in action, try taking a local copy of our example, and changing the fourth console.log() call to the following: console.log ('all done!
Functions — reusable blocks of code - Learn web development
the above function for example calls the random() function three times, which is defined by the following code: function random(number) { return math.floor(math.random()*number); } we needed this function because the browser's built-in math.random() function only generates a random decimal number between 0 and 1.
...you generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked: const mybutton = document.queryselector('button'); mybutton.onclick = function() { alert('hello'); } the above example would require there to be a <button> element available on the page to select and click.
...in the javascript console, enter the following command: output(x); you should see the value of variable x output to the screen.
... now try entering the following in your console output(y); output(z); both of these should return an error along the lines of "referenceerror: y is not defined".
JavaScript object basics - Learn web development
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.
...i\'m ' + this.name[0] + '.'); } }; after saving and refreshing, try entering some of the following into the javascript console on your browser devtools: person.name person.name[0] person.age person.interests[1] person.bio() person.greeting() you have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax!
...we could get those values like this: let mydataname = nameinput.value; let mydatavalue = namevalue.value; we could then add this new member name and value to the person object like this: person[mydataname] = mydatavalue; to test this, try adding the following lines into your code, just below the closing curly brace of the person object: let mydataname = 'height'; let mydatavalue = '1.75m'; person[mydataname] = mydatavalue; now try saving and refreshing, and entering the following into your text input: person.height adding a property to an object using the method above isn't possible with dot notation, which can only accept a literal member name, n...
...try entering the following into your javascript console: const mynotification = new notification('hello!'); again, we'll look at constructors in a later article.
Client-Server Overview - Learn web development
both static and dynamic websites (discussed in the following sections) use exactly the same communication protocol/patterns.
...the header contains information like the following: the first line includes the response code 200 ok, which tells us that the request succeeded.
... for example, consider the following django (python) code that maps two url patterns to two view functions.
... in a following module we'll help you choose the best web framework for your first site.
Routing in Ember - Learn web development
to do this you’ll need to enter the following commands into your terminal, inside the root directory of your app: ember generate route index ember generate route completed ember generate route active the second and third commands should have not only generated new files, but also updated an existing file, app/router.js.
... it contains the following contents: import emberrouter from '@ember/routing/router'; import config from './config/environment'; export default class router extends emberrouter { location = config.locationtype; rooturl = config.rooturl; } router.map(function() { this.route('completed'); this.route('active'); }); the highlighted lines were added when the 2nd and 3rd commands above were run.
...add the following below the existing getters: get completed() { return this.todos.filter(todo => todo.iscompleted); } models now we need to add models to our route javascript files to allow us to easily return specific data sets to display in those models.
... go back to todomvc/app/components/footer.hbs, and find the following bit of markup: <a href="#">all</a> <a href="#">active</a> <a href="#">completed</a> update it to <linkto @route='index'>all</linkto> <linkto @route='active'>active</linkto> <linkto @route='completed'>completed</linkto> <linkto> is a built-in ember component that handles all the state changes when navigating routes, as well as setting an "active" class on any link that matches the url, in case...
Accessibility in React - Learn web development
let's see this in action; put the following useeffect() call just above the return statement in the body of todo(), and pass into it a function that logs the words "side effect" to your console: useeffect(() => { console.log("side effect"); }); to illustrate the difference between the main render process and code run inside useeffect(), add another log – put this one below the previous addition: console.log("main render"); now, ope...
... paste the following code near the top of todo.js, above your todo() function.
...add it to the top of your app.js file, just below the imports: function useprevious(value) { const ref = useref(); useeffect(() => { ref.current = value; }); return ref.current; } now add the following, above the return statement inside the app() function: const prevtasklength = useprevious(tasks.length); here we are invoking useprevious() to track the length of the tasks state, like so: note: since we're now utilizing useprevious() in two files, a good efficiency refactor would be to move the useprevious() function into its own file, export it from that file, and import it where you need i...
... add the following into the body of your app() function, just below your previous additions: useeffect(() => { if (tasks.length - prevtasklength === -1) { listheadingref.current.focus(); } }, [tasks.length, prevtasklength]); we only try to focus on our list heading if we have fewer tasks now than we did before.
Componentizing our React app - Learn web development
the following commands make a components directory and then, within that, a file called todo.js.
...in app.js, add the following line near the top of the file to import todo: import todo from "./components/todo"; with this component imported, you can replace all of the <li> elements in app.js with <todo /> component calls.
...let's try the following instead of what we have already: const tasklist = props.tasks.map(task => <todo />); look again at your app; now our tasks look more like they used to, but they’re missing the names of the tasks themselves.
...run this command in your terminal, taking care that you're in the root directory of your app: touch src/components/form.js src/components/filterbutton.js the <form /> open components/form.js and do the following: import react at the top of the file, like we did in todo.js.
Beginning our React todo list - Learn web development
our app should fulfill the following stories: as a user, i can read a list of tasks.
... then, copy and paste the following commands into your terminal to delete some unneeded files.
... the jsx copy the following snippet to your clipboard, then paste it into app.js so that it replaces the existing app() function: function app(props) { return ( <div classname="todoapp stack-large"> <h1>todomatic</h1> <form> <h2 classname="label-wrapper"> <label htmlfor="new-todo-input" classname="label__lg"> what needs to be done?
... implementing our styles paste the following css code into src/index.css so that it replaces what's currently there: /* resets */ *, *::before, *::after { box-sizing: border-box; } *:focus { outline: 3px dashed #228bec; outline-offset: 0; } html { font: 62.5% / 1.15 sans-serif; } h1, h2 { margin-bottom: 0; } ul { list-style: none; padding: 0; } button { border: none; margin: 0; padding: 0; width: auto; overflow: vis...
Deployment and next steps - Learn web development
note: the following section could be applied to any client-side static web site requiring a build step, not just svelte apps.
...in our case we will tell git to exclude files in the node_modules directory by creating a .gitignore file in the root folder of your local project, with the following content: node_modules/ now let's go back to gitlab.
... create a .gitlab-ci.yml file inside your project's root and give it the following content: image: node:latest pages: stage: deploy script: - npm install - npm run build artifacts: paths: - public only: - master here we are telling gitlab to use an image with the latest version of node to build our app.
...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.
Vue conditional rendering: editing existing todos - Learn web development
copy the following code into that file: <template> <form class="stack-small" @submit.prevent="onsubmit"> <div> <label class="edit-label">edit name for &quot;{{label}}&quot;</label> <input :id="id" type="text" autocomplete="off" v-model.lazy.trim="newlabel" /> </div> <div class="btn-group"> <button type="button" class="btn" @click="oncancel"> cancel <span class="visua...
... first of all add v-if="!isediting" to the root <div> in your todoitem component, <div class="stack-small" v-if="!isediting"> next, below that <div>'s closing tag add the following line: <to-do-item-edit-form v-else :id="id" :label="label"></to-do-item-edit-form> we also need to import and register the todoitemeditform component, so we can use it inside this template.
... add the following new methods to your app.vue's component object, below the existing methods inside the methods property: deletetodo(todoid) { const itemindex = this.todoitems.findindex(item => item.id === todoid); this.todoitems.splice(itemindex, 1); }, edittodo(todoid, newlabel) { const todotoedit = this.todoitems.find(item => item.id === todoid); todotoedit.label = newlabel; } next, we'll add the even...
... so, let's implement the fix: remove the following line from inside our data() property: isdone: this.done, add the following block below the data() { } block: computed: { isdone() { return this.done; } }, now when you save and reload, you'll find that the problem is solved — the checkbox state is now preserved when you switch between todo item templates.
Handling common HTML and CSS problems - Learn web development
the following example shows date and time inputs: <form> <div> <label for="date">enter a date:</label> <input id="date" type="date"> </div> <div> <label for="time">enter a time:</label> <input id="time" type="time"> </div> </form> the output of this code is as follows: hidden example label { float: left; width: 30%; text-align: right; } input { ...
... put the following code into the head of your html document, just before the opening <style> tag: <script type="text/javascript" src="mootools-core-1.6.0.js"></script> <!--[if (gte ie 6)&(lte ie 8)]> <script type="text/javascript" src="selectivizr-min.js"></script> <![endif]--> if you try running this in an old version of ie, it should work fine.
...as an example, the following query will select the last 2 versions of all major browsers and versions of ie above 9.
... as an example, we entered the following code: body { display: flex; } we highlighted it and ran the autoprefixer command, and it replaced it with this: body { display: -webkit-box; display: -ms-flexbox; display: flex; } layout issues another problem that might come up is differences in layouts between browsers.
Learn web development
random glossary entry semantics in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) topics covered the following is a list of all the topics we cover in the mdn learning area.
... to copy the learning area repo to a folder called learning-area in the current location your command prompt/terminal is pointing to, use the following command: git clone https://github.com/mdn/learning-area you can now enter the directory and find the files you are after (either using your finder/file explorer or the cd command).
... you can update the learning-area repository with any changes made to the master version on github with the following steps: in your command prompt/terminal, go inside the learning-area directory using cd.
... for example, if you were in the parent directory: cd learning-area update the repository using the following command: git pull contact us if you want to get in touch with us about anything, the best way is to drop us a message on our discourse forum.
Gecko info for Windows accessibility vendors
in total, gecko supports the following window classes: mozillauiwindowclass - root ui window, at the root of the window hierarchy mozillacontentwindowclass -- root document window mozillacontentframewindowclass - root of a subdocument created by a <frame> or <iframe> element mozillahiddenwindowclass - ignore these windows, they are used to help manage other windows mozillawindowclass - general filler window, a c...
... msaa features we do not support no one has yet asked for the following features (if you need something, please contact the mozilla accessibility community ): iaccessible methods that we don't currently support: get_acchelp get_acchelptopic put_accname put_accvalue we do not currently support the visual basic (idispatch) bindings for iaccessible.
...the following html tags are exposed as bstr's: abbr, acronym, blockquote, dd, dl, dt, form, frame, h1, h2, h3, h4, h5, h6, iframe, q, tbody, tfoot, thead in addition, an html list uses the bullet bstr role to expose bullets and numbers that are automatically inserted into the formatting by gecko.
... positional descriptions are supported the accdescription field is overriden for the following roles: role_listitem, role_menuitem, role_radiobutton, role_pagetab and role_outlineitem for everything other than outline item, the positional description is in the form "n of m" where n is an integer indicating the position within other similar objects in a group, and m represents the number of objects in that group.
Command line options
in general, the syntax is as follows: application -option -option "argument" -option argument examples the following examples show the use of the "-profilemanager" command, which will open the profile manager prior to starting firefox or thunderbird: windows select run from windows start menu.
... enter the following command: firefox -profilemanager mac os x go to applications > utilities.
... open terminal and enter the following command: cd /applications/firefox.app/contents/macos ./firefox -profilemanager if you use firefox nightly, you can enter: cd /applications/firefoxnightly.app/contents/macos ./firefox -profilemanager linux open terminal and enter the following command: cd thunderbird installation directory ./thunderbird -profilemanager the example above invokes the "-profilemanager" command line option with mozilla's thunderbird mail client.
...this can be used to suppress the migration wizard at startup by loading the following override.ini.
Debugging Frame Reflow
it provides the following information for each frame at the start of its reflow reflow reason available width, available height computed width, computed height the previous and the next frame in flow and a count number.
... when the frame's reflow is finished the following information is displayed : reflow metric (desired) width, height max.
... log file analysis the log file for a simple table like <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> </head> <body> <table width="100"> <tbody> <tr> <td>foo</td> </tr> </tbody> </table> </body> </html> will create the following log: vp 00b97c30 r=0 a=9180,4470 c=9180,4470 cnt=856 scroll 00b97ee0 r=0 a=9180,4470 c=9180,4470 cnt=857 scroll 00b97ee0 r=0 a=9180,4470 c=9180,4470 cnt=858 canvas 00b97c6c r=0 a=9180,uc c=9180,4470 cnt=859 area 02d7afe4 r=0 a=9180,uc c=9180,uc cnt=860 text 02d7b150 r=0 a=9180,uc c=uc,uc cnt=861 text 02d7b150 d=0,0 block 02d7b210 r=0 a=9180,uc c=8940,uc cnt=862 block 02d7b2...
...the display of the following frames can be turned on by adding a line with the frame name and 1 or turned off by adding a line with the frame name and 0: short name layout tag area area block block br br bullet bullet button gfxbuttoncontrol hr hr framei ...
HTTP logging
copy and paste the following lines one at a time into the command prompt window.
... copy and paste the following commands into the shell one at a time.
... copy and paste the following commands into the terminal window, hitting the return key after each line.
... copy and paste the following line into the "run" command window and then press enter: for 32-bit windows: "c:\program files (x86)\mozilla firefox\firefox.exe" -moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 -moz_log_file=%temp%\log.txt for 64-bit windows: "c:\program files\mozilla firefox\firefox.exe" -moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,n...
The Firefox codebase: CSS Guidelines
using css variables adding new variables before adding new css variables, please consider the following questions: is the variable value changed at runtime?
...theme css the following directories also contain css: browser/base/content/ toolkit/content/ these directories contain content css, that applies on all platforms, which is styling deemed to be essential for the browser to behave correctly.
...in general, the following colors are used: -moz-field: textbox or field background colors, also used as the background color of listboxes or trees.
...in the following example, -moz-mac-yosemite-theme targets macos 10.10 and higher, so it should be privileged over the styling for macos 10.9.
Creating Custom Events That Can Pass Data
(see bug 427537) requirements in order to do this you must be able to do all of the following: download mozilla source code build mozilla creating custom firefox extensions with the mozilla build system.
... you need to make the following two modifications: around line 1000: ns_define_classinfo_data({truncated name}, nsdomgenericsh, dom_default_scriptable_flags) around line 2900: dom_classinfo_map_begin({truncated name}, nsidom{truncatedname}) dom_classinfo_map_entry(nsidom{truncated name}) dom_classinfo_event_map_entries dom_classinfo_map_end remember, {truncated name} is the same as above.
...your event in order for your event to work you must do the following: create a scriptable interface called nsidom{youreventname} inheriting from nsidomevent.
...var event = document.createevent("nsdommyevent"); event.initevent("nsdommyevent", true, true); window.dispatchevent(event); dispatching your event in c++ the following shows how to dispatch your event in c++: nscomptr<nsiwindowwatcher> wwatcher (do_getservice("@mozilla.org/embedcomp/window-watcher;1")); // the window watcher will be able to give me a handle to the window nscomptr<nsidomwindow> awindow; // a handle to the window nscomptr<nsidomdocument> adoc; // a handle to the document nscomptr<nsidomeventtarget> twindow; // the ...
Commenting IDL for better documentation
happily, following these recommendations will also help ensure your comments are extremely human-readable, too.
...but by following the guidelines here, you can help make sure that our tools can generate a "good start" version of the documentation for your interfaces, and that the writers will be able to easily figure out what the tools are not able to do automatically.
... comment format doxygen supports several comment formats; for style and consistency reasons, we use the following: /** * */ note the two asterisks ("**") on the first line of the comment.
...following the rules below will ensure that our tools are able to produce the best possible results, and will have the added bonus of making your comments easier to read!
Obsolete Build Caveats and Tips
to get this code, do the following: # pull the mozilla source to the folder 20src/ - may take a while # as hundreds of megabytes of history is downloaded to .hg hg clone https://hg.mozilla.org/releases/mozilla-2.0/ 20src cd 20src mozilla-1.9.2 (firefox 3.6) code for the firefox 3.6 (gecko 1.9.2) release lives in releases/mozilla-1.9.2.
... to get this code, do the following: # pull the mozilla source to the folder 192src/ - may take a while # as hundreds of megabytes of history is downloaded to .hg hg clone https://hg.mozilla.org/releases/mozilla-1.9.2/ 192src cd 192src mozilla-1.9.1 (firefox 3.5) code for the firefox 3.5 (gecko 1.9.1) release lives 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.
... unsupported sdks the windows sdk for windows server 2008 is not supported, and has been found to cause the following problems: breaks the vcvars32.bat file from visual studio 2008 no longer sets the correct path for the .net framework causes an invalid path which breaks the mozilla build if you have the windows server 2008 sdk installed, uninstall it.
Browser API
navigation methods the following navigation methods allow navigation through the browsing history of the <iframe>.
... audio-related methods the following methods allow direct control of sound in the browser element.
...the following methods are used to deal with those events: the <iframe> gains support for the methods of the eventtarget interface addeventlistener(), removeeventlistener(), and dispatchevent().
...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.
Downloads.jsm
alternatively, may be an nsiuri, a downloadsource object, or an object with the following properties: url: string containing the uri for the download source.
...alternatively, may be an nsifile, a downloadtarget object, or an object with the following properties: path: string containing the path of the target file.
...you may pass an object with a subset of the following fields: isprivate: optional indicates whether the download originated from a private window.
...in general, you should be aware of the following highlights: there is no difference between active downloads and finished downloads.
Sqlite.jsm
the following sections detail the api of an opened connection instance.
... these functions receive the following arguments: readonly (optional) if true the clone will be read-only, default is false.
... these functions receive the following arguments: sql (required) string sql statement to execute.
... this function receives the following arguments: func the function defining the transaction body.
Index
17 localization sign-off reviews guide, localization, mozilla this article presents an overview of why we do sign-off reviews of localizations, the details on the criteria used for the sign-off reviews, and the process for requesting a review and for following its progress.
... 18 localization technical reviews guide, localization, mozilla this guide provides details on what a localization technical review is, what criteria are used for the technical reviews, and the process for requesting one and following its progress.
...with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation.
...the following list contains links to pages that highlight steps that can be taken to make web content localizable.
Localization content best practices
for example, in english all the following begin with the same clause: the url of this feed is invalid; the url of this feed cannot be reached; the url of this feed cannot be parsed.
...for example, if you're adding a new menu item in settings on android, don't use the same string for the menu item and the following screen header.
...instead, you should use the following strings # localization note(privacy-text): {{link}} will be replaced at run-time # by an active link.
... feedback from l10n-drivers is not necessary for each landing involving strings, as long as you're following the basic rules described in this document.
Localizing extension descriptions
the following example demonstrates this (most normal manifest properties have been removed for brevity): <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>tabsidebar@blueprintit.co.uk</em:id> <em:localized> <description> <em:locale>de-de</em:local...
... add the following line to each of your localization properties files (where extension_id matches your extension id (<em:id> from install.rdf) and localized_description is the description of your extension that you want to appear in the given language): extensions.extension_id.description=localized_description if you do not currently have one, create a default preferences file.
... add the following line to it (where extension_id matches your application id from install.rdf and path_to_localization_file is the chrome path to the localization file you added to earlier): pref("extensions.extension_id.description", "path_to_localization_file"); localizable strings the following add-on metadata can be localized using this process: name description creator homepageurl localizable lists in cases where multiple values can exist, a numeric index is appended to the end of the preference name: extensions.extension_id.contributor.1=first_localized_contributor_name extensions.extension_id.contributor.2=second_localized_contributor_name extensions.extension_id.contributor.3=thrid_localized_contributor_name pref("extensions.extension_id.contributor.1", "path_to_localiza...
...tion_file"); pref("extensions.extension_id.contributor.2", "path_to_localization_file"); pref("extensions.extension_id.contributor.3", "path_to_localization_file"); the following add-on metadata can be localized using this process: developer translator contributor ...
Basics
this demo has been made to illustrate the following aspects.
...you can also make displayed equations, such as the following ones: x → maps to y = f n ⁡ ( x ) = ( 1 + 1 x n ) n ∫ a b f ( x ) d x = b - a 6 [ f ( a ) + 4 f ( a + b 2 ) + f ( b ) ] - ( b - a ) 5 4 !
...the following example shows the i-th step of the multiplication of a matrix a by a vector x (notice how ai1 , ...
...incrementinput('input21',-1);" title="decrease input">-</a> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; right size: <a class="control" href="javascript:incrementinput('input12', 1);" title="increase input">+</a> <a class="control" href="javascript:incrementinput('input12',-1);" title="decrease input">-</a> <br/> (click these control buttons to see their effects.) </div> <p> each entry of the following matrix represents <math> <msup><mrow><mo>(</mo><mi>x</mi><mo>+</mo><mi>y</mi><mo>)</mo></mrow><mi>n</mi></msup> </math> for some <i>n</i>.
Fonts for Mozilla 2.0's MathML engine
the fonts may be installed by extracting the font files (which have the .otf extension) from the zip archive, then following instructions for microsoft windows, or copying the files to a ~/library/fonts folder on mac os x, or to a ~/.fonts/ directory (which may need to be created) on unix/linux systems.
...the following fonts are not necessary when the above fonts are installed, but are worth noting because of their unicode support for many mathematical characters.
...mathml font selection with css you can get these fonts from the mathml-fonts add-on ; the xpi is just a zip archive that you can fetch and extract for example with the following command: wget https://addons.mozilla.org/firefox/downloads/latest/367848/addon-367848-latest.xpi -o mathml-fonts.zip; \ unzip mathml-fonts.zip -d mathml-fonts then copy the mathml-fonts/resource/ directory somewhere on your web site and ensure that the woff files are served with the correct mime type.
... finally, include the mathml-fonts/resource/mathml.css style sheet in your web pages, for example by adding the following rule to the default style sheet of your web site: @import url('/path/to/resource/mathml.css'); browsers have default font-families in their user agent stylesheets.
MathML Demo: <mo> - operator, fence, separator, or accent
binary operators and relations the following table contains instances of all operators found on the swp binary operations and binary relations panels.
... ≂ c a ⊎ b ⋖ c a ⌆ b ⋗ c a ⨿ b ∣ c a ⊴ b ∥ c a ⊵ b ∼ c a ▽ b ≈ c a △ b ≊ c a ⋄ b ⪸ c a † b ⪷ c a ‡ b ∋ c a ⊞ b \vartriangle c arrows the following table contains instances of all arrows found on the swp arrows panel.
... a - b ↫ c a + b ↬ c a - b ⊸ c a + b ⇛ c a - b ⇚ c a + b ↶ c a - b ↷ c a + b ⤏ c a - b ⤎ c a + b ⇒ c a - b ⇐ c a + b ⇔ c negated relations the following table contains instances of all negated relations found on the swp panel.
...fixed sized fences are useful with nested fences as in the following example [ [ a b ] + [ b a ] ] + [ a b ] latex fences that are built into fractions (\binom, etc.) are not stretchy, but they are taller in displays.
Activity Monitor, Battery Status Menu and top
the following screenshot shows a customized "energy" tab.
...careful investigation indicates that on mac os 10.10 and 10.11 it is computed with a formula that is machine model-specific, and includes the following factors: cpu usage, wakeup frequency, quality of service class usage, and disk, gpu, and network activity.
... the weightings of each factor can be found in one of the the files in /usr/share/pmenergy/mac-<id>.plist, where <id> can be determined with the following command.
... it will show periodically-updating data like the following.
Memory reporting
two ways to measure memory reporters can be divided into the two following kinds.
... traversal-based reporters are preferable, for the following reasons.
... a simple example imagine a simple string class with the following data fields: class mystring { private: char *mbuffer; // heap-allocated size_t mlen; // ...
... all this is probably not what you'd expect, but the above functions have the following crucial features.
Power profiling overview
intel processor basics processor layout the following diagram (from the intel power governor documentation) shows how machines using recent intel processors are constructed.
...the following sections list them from best to worst.
... pp1: an uncore device, usually the gpu (not available on all processor models.) dram: main memory (not available on all processor models.) the following relationship holds: pp0 + pp1 <= pkg.
... tools that can take rapl readings include the following.
TraceMalloc
the built mozilla application will support the following additional command-line options: --trace-malloc filename the application will log allocation and deallocation events with stack traces in a binary format to the given file.
... also, your javascript can call the following dom window methods: tracemallocdisable() - turn off tracing, first flushing any buffered log events for all log files.
...it will produce a report like the following.
...you can use the following web page to do so.
about:memory
within each process's measurements, there are the following subsections.
... some add-on memory usage is identified, as the following example shows.
...for example, in the "explicit" tree all dom and layout measurements are broken down by window by window, but in "other measurements" those measurements are aggregated into totals for the whole browser, as the following example shows.
... finally, at the end of this section are individual measurements, as the following example shows.
powermetrics
the following command encompasses the most useful ones: sudo powermetrics --samplers tasks --show-process-coalition --show-process-gpu -n 1 -i 5000 --samplers tasks tells it to just do per-process measurements.
... the following is example output from such an invocation: *** sampled system activity (fri sep 4 17:15:14 2015 +1000) (5009.63ms elapsed) *** *** running tasks *** name id cpu ms/s user% deadlines (<2 ms, 2-5 ms) wakeups (intr, pkg idle) gpu ms/s com.apple.terminal 293 447.66 274.83 120.35 221.74 firefox ...
... 0.00 com.apple.safari.searchhelper 84690 0.15 49.49 0.00 0.00 0.20 0.20 0.00 org.mozilla.firefox 482 76.56 124.34 63.47 0.00 firefox 84496 76.70 89.18 10.58 5.59 124.55 63.48 0.00 this sample was taken while the following programs were running: firefox beta (single process, invoked from the mac os dock, shown in the org.mozilla.firefox coalition.) firefox nightly (multi-process, invoked from the command line, shown in the com.apple.terminal coalition.) google chrome.
...the following is sample output.
PR_Poll
syntax #include <prio.h> print32 pr_poll( prpolldesc *pds, printn npds, printervaltime timeout); parameters the function has the following parameters: pds a pointer to the first element of an array of prpolldesc structures.
... the prpolldesc structure is defined as follows: struct prpolldesc { prfiledesc* fd; print16 in_flags; print16 out_flags; }; typedef struct prpolldesc prpolldesc; the structure has the following fields: fd a pointer to a prfiledesc object representing a socket or a pollable event.
... in_flags a bitwise or of the following bit flags: pr_poll_read: fd is readable.
... out_flags a bitwise or of the following bit flags: pr_poll_read pr_poll_write pr_poll_except pr_poll_err: fd has an error.
NSS 3.12.5 release_notes
this default setting can also be changed within the application by using the following existing api functions: secstatus ssl_optionset(prfiledesc *fd, print32 option, prbool on) secstatus ssl_optionsetdefault(print32 option, prbool on) there is now a new value for "option", which is: ssl_enable_renegotiation the corresponding new values for ssl_enable_renegotiation are: ssl_renegotiate_never: never renegotiate at all (default).
... see the following struct in nss.h for details: nssinitparametersstr other new functions in secmod.h: secmod_getskipfirstflag secmod_getdefaultmoddbflag in prlink.h nss_securememcmp port_loadlibraryfromorigin modified functions sgn_update (see cryptohi.h) the parameter "input" of this function is changed from unsigned char * to const unsigned char *.
... bugs fixed the following bugs have been fixed in nss 3.12.5.
...new and revised documents available since the release of nss 3.11 include the following: build instructions nss shared db compatibility nss 3.12.5 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.12.6 release notes
the behavior of nss for renegotiation can be changed through api function calls, or with the following environment variables: nss_ssl_enable_renegotiation values: [0|n|n]: ssl_renegotiate_never never allow renegotiation - that was the default for 3.12.5 release.
... these options can also be set with the following ssl options: ssloptions.enablerenegotiation ssloptions.requiresafenegotiation new pseudo cipher suite value: tls_empty_renegotiation_info_scsv (cannot be negotiated) tls server name indication for servers tls server name indication (sni) for servers is almost fully impl...
... bugs fixed the following bugs have been fixed in nss 3.12.6.
...new and revised documents available since the release of nss 3.11 include the following: build instructions nss shared db compatibility nss 3.12.6 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.14 release notes
introduction the nss team has released network security services (nss) 3.14, which is a minor release with the following new features: support for tls 1.1 (rfc 4346) experimental support for dtls 1.0 (rfc 4347) and dtls-srtp (rfc 5764) support for aes-ctr, aes-cts, and aes-gcm support for keying material exporters for tls (rfc 5705) in addition to the above new features, the following major changes have been introduced: support for certificate signatures using the md5 hash algorithm is now disabled by default.
...the following functions have been added to the libssl library included in nss 3.14 ssl_versionrangeget (in ssl.h) ssl_versionrangegetdefault (in ssl.h) ssl_versionrangegetsupported (in ssl.h) ssl_versionrangeset (in ssl.h) ssl_versionrangesetdefault (in ssl.h) to better ensure interoperability with peers that support tls 1.1, nss has altered how i...
... the following functions have been added to the libssl library included in nss 3.14: dtls_importfd (in ssl.h) dtls_gethandshaketimeout (in ssl.h) ssl_getsrtpcipher (in ssl.h) ssl_setrtpciphers (in ssl.h) support for aes-gcm support for aes-gcm has been added to the nss pkcs #11 module (softoken), based upon the draft 7 of pkcs #11 v2.30.
... the following types have been added in nss 3.14 certchainverifycallback (in certt.h) certchainverifycallbackfunc (in certt.h) cert_pi_chainverifycallback, a new option for certvalparamintype (in certt.h) a new error code: sec_error_application_callback_error (in secerr.h) new for pkcs #11 pkcs #11 mechanisms: ckm_aes_cts ...
PKCS #11 Module Specs
pkcs #11 module specs the following is a proposal to the pkcs #11 working group made in august 2001 for configuring pkcs #11 modules.
... recognized names all applications/libraries must be able recognize the following name values: library this specifies the path to the pkcs #11 library.
...only one of the following can be specified.
...if tokens is not specified, then softoken would default to the following specs: in non-fips mode: tokens=<0x01=[configdir=configdir tokendescription=cryptotokendescription slotdescription=cryptoslotdescription flags=nocertdb,nokeydb,optimizespace] 0x02=[configdir=configdir tokendescription=dbtokendescription slotdescription=dbslotdescription certprefix=certprefix keyprefix=keyprefix flags=flags minpwlen=minpwlen]> in fips mode: tokens=<0x03=[configdir=configdir ...
NSS tools : ssltab
the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercept any connection information.
...the simplest way to use the debugging tool is to execute the following command from a command shell: $ ssltap www.netscape.com the program waits for an incoming connection on the default port 1924.
...data sent from the client to the server is surrounded by the following symbols: --> [ data ] data sent from the server to the client is surrounded by the following symbols: "left arrow"-- [ data ] the raw data stream is sent to standard output and is not interpreted in any way.
...the following examples show the output from commonly used combinations of options.
NSS tools : ssltap
the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercept any connection information.
...the simplest way to use the debugging tool is to execute the following command from a command shell: $ ssltap www.netscape.com the program waits for an incoming connection on the default port 1924.
...data sent from the client to the server is surrounded by the following symbols: --> [ data ] data sent from the server to the client is surrounded by the following symbols: "left arrow"-- [ data ] the raw data stream is sent to standard output and is not interpreted in any way.
...the following examples show the output from commonly used combinations of options.
NSS Tools crlutil
syntax to run the certificate revocation list management tool, type the command crlutil option [arguments] where options and arguments are combinations of the options and arguments listed in the following section.
... crl generation script syntax: crl generation script file has the following syntax: line with comments should have <bold>#</bold> as a first symbol of a line set "this update" or "next update" crl fields: update=yyyymmddhhmmssz nextupdate=yyyymmddhhmmssz field "next update" is optional.
... reasoncode non-critical code where: reasoncode: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension code: the following codes are available: unspecified (0), keycompromise (1), cacompromise (2), affiliationchanged (3), superseded (4), cessationofoperation (5), certificatehold (6), removefromcrl (8), privilegewithdrawn (9), aacompromise (10) add invalidity date extension: the invalidity date is a non-critica...
... listing crls in a database this example lists all the crls in the nss database in the specified directory: crlutil -l -d certdir the crl management tool displays output similar to the following: crl name crl type cn=nss test ca,o=bogus nss,l=mountain view,st=california,c=us crl cn=john smith,o=netscape,l=mountain view,st=california,c=us crl to view a particular crl user should specify -n nickname parameter.
NSS tools : ssltap
MozillaProjectsNSStoolsssltap
the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercept any connection information.
...the simplest way to use the debugging tool is to execute the following command from a command shell: $ ssltap www.netscape.com the program waits for an incoming connection on the default port 1924.
...data sent from the client to the server is surrounded by the following symbols: --> [ data ] data sent from the server to the client is surrounded by the following symbols: "left arrow"-- [ data ] the raw data stream is sent to standard output and is not interpreted in any way.
...the following examples show the output from commonly used combinations of options.
Scripting Java
for example, the following code actually calls the file object's getname and isdirectory methods.
... as an example, consider the following java class that defines a number of overloaded methods and calls them.
...to create an array of five java strings you would make the following call: js> a = java.lang.reflect.array.newinstance(java.lang.string, 5); [ljava.lang.string;@7ffe01 to create an array of primitive types, we must use the special type field defined in the associated object class in the java.lang package.
...rhino wraps java exceptions into error objects with the following properties: javaexception: the original exception thrown by the java method rhinoexception: the exception wrapped by the rhino runtime the instanceof operator can be used to query the type of an exception: try { java.lang.class.forname("nonexistingclass"); } catch (e) { if (e.javaexception instanceof java.lang.classnotfoundexception) { print("class not found"); } } rhi...
Rebranding SpiderMonkey (1.8.5)
after installing the build pre-requisites and downloading the spidermonkey source tarball issue the following commands at the terminal: cd js/src autoconf-2.13 for the remainder of this document wherever you see the text $brand you will substitute that text with the name of your brand.
...in the unix world we would issue the following command: find ./ -type f -exec sed -i "s/mozjs185/$brand/" {} \; windows users: notepad++ can be used to perform the recursive find and replace text operation.
...you may now perform the build and installation of your custom branded spidermonkey library: make note: depending on your system you may need administrative rights to perform the installation: make install the following information isn't technically needed for using your library but it will help other applications use your library.
...if this is not desirable, you can issue the following command on unix systems: sed -i "s/mozjs185/$brand/" /usr/bin/js-config which performs a simple text replacement of mozjs185 with your branding on the js-config script.
64-bit Compatibility
the following types or typedefs are always 64-bit on 64-bit platforms, and 32-bit on 32-bit platforms: pointers uintptr_t, intptr_t, ptrdiff_t, (probably) size_t jsval jsuword, jsword length of a string, though the actual length cannot exceed 30 bits jsuintptr, jsintptr, jsptrdiff, jsuptrdiff, jssize, jsuword, jsword (let's not use these, kthx) the following types are 32-bit on 32-bit platforms.
...mucking with native integers in lir the following opcodes can be used to safely load, modify, and compare native integers.
...the following table contains the most relevant opcodes: platform alias 32-bit op 64-bit op ldp ld ldq ldcp ldc ldcq piadd add qiadd piand and qiand pilsh lsh qilsh pirsh rsh qirsh pursh ush qursh pcmov cmov qcmov pior or qior pxor xor qxor addp iaddp qaddp peq - puge eq - uge qeq - quge pcall icall qcall the 32-bit versions have the following inputs ...
...i32 i32 add i32, i32 i32 and i32, i32 i32 lsh i32, i32 i32 rsh i32, i32 i32 ush i32 cmov i32, i32, i32 i32 or i32, i32 i32 xor i32, i32 i32 iaddp i32, i32 i32 eg - uge i32, i32 i32 icall n/a i32 the 64-bit versions have the following inputs and outputs.
JS::CompileOptions
source belongs to a dom element in the following cases: source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <script> element in the markup text), or is the source document referenced by its src attribute.
... introductiontype const char a statically allocated c string: one of following in general: "eval" - code passed to eval "function" - code passed to the function constructor.
... in addition to above, the following are used in browser: "worker" - code loaded by calling the web worker constructor—the worker's main script.
... the following are used in js shell: "js shell file" "js shell interactive" "js shell load" "js shell evaluate" "js shell run" "js shell disfile" "js shell compfile" "js shell parse" "js shell syntaxparse" "js shell offthreadcompilescript" and the following are used in self-hosted code and debugger: "self-hosted" "debugger eval" ...
Animated PNG graphics
MozillaTechAPNG
4 width unsigned int width of the following frame.
... 8 height unsigned int height of the following frame.
... 12 x_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.
An Overview of XPCOM
when a class inherits from another class, the inheriting class may override the default behaviors of the base class without having to copy all of that class's code, in effect creating a more specific class, as in the following example: simple class inheritance class shape { private: int m_x; int m_y; public: virtual void draw() = 0; shape(); virtual ~shape(); }; class circle : public shape { private: int m_radius; public: virtual draw(); circle(int x, int y, int radius); virtual ~circle(); }; circle is a derived class of shape.
... xpcom types there are many xpcom declared types and simple macros that we will use in the following samples.
...the most common types are described in the following sections.
... method types the following are a set of types for ensuring correct calling convention and return type of xpcom methods.
Address Book examples
in the following examples: selectedab is the uri of an address book to default the dialog to saving the card in.
...the following options are available.
...for example, in order to register a load listener for a contact, the following should take place within the scope of the contact editor dialog: /* an example load listener for a contact * acard the nsiabcard being loaded * adocument a reference to the contact editor document */ function foo(acard, adocument) { // do something useful, like disabling // input fields that cards for this // address book type do not support.
...each photo handler must implement the following interface: /* * onload: function(acard, adocument): * called when the editor wants to populate the contact editor * input fields with information about acard's photo.
Index
the following preferences are supported to control how this gets logged: 30 gloda examples thunderbird 3, thunderbird this page provides some examples for using gloda.
...as an example, i received the following inquiry, and i decided to follow my usual path and document what i do: 88 styling the folder pane the folder pane in thunderbird is predominantly controlled by code in folderpane.js.
...by example, to modify the mail subject : 104 get thunderbird version thunderbird on thunderbird version 3.0b3pre and later, you can use the following snippet to get the thunderbird version.
... 110 tips and tricks from the newsgroups thunderbird the following discussions on mozilla.dev.apps.thunderbird and mozilla.dev.extensions include useful tips for thunderbird add-on developers.
Mail composition back end
(for detailed information on the listener interfaces, see the listener interfaces section of this document) nsimsgsend the following describes the methods of the nsimsgsend interface.
... nsimsgsendlistener the following describes the methods of the nsimsgsendlistener interface: onstartsending the onstartsending interface is called when the sending operation has begun.
...the following details the specific copy operations that can occur in a message send call.
... the following describes the methods of the nsimsgsendlater interface.
Type conversion
var buffer = ctypes.char.array(10)(); var somecfunction = library.declare("somecfunction", ctypes.default_abi, ctypes.void_t, ctypes.char.ptr); somecfunction(buffer); // here ctypes.char.array(10)() is converted to ctypes.char.ptr type implicit conversion can be tested in the following way: var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' boolean type target type source converted value ctypes.bool js boolean src js number (0 or 1) if src == 0: false if src == 1: true var mystruct = ctypes.structtype("mystructtype", [ { "v": ...
... note that the following table does not contain environment dependent types (ctypes.long, etc.).
...ucttype("mystructtype", [ { "v": ctypes.int16_t.ptr } ])(); mystruct.v = ctypes.int16_t.array(10)(); console.log(mystruct.v.tostring()); // 'ctypes.int16_t.ptr(ctypes.uint64("0x11d6ff400"))' mystruct.v = null; console.log(mystruct.v.tostring()); // 'ctypes.int16_t.ptr(ctypes.uint64("0x0"))' mystruct.v = ctypes.int32_t.array(10)(); // throws error only in functiontype argument, the following rules are also applied: target type source converted value ctypes.char.ptr js string pointer to temporary allocated null-terminated utf8 string ctypes.signed_char.ptr ctypes.unsigned_char.ptr ctypes.char16.ptr js string pointer to temporary allocated null-terminated utf16 string any pointer types any arraybuffer object ...
...ct (only if the object has properties for all fields and no other properties) implicitly convert each enumerable property to corresponding field explicit convert in js-ctypes, data could be converted explicitly, when passing to cdata constructor: ctypes.int32_t("123"); // string "123" is parsed as 10-base string explicit convert tries implicit convert first, and if it fails, the following rules are applied: boolean type target type source converted value ctype.bool js value toboolean(src) console.log(ctypes.bool("123").tostring()); // 'ctypes.bool(true)' console.log(ctypes.bool("").tostring()); // 'ctypes.bool(false)' integer types target type source converted value any integer types js number except -infinity...
Debugger.Frame - Firefox Developer Tools
a frame is a visible frame if any of the following are true: it is running debuggee code; its immediate caller is a frame running debuggee code; or it is a "debugger" frame, representing the continuation of debuggee code invoked by the debugger.
... accessor properties of the debugger.frame prototype object a debugger.frame instance inherits the following accessor properties from its prototype: type a string describing what sort of frame this is: "call": a frame running a function call.
... debugger.frame instances inherit the following handler method properties: onstep this property must be either undefined or a function.
...the eval method recognizes the following properties: url the filename or url to which we should attributecode.
Debugger.Source - Firefox Developer Tools
accessor properties of the debugger.source prototype object a debugger.source instance inherits the following accessor properties from its prototype: text if the instance refers to javascript source, the javascript source code, as a string.
...source may be loaded from a url in the following ways: the url may appear as the src attribute of a <script> element in markup text.
...source belongs to a dom element in the following cases: source belongs to a <script> element if it is the element’s text content (that is, it is written out as the body of the <script> element in the markup text), or is the source document referenced by its src attribute.
...this accessor returns one of the following values: "eval", for code passed to eval.
Network request list - Firefox Developer Tools
to close the search panel, do one of the following: click the x icon next to the search field.
... context menu context-clicking on a row in the list displays a context menu with the following options: menuitem description copy > copy url copies the url.
... copy as curl the command may include the following options: -x [method] if the method is not get or post --data for url encoded request parameters --data-binary for multipart request parameters --http/version if the http version is not 1.1 -i if the method is head -h one for each request header.
... network monitor features the following articles cover different aspects of using the network monitor: toolbar network request details network traffic recording performance analysis throttling ...
Examine and edit CSS - Firefox Developer Tools
in the following example, a spelling error, "background-colour" instead of "background-color" has made the rule invalid: rule display it displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations.
... displaying pseudo-elements the rule view displays the following pseudo-elements, if they are applied to the selected element: ::after ::backdrop ::before ::first-letter ::first-line ::selection :-moz-color-swatch :-moz-number-spin-box :-moz-number-spin-down :-moz-number-spin-up :-moz-number-text :-moz-number-wrapper :-moz-placeholder :-moz-progress-bar :-moz-range-progress :-moz-range-thumb :-moz-range-track :-moz-selection if the selected ...
...for example, copying the changes in the preceding image, you get the following: .text-content p { box-sizing:border-box; max-width:24rem; text-decoration: underline; color: cadetblue; font-weight: bold; } add rules you can add new rules in the rules view.
... there's also a button that enables you to do the same thing: copy rules to copy rules, and pieces of rules, use one of the following context menu items in the rules view: copy rule copy selector copy property declaration copy property name copy property value ...
Console messages - Firefox Developer Tools
the following icons may be used: informational message warning error blocked; for network messages in addition, a disclosure triangle indicates that further information is available; clicking it displays or collapses that information.
... the web console supports the following console api messages: assert() clear() count() dir() dirxml() error() exception() group() groupend() info() log() table() time() timeend() trace() warn() the console prints a stack trace for all error messages, like this: function foo() { console.error("it explodes"); } function bar() { foo(); } function dostuff() { bar(); } dostuff(); server server-side log mess...
... for responses that contain objects or variables, the following context menu options are available: reveal in inspector shows the selected dom node in the inspector pane.
...for example, the following video shows the results when filtering on two simple regular expressions: /(cool|rad)/ and /(cool)/.
Applying styles and colors - Web APIs
each of the following examples describe the same color.
... because the strokestyle and fillstyle properties accept css rgba color values, we can use the following notation to assign a transparent color to them.
...we create a canvasgradient object by using one of the following methods.
... the type specifies how to use the image in order to create the pattern, and must be one of the following string values: repeat tiles the image in both vertical and horizontal directions.
Drawing shapes with canvas - Web APIs
the starting point is dependent on previously drawn paths, where the end point of the previous path is the starting point for the following, etc.
...to convert degrees to radians you can use the following javascript expression: radians = (math.pi/180)*degrees.
... the following example is a little more complex than the ones we've seen above.
...in the following example, we'll be drawing some simple organic shapes, but if you have the time and, most of all, the patience, much more complex shapes can be created.
Document.cookie - Web APIs
WebAPIDocumentcookie
consider also that: any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator: ;path=path (e.g., '/', '/mydir') if not specified, defaults to the current path of the current document location.
... the strict value will prevent the cookie from being sent by the browser to the target site in all cross-site browsing contexts, even when following a regular link.
... some user agent implementations support the following cookie prefixes: __secure- signals to the browser that it should only include the cookie in requests transmitted over a secure channel.
...xample #2: get a sample cookie named test2 document.cookie = "test1=hello"; document.cookie = "test2=world"; const cookievalue = document.cookie .split('; ') .find(row => row.startswith('test2')) .split('=')[1]; function alertcookievalue() { alert(cookievalue); } <button onclick="alertcookievalue()">show cookie value</button> example #3: do something only once in order to use the following code, please replace all occurrences of the word dosomethingonlyonce (the name of the cookie) with a custom name.
Examples of web and XML development using the DOM - Web APIs
example 1: height and width the following example shows the use of the height and width properties alongside images of varying dimensions: <!doctype html> <html lang="en"> <head> <title>width/height example</title> <script> function init() { var arrimages = new array(3); arrimages[0] = document.getelementbyid("image1"); arrimages[1] = document.getelementbyid("image2"); arrimages[2] = document.getelementbyid("image3"); var objoutput = document.getelementbyid("output"); var strhtml = "<ul>"; for (var i = 0; i < arrimages.length; i++) { strhtml += "<li>image" + (i+1)...
... var ss = document.stylesheets; for(var i = 0; i < ss.length; i++) { for(var j = 0; j < ss[i].cssrules.length; j++) { dump( ss[i].cssrules[j].selectortext + "\n" ); } } for a document with a single stylesheet in which the following three rules are defined: body { background-color: darkblue; } p { font-face: arial; font-size: 10pt; margin-left: .125in; } #lumpy { display: none; } this script outputs the following: body p #lumpy example 5: event propagation this example demonstrates how events fire and are handled in the dom in a very simple way.
... getcomputedstyle() returns a computedcssstyledeclaration object, whose individual style properties can be referenced with this object's getpropertyvalue() method, as the following example document shows.
... put the following code into a blank text file and load it into a variety of browsers, you'll be surprised at the different number and names of properties.
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
take the following minimal example: <!doctype html> <h1> hello world!
... take the following document, for example: <!doctype html> <html> <head> <title>my document</title> </head> <body> <h1>header</h1> <p> paragraph </p> </body> </html> the dom tree for this looks like so: conserving whitespace characters in the dom is useful in many ways, but there are certain places where this makes certain layouts more difficult to implement, and causes problems for developers who ...
...re and apply this first rule, we get: <h1>◦◦◦hello⏎ <span>◦world!</span>⇥◦◦</h1> next, all tab characters are handled as space characters, so the example becomes: <h1>◦◦◦hello⏎ <span>◦world!</span>◦◦◦</h1> next, line breaks are converted to spaces: <h1>◦◦◦hello◦<span>◦world!</span>◦◦◦</h1> after that, any space immediately following another space (even across two separate inline elements) is ignored, so we end up with: <h1>◦hello◦<span>world!</span>◦</h1> and finally, sequences of spaces at the beginning and end of a line are removed, so we finally get this: <h1>hello◦<span>world!</span></h1> this is why people visiting the web page will simply see the phrase "hello world!" nicely written at the top o...
... */ function data_of( txt ) { var data = txt.textcontent; // use ecma-262 edition 3 string and regexp features data = data.replace(/[\t\n\r ]+/g, " "); if (data.charat(0) == " ") data = data.substring(1, data.length); if (data.charat(data.length - 1) == " ") data = data.substring(0, data.length - 1); return data; } example the following code demonstrates the use of the functions above.
Using the Frame Timing API - Web APIs
in the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax.
...in the following example, the observer only registers for "frame" performance entry notifications.
... }); // only observe 'frame' events observe_frame.observe({entrytypes: ['frame']}); in the following example, the observer registers to be notified when several different performance entry types are added to the performance timeline.
... in the following example, the observer only processes "frame" entries.
HTMLButtonElement - Web APIs
this is an enumerated attribute with the following possible values: submit: the button submits the form.
... recommendation the following attribute has been added: menu.
... the following attributes have been added: autofocus, formaction, formenctype, formmethod, formnovalidate, formtarget, labels, validity, validationmessage, and willvalidate.
... the following methods have been added: checkvalidity(), setcustomvalidity().
HTMLTableCellElement - Web APIs
permitted values for scope are: col the header cell applies to the following cells in the same column (or columns, if colspan is used as well), until either the end of the column or another <th> in the column establishes a new scope.
... row the header cell applies to the following cells in the same row (or rows, if rowspan is used as well), until either the end of the row or another <th> in the same row establishes a new scope.
...it reflects the valign attribute and can have one of the following values: "top", "middle", "bottom", or "baseline".
... recommendation the following properties have been obsoleted: align, axis, bgcolor, height, width, ch, choff, nowrap, and valign.
Drag Operations - Web APIs
the following describes the steps that occur during a drag and drop operation.
...this technique is useful when drawing custom drag images using the canvas element, as in the following example: function dragwithcustomimage(event) { const canvas = document.createelement("canvas"); canvas.width = canvas.height = 50; const ctx = canvas.getcontext("2d"); ctx.linewidth = 4; ctx.moveto(0, 0); ctx.lineto(50, 50); ctx.moveto(0, 50); ctx.lineto(50, 0); ctx.stroke(); const dt = event.datatransfer; dt.setdata('text/plain', 'data to drag'); dt.setdragimage(canvas...
...in the following example, three formats are supported by a drop target.
... the following example returns the data associated with the best-supported format: function dodrop(event) { const supportedtypes = ["application/x-moz-file", "text/uri-list", "text/plain"]; const types = event.datatransfer.types.filter(type => supportedtypes.includes(type)); if (types.length) { const data = event.datatransfer.getdata(types[0]); } event.preventdefault(); } finishing a drag once the drag is complete, a dragend event is fired at the source of the drag (the same element that received the dragstart event).
File drag and drop - Web APIs
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.
...in this example, the drop target element uses the following styling: #drop_zone { border: 5px solid blue; width: 200px; height: 100px; } note that dragstart and dragend events are not fired when dragging a file into the browser from the os.
...in the following drop handler, if the browser supports datatransferitemlist interface, the getasfile() method is used to access each file; otherwise the datatransfer interface's files property is used to access each file.
...file[' + i + '].name = ' + ev.datatransfer.files[i].name); } } } prevent the browser's default drag behavior the following dragover event handler calls preventdefault() to turn off the browser's default drag and drop handler.
IDBDatabaseSync - Web APIs
exceptions this method can raise an idbdatabaseexception with the following code: constraint_err if an object store with the same name (based on case-sensitive comparison) already exists in the connected database.
... exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if an object store with the given name (based on case-sensitive comparison) already exists in the connected database.
... returns void exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if the object store with the given name (based on case-sensitive comparison) does not exist in the connected database.
... exceptions this method can raise an idbdatabaseexception with the following code: timeout_err if reserving all the database objects identified in storenames takes longer than the timeout interval.
IDBKeyRange - Web APIs
to retrieve all keys within a certain range, you can use the following code constructs: range code all keys ≥ x idbkeyrange.lowerbound(x) all keys > x idbkeyrange.lowerbound(x, true) all keys ≤ y idbkeyrange.upperbound(y) all keys < y idbkeyrange.upperbound(y, true) all keys ≥ x && ≤ y idbkeyrange.bound(x, y) all keys > x &&< y idbkeyrange.bound(x, y, true, true) a...
...ll keys > x && ≤ y idbkeyrange.bound(x, y, true, false) all keys ≥ x &&< y idbkeyrange.bound(x, y, false, true) the key = z idbkeyrange.only(z) a key is in a key range if the following conditions are true: the lower value of the key range is one of the following: undefined less than key value equal to key value if loweropen is false.
... the upper value of the key range is one of the following: undefined greater than key value equal to key value if upperopen is false.
... examples the following example illustrates how you'd use a key range.
LocalFileSystem - Web APIs
so to request storage, you need to do something like the following: var requestedbytes = 1024*1024*10; // 10mb navigator.webkitpersistentstorage.requestquota ( requestedbytes, function(grantedbytes) { window.requestfilesystem(persistent, grantedbytes, oninitfs, errorhandler); }, function(e) { console.log('error', e); } ); your user must grant your app permission to store data locally before your app can use persistent storage.
... example the following is a code snippet that shows how you can request a file system storage.
... returns void exceptions this method can raise an fileerror with the following code: exception description security_error the application does not have permission to access the file system interface.
... returns void exceptions this method can raise an fileerror with the following code: exception description encoding_err the syntax of the url was invalid.
Using Performance Timeline - Web APIs
the following example show the usage of these methods getentries(), getentriesbyname() and getentriesbytype().
...the following example shows the use of these properties.
...the following examples show the use of this method.
... the following example shows how to register two observers: the first one registers for several event types and the second observer only registers for one event type.
Request - Web APIs
WebAPIRequest
request implements body, so it also inherits the following properties: body read only a simple getter used to expose a readablestream of the body contents.
... request implements body, so it also has the following methods available to it: body.arraybuffer() returns a promise that resolves with an arraybuffer representation of the request body.
... examples in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then return some property values of the request: const request = new request('https://www.mozilla.org/favicon.ico'); const url = request.url; const method = request.method; const credentials = request.credentials; you could then fetch this request by passing the request ob...
...ject in as a parameter to a windoworworkerglobalscope.fetch() call, for example: fetch(request) .then(response => response.blob()) .then(blob => { image.src = url.createobjecturl(blob); }); in the following snippet, we create a new request using the request() constructor with some initial data and body content for an api request which need a body payload: const request = new request('https://example.com', {method: 'post', body: '{"foo": "bar"}'}); const url = request.url; const method = request.method; const credentials = request.credentials; const bodyused = request.bodyused; note: the body type can only be a blob, buffersource, formdata, urlsearchparams, usvstring or readablestream type, so for adding a json object to the payload you need to stringify that object.
Using the Resource Timing API - Web APIs
timing resource loading phases the following example illustrates using the resource timing properties to calculate the amount of time the following phases take: redirection (redirectstart and redirectend ), dns lookup (domainlookupstart and domainlookupend), tcp handshake (connectstart and connectend), and response (responsestart and responseend).
... the following example demonstrates using these three properties.
... the following example demonstrates the usage of these two methods.
...the following code example sets a onresourcetimingbufferfull event callback in the init() function.
Screen Wake Lock API - Web APIs
there are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a qr/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake).
... if ('wakelock' in navigator) { issupported = true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled = true; statuselem.textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object.
...equestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // change up our interface to reflect wake lock active statuselem.textcontent = 'wake lock is active!'; } catch (err) { // if wake lock request fails - usually system related, such as battery statuselem.textcontent = `${err.name}, ${err.message}`; } } releasing wake lock the following example shows how to release the previously acquired wake lock.
... wakelock.addeventlistener('release', () => { // the wake lock has been released statuselem.textcontent = 'wake lock has been released'; }); reacquiring a wake lock the following code reacquires the wake lock should the visibility of the document change and the wake lock is released.
Using Service Workers - Web APIs
basic architecture with service workers, the following steps are generally observed for basic set up: the service worker url is fetched and registered via serviceworkercontainer.register().
...it is different in the following ways: in the original, we only passed in a url to an image we wanted to load.
... this could be for the following reasons: you are not running your application through https.
...the following would do the trick: self.addeventlistener('fetch', (event) => { event.respondwith( caches.match(event.request).then((resp) => { return resp || fetch(event.request).then((response) => { return caches.open('v1').then((cache) => { cache.put(event.request, response.clone()); return response; }); }); }) ); }); here we return the default net...
Migrating from webkitAudioContext - Web APIs
see the following example: // old webkitaudiocontext code: var src = context.createbuffersource(); src.buffer = somebuffer; src.gain.value = 0.5; src.connect(context.destination); src.noteon(0); // new standard audiocontext code: var src = context.createbuffersource(); src.buffer = somebuffer; var gain = context.creategain(); src.connect(gain); gain.gain.value = 0.5; gain.connect(context.destination); src.start(...
... see the following example: // old webkitaudiocontext code: var src = context.createbuffersource(); src.buffer = somebuffer; src.buffer.gain = 0.5; src.connect(context.destination); src.noteon(0); // new standard audiocontext code: var src = context.createbuffersource(); src.buffer = somebuffer; var gain = context.creategain(); src.connect(gain); gain.gain.value = 0.5; gain.connect(context.destination); src.start(0); removal of audiobuffersourcenode.looping the looping attribute of audiobuffersourcenode has been removed.
... depending on why you used this attribute, you can use the following techniques to get the same information: if you need to compare this attribute to unscheduled_state, you can basically remember whether you've called start() on the node or not.
...ext api: // old webkitaudiocontext code: var osc = context.createoscillator(); var table = context.createwavetable(realarray, imaginaryarray); osc.setwavetable(table); // new standard audiocontext code: var osc = context.createoscillator(); var table = context.createperiodicwave(realarray, imaginaryarray); osc.setperiodicwave(table); removal of some of the audioparam read-only attributes the following read-only attributes have been removed from audioparam: name, units, minvalue, and maxvalue.
Background audio processing using AudioWorklet - Web APIs
structure of an audio worklet processor an audio worklet processor is a javascript module which consists of the following: a javascript class which defines the audio processor.
...this is demonstrated in the following example.
... to use an audio worklet processor, you can use code similar to the following: let audiocontext = null; async function createmyaudioprocessor() { if (!audiocontext) { try { audiocontext = new audiocontext(); await audiocontext.resume(); await audiocontext.audioworklet.addmodule("module-url/module.js"); } catch(e) { return null; } } return new audioworkletnode(audiocontext, "processor-name"); } this createmyaudioprocessor() fun...
... in the following implementation of parameterdescriptors(), the returned array has two audioparam objects.
Web Audio API - Web APIs
it can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.
... offline/background audio processing it is possible to process/render an audio graph very quickly in the background — rendering it to an audiobuffer rather than to the device's speakers — with the following.
... obsolete interfaces the following interfaces were defined in old versions of the web audio api spec, but are now obsolete and have been replaced by other interfaces.
...this example makes use of the following web api interfaces: audiocontext, oscillatornode, periodicwave, and gainnode.migrating from webkitaudiocontextin this article, we cover the differences in web audio api since it was first implemented in webkit and how to update your code to use the modern web audio api.
Using the Web Speech API - Web APIs
the following variable is defined to hold our grammar: var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral' ...
... you can have as many terms defined as you want on separate lines following the above structure, and include fairly complex grammar definitions.
... browser support support for web speech api speech synthesis is still getting there across mainstream browsers, and is currently limited to the following: firefox desktop and mobile support it in gecko 42+ (windows)/44+, without prefixes, and it can be turned on by flipping the media.webspeech.synth.enabled flag to true in about:config.
... { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } when we come to run the function, we do the following.
Using feature queries - CSS: Cascading Style Sheets
you may not test for a bare property name such as display; the rule requires a property name and a value: @supports (property: value) { css rules to apply } if you want to check if a browser supports the row-gap property, for example, you would write the following feature query.
... testing for lack of support in addition to asking the browser if it supports a feature, you can test for the opposite by adding in the not keyword: @supports not (property: value) { css rules to apply } the css inside the following example feature query will run if the browser does not support row-gap.
...the following rule will only return true if both shape-outside: circle() and display: grid are supported by the browser.
...we can start by creating that floated layout with the following code, which gives us three columns.
Ordering Flex Items - CSS: Cascading Style Sheets
the specification says the following on this matter: “note: the reordering capabilities of flex layout intentionally affect only the visual rendering, leaving speech order and navigation based on the source order.
...you should always take the source order as the logical order of the document as all up-to-date user agents will be following the specification and doing so.
... as an example, i have 5 flex items, and assign order values as follows: source item 1: order: 2 source item 2: order: 3 source item 3: order: 1 source item 4: order: 3 source item 5: order: 1 these items would be displayed on the page in the following order: source item 3: order: 1 source item 5: order: 1 source item 1: order: 2 source item 2: order: 3 source item 4: order: 3 you can play around with the values in this live example below and see how that changes the order.
...to read more about this disconnect of visual order and logical order and some of the potential problems it raises for accessibility, see the following resources.
Basic Concepts of grid layout - CSS: Cascading Style Sheets
css grid layout has the following features: fixed and flexible track sizes you can create a grid with fixed track sizes – using pixels for example.
...the following example demonstrates doing this in a simple way.
... in the following example i am placing the first two items on our three column track grid, using the grid-column-start, grid-column-end, grid-row-start and grid-row-end properties.
...in the following example, i have the three-column grid that i created earlier, with our two positioned items.
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
textfield div { color: black; -moz-appearance: textfield; -webkit-appearance: textfield; } <div>lorem</div> firefox chrome safari edge the following values are treated as equivalent to auto: button div { color: black; -moz-appearance: button; -webkit-appearance: button; } <div>lorem</div> firefox chrome safari edge the element is drawn like a button.
... chrome safari edge square-button div{ color: black; -moz-appearance: square-button; -webkit-appearance: square-button; } <div>lorem</div> chrome safari edge textarea div{ color: black; -webkit-appearance: textarea; } <div>lorem</div> firefox chrome safari edge non-standard keywords the following values are implemented only for one or both of the prefixed properties, but not on the standard appearance property.
...available on the web starting in ios 10.1 and macos 10.12.1 obsolete values the following values were at some point implemented for a prefixed property, but are no longer supported.
... formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | auto | button | textfield | menulist-button | <compat-auto>where <compat-auto> = searchfield | textarea | push-button | slider-horizontal | checkbox | radio | square-button | menulist | listbox | meter | progress-bar examples the following would make an element look like a menulist button: .exampleone { appearance: menulist-button; } see also this jsfiddle for an example showing how you might use appearance: none to apply custom styling to radio buttons and checkboxes.
<color> - CSS: Cascading Style Sheets
a <color> can be defined in any of the following ways: using a keyword (such as blue or transparent) using the rgb cubic-coordinate system (via the #-hexadecimal or the rgb() and rgba() functional notations) using the hsl cylindrical-coordinate system (via the hsl() and hsla() functional notations) note: this article describes the <color> data type in detail.
...these system colors are exposed by the following keywords, which can be used to ensure that the rest of the page integrates well with the restricted palette.
... the keywords in the following list are defined by the css color module level 4 specification.
...ontent or documents field background of input fields fieldtext text in input fields graytext text that is disabled highlight background of items that are selected in a control highlighttext text of items that are selected in a control linktext text of non-active, non-visited links visitedtext text of visited links deprecated system color keywords the following keywords were defined in earlier versions of the css color module.
conic-gradient() - CSS: Cascading Style Sheets
the following two gradients are equivalent conic-gradient(red, orange, yellow, green, blue); conic-gradient(red 0deg, orange 90deg, yellow 180deg, green 270deg, blue 360deg); by default, colors transition smoothly from the color at one color stop to the color at the subsequent color stop, with the midpoint between the colors being the half way point between the color transition.
...the following is solid red from the start to the 10% mark, transitions from red to blue over 80% of the turn, with the final 10% being solid blue.
...the following two declarations are equivalent: conic-gradient(#fff 0.09turn, #bbb 0.09turn, #bbb 0.27turn, #666 0.27turn, #666 0.54turn, #000 0.54turn); conic-gradient(#fff 0turn 0.09turn, #bbb 0.09turn 0.27turn, #666 0.27turn 0.54turn, #000 0.54turn 1turn); color stops should be listed in ascending order.
...the following changes from red to yellow at the 30% mark, and then transitions from yellow to blue over 35% of the gradient conic-gradient(red .8rad, yellow .6rad, blue 1.3rad); there are other effects you can create with conic gradients.
linear-gradient() - CSS: Cascading Style Sheets
the following two gradients are equivalent.
...the following example is solid red from the start to the 10% mark and solid blue from 90% to the end.
...the following changes from red to yellow at the 30% mark, and then transitions from yellow to blue over 35% of the gradient linear-gradient(red 40%, yellow 30%, blue 65%); multi-position color stop are allowed.
...the following three gradients are equivalent: linear-gradient(red 0%, orange 10%, orange 30%, yellow 50%, yellow 70%, green 90%, green 100%); linear-gradient(red, orange 10% 30%, yellow 50% 70%, green 90%); linear-gradient(red 0%, orange 10% 30%, yellow 50% 70%, green 90% 100%); by default, if there is no color with a 0% stop, the first color declared will be at that point.
Constraint validation - Developer guides
validation-related attributes in addition to the type attribute described above, the following attributes are used to describe basic constraints: attribute input types supporting the attribute possible values constraint description associated violation pattern text, search, url, tel, email, password a javascript regular expression (compiled with the ecmascript 5 global, ignorecase, and multiline flags disabled) the value must match the pattern.
...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.
... <label for="zip">zip : </label> <input type="text" id="zip"> <label for="country">country : </label> <select id="country"> <option value="ch">switzerland</option> <option value="fr">france</option> <option value="de">germany</option> <option value="nl">the netherlands</option> </select> <input type="submit" value="validate"> </form> this displays the following form: first, we write a function checking the constraint itself: function checkzip() { // for each country, defines the pattern that the zip has to follow var constraints = { ch : [ '^(ch-)?\\d{4}$', "switzerland zips must have exactly 4 digits: e.g.
... controlling the text of constraint violation the following items can help with controlling the text of a constraint violation: element.setcustomvalidity(message) method on the following elements: <fieldset>.
Date and time formats used in HTML - HTML: Hypertext Markup Language
this is detailed in the following table.
...that means it's possible for the first few days of january to be considered part of the previous week-year, and for the last few days of december to be considered part of the following week-year.
...a valid global date and time string is the same format as a local date and time string, except it has a time zone string appended to the end, following the time.
... the time zone string is appended immediately following the time in the date and time string.
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
take the following example: <form> <div> <input type="checkbox" id="subscribenews" name="subscribe" value="newsletter"> <label for="subscribenews">subscribe to newsletter?</label> </div> <div> <button type="submit">subscribe</button> </div> </form> in this example, we've got a name of subscribe, and a value of newsletter.
... additional attributes in addition to the common attributes shared by all <input> elements, "checkbox" inputs support the following attributes: attribute description checked boolean; if present, the checkbox is toggled on by default indeterminate a boolean which, if present, indicates that the value of the checkbox is indeterminate rather than true or false value the string to use as the value of the checkbox when submitting the form, if the checkbox is currently toggled on...
... for example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the examples section).
... examples the following example is an extended version of the "multiple checkboxes" example we saw above — it has more standard options, plus an "other" checkbox that when checked causes a text field to appear to enter a value for the "other" option.
<input type="image"> - HTML: Hypertext Markup Language
WebHTMLElementinputimage
additional attributes in addition to the attributes shared by all <input> elements, image button inputs support the following attributes: attribute description alt alternate string to display when the image can't be shown formaction the url to which to submit the data formenctype the encoding method to use when submitting the form data formmethod the http method to use when submitting the form formnovalidate a boolean which, if present, indicat...
... obsolete attributes the following attribute was defined by html 4 for image inputs, but was not implemented by all browsers and has since been deprecated: attribute description usemap the name of an image map (<map>) element to use with the image; this is obsolete.
...the following keywords have special meanings: _self: load the response into the same browsing context as the current one.
... examples a login form the following example shows the same button as before, but included in the context of a typical login form.
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, text inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid pattern a regular expression the input's...
... non-standard attributes the following non-standard attributes are also available on some browsers.
...look at the following example: <form> <div> <label for="uname">choose a username: </label> <input type="text" id="uname" name="name" placeholder="lower case, all one word"> </div> <div> <button>submit</button> </div> </form> you can see how the placeholder is rendered below: the placeholder is typically rendered in a lighter color than the element's foreground color, and automatical...
...in this section, we'll use the following css, which will place a check (tick) mark next to inputs containing valid values, and a cross (x) next to inputs containing invalid values.
itemprop - HTML: Hypertext Markup Language
same structured data marked up in two different ways there is no semantic difference between the following two examples <figure> <img src="castle.jpeg"> <figcaption><span itemscope><span itemprop="name">the castle</span></span> (1986)</figcaption> </figure> <span itemscope><meta itemprop="name" content="the castle"></span> <figure> <img src="castle.jpeg"> <figcaption>the castle (1986)</figcaption> </figure> both have a figure with a caption, and both, completely unrelated to th...
... values the property value of a name-value pair is as given for the first matching case in the following list: if the element has an itemscope attribute the value is the item created by the element.
... in the following example, the "a" property has the values "1" and "2", in that order, but whether the "a" property comes before the "b" property or not is not important <div itemscope> <p itemprop="a">1</p> <p itemprop="a">2</p> <p itemprop="b">test</p> </div> the following is equivalent <div itemscope> <p itemprop="b">test</p> <p itemprop="a">1</p> <p itemprop="a">2</p> </div> as is the following <div...
... itemscope> <p itemprop="a">1</p> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> and the following <div id="x"> <p itemprop="a">1</p> </div> <div itemscope itemref="x"> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> other examples html <dl itemscope itemtype="http://vocab.example.net/book" itemid="urn:isbn:0-330-34032-8"> <dt>title <dd itemprop="title">the reality dysfunction <dt>author <dd itemprop="author">peter f.
Inline elements - HTML: Hypertext Markup Language
first, some simple css that we'll be using: .highlight { background-color:#ee3; } inline let's look at the following example which demonstrates an inline element: <div>the following span is an <span class="highlight">inline element</span>; its background has been colored to display both the beginning and end of the inline element's influence.</div> in this example, the <div> block-level element contains some text.
...because the <span> element is inline, the paragraph correctly renders as a single, unbroken text flow, like this: for looks, this css (not displayed in standard reading mode) is also used: body { margin: 0; padding: 4px; border: 1px solid #333; } .highlight { background-color:#ee3; } block-level now let's change that <span> into a block-level element, such as <p>: <div>the following paragraph is a <p class="highlight">block-level element;</p> its background has been colored to display both the beginning and end of the block-level element's influence.</div> the css (not displayed in standard reading mode) is also used: body { margin: 0; padding: 4px; border: 1px solid #333; } .highlight { background-color:#ee3; } rendered using the same css as before, we get: ...
...the <p> element totally changes the layout of the text, splitting it into three segments: the text before the <p>, then the <p>'s text, and finally the text following the <p>.
... list of "inline" elements the following elements are inline by default (although block and inline elements are no longer defined in html 5, use content categories instead): <a> <abbr> <acronym> <audio> (if it has visible controls) <b> <bdi> <bdo> <big> <br> <button> <canvas> <cite> <code> <data> <datalist> <del> <dfn> <em> <embed> <i> <iframe> <img> <input> <ins> <kbd> <label> <map> <mark> <meter> <nosc...
Content Security Policy (CSP) - HTTP
WebHTTPCSP
content-security-policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com here, by default, content is only permitted from the document's origin, with the following exceptions: images may load from anywhere (note the "*" wildcard).
... violation report syntax the report json object contains the following data: blocked-uri the uri of the resource that was blocked from loading by the content security policy.
...it uses the following policy, disallowing everything but stylesheets from cdn.example.com.
...a browser capable of enforcing csp would send the following violation report as a post request to http://example.com/_/csp-reports, when the document is visited: { "csp-report": { "document-uri": "http://example.com/signup.html", "referrer": "", "blocked-uri": "http://example.com/css/style.css", "violated-directive": "style-src cdn.example.com", "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-rep...
Using Feature Policy - HTTP
allowlist an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
...it has the following structure.
... for example, the following are equivalent: feature-policy: unsized-media 'none'; geolocation 'self' https://example.com; camera *; feature-policy: unsized-media 'none' feature-policy: geolocation 'self' https://example.com feature-policy: camera *; the iframe allow attribute the second way to use feature policy is for controlling content within an iframe.
... send the following the http header: feature-policy: layout-animations 'none'; unoptimized-images 'none'; oversized-images 'none'; sync-script 'none'; sync-xhr 'none'; unsized-media 'none'; using the <iframe> allow attribute: <iframe src="https://example.com..." allow="layout-animations 'none'; unoptimized-images 'none'; oversized-images 'none'; sync-script 'none'; sync-xhr 'none'; unsized-media 'none';"></iframe...
Set-Cookie - HTTP
it also must not contain a separator character like the following: ( ) < > @ , ; : \ " / [ ] ?
... lax: the cookie is withheld on cross-site subrequests, such as calls to load images or frames, but is sent when a user navigates to the url from an external site, such as by following a link.
... the following cookie will be rejected if set by a server hosted on originalcompany.com: set-cookie: qwerty=219ffwef9w0f; domain=somecompany.co.uk a cookie for a sub domain of the serving domain will be rejected.
... the following cookie will be rejected if set by a server hosted on example.com: set-cookie: sessionid=e8bb43229de9; domain=foo.example.com cookie prefixes cookies names prefixed with __secure- or __host- can be used only if they are set with the secure attribute from a secure (https) origin.
Firefox user agent string reference - HTTP
windows windows user agents have the following variations, where x.y is the windows nt version (for instance, windows nt 6.1).
... form factor gecko user agent string phone mozilla/5.0 (android 4.4; mobile; rv:41.0) gecko/41.0 firefox/41.0 tablet mozilla/5.0 (android 4.4; tablet; rv:41.0) gecko/41.0 firefox/41.0 focus for android from version 1, focus is powered by android webview and uses the following user agent string format: mozilla/5.0 (linux; <android version> <build tag etc.>) applewebkit/<webkit rev> (khtml, like gecko) version/4.0 focus/<focusversion> chrome/<chrome rev> mobile safari/<webkit rev> tablet versions on webview mirror mobile, but do not contain a mobile token.
...sion/4.0 klar/1.0 chrome/58.0.3029.83 mobile safari/537.36 4.1+ (webview) mozilla/5.0 (linux; android 7.0) applewebkit/537.36 (khtml, like gecko) version/4.0 focus/4.1 chrome/62.0.3029.83 mobile safari/537.36 6.0+ (geckoview) mozilla/5.0 (android 7.0; mobile; rv:62.0) gecko/62.0 firefox/62.0 focus for ios version 7 of focus for ios uses a user agent string with the following format: mozilla/5.0 (iphone; cpu iphone os 12_1 like mac os x) applewebkit/605.1.15 (khtml, like gecko) fxios/7.0.4 mobile/16b91 safari/605.1.15 note: this user agent was retrieved from an iphone xr simulator and may be different on device.
... firefox for fire tv version 3 (and probably earlier) of firefox for fire tv use a user agent string with the following format: mozilla/5.0 (linux; <android version>) applewebkit/537.36 (khtml, like gecko) version/4.0 focus/<firefoxversion> chrome/<chrome rev> safari/<webkit rev> firefox tv version user agent string v3.0 mozilla/5.0 (linux; android 7.1.2) applewebkit/537.36 (khtml, like gecko) version/4.0 focus/3.0 chrome/59.0.3017.125 safari/537.36 firefox for echo show from version 1.1, firefox for echo show uses a user agent string with the following format: mozilla/5.0 (linux; <android version>) applewebkit/537.36 (khtml, like gecko) version/4.0 focus/<firefoxversion> chrome/<chrome rev> safari/<webkit rev> firefox for echo show version user ag...
Introduction - JavaScript
what you should already know this guide assumes you have the following basic background: a general understanding of the internet and the world wide web (www).
... where to find javascript information the javascript documentation on mdn includes the following: learn web development provides information for beginners and introduces basic concepts of programming and the internet.
... in the following pages, this guide introduces you to the javascript syntax and language features, so that you will be able to write more complex applications.
...you will learn what these mean, but for now they can be thought of as doing the following: massively improve performance.
Deprecated and obsolete features - JavaScript
regexp properties the following properties are deprecated.
... rightcontext the substring following the most recent match.
... the following are now properties of regexp instances, no longer of the regexp object: property description global whether or not to test the regular expression against all possible matches in a string, or only against the first.
... the following traps are obsolete: hasown (bug 980565, firefox 33).
Array.prototype.sort() - JavaScript
so, the compare function has the following form: function compare(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } to compare numbers instead of strings, the compare function can simply subtract b from a.
... the following function will sort the array in ascending order (if it doesn't contain infinity and nan): function comparenumbers(a, b) { return a - b; } the sort method can be conveniently used with function expressions: var numbers = [4, 2, 5, 1, 3]; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5] es2015 provides arrow function expressions with even shorter syntax.
..., b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var namea = a.name.touppercase(); // ignore upper and lowercase var nameb = b.name.touppercase(); // ignore upper and lowercase if (namea < nameb) { return -1; } if (namea > nameb) { return 1; } // names must be equal return 0; }); examples creating, displaying, and sorting an array the following example creates four arrays and displays the original array, then the sorted arrays.
...orted without a compare function:', numericstringarray.sort()); console.log('sorted with comparenumbers:', numericstringarray.sort(comparenumbers)); console.log('mixednumericarray:', mixednumericarray.join()); console.log('sorted without a compare function:', mixednumericarray.sort()); console.log('sorted with comparenumbers:', mixednumericarray.sort(comparenumbers)); this example produces the following output.
Array - JavaScript
as a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true: console.log(years['2'] != years['02']) relationship between length and numerical properties a javascript array's length property and numerical properties are connected.
... to help explain these properties and elements, see this example and then refer to the table below: // match one d followed by one or more b's followed by one d // remember matched b's and the following d // ignore case const myre = /d(b+)(d)/i const myarray = myre.exec('cdbbdbsbz') the properties and elements returned from this match are as follows: property/element description example input read only the original string against which the regular expression was matched.
... examples creating an array the following example creates an array, msgarray, with a length of 0, then assigns values to msgarray[0] and msgarray[99], changing the length of the array to 100.
... let msgarray = [] msgarray[0] = 'hello' msgarray[99] = 'world' if (msgarray.length === 100) { console.log('the length is 100.') } creating a two-dimensional array the following creates a chessboard as a two-dimensional array of strings.
Function.prototype.bind() - JavaScript
a bound function has the following internal properties: [[boundtargetfunction]] the wrapped function object [[boundthis]] the value that is always passed as this value when calling the wrapped function.
... when a bound function is called, it calls internal method [[call]] on [[boundtargetfunction]], with following arguments call(boundthis, ...args).
...osest thing possible to the ecmascript 5 // internal iscallable function throw new typeerror('function.prototype.bind - ' + 'what is trying to be bound is not callable'); } return function(){ var funcargs = args.concat(slice.call(arguments)) return thatfunc.apply(thatarg, funcargs); }; }; })(); you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in implementations that do not natively support it.
... in the following piece of code, slice() is a bound function to the apply() function of function.prototype, with the this value set to the slice() function of array.prototype.
Object.prototype.constructor - JavaScript
let o = {} o.constructor === object // true let o = new object o.constructor === object // true let a = [] a.constructor === array // true let a = new array a.constructor === array // true let n = new number(3) n.constructor === number // true examples displaying the constructor of an object the following example creates a constructor (tree) and an object of that type (thetree).
... function tree(name) { this.name = name } let thetree = new tree('redwood') console.log('thetree.constructor is ' + thetree.constructor) this example displays the following output: thetree.constructor is function tree(name) { this.name = name } changing the constructor of an object the following example shows how to modify the constructor value of generic objects.
...tion () {}, math, new number(), 1, // remains unchanged new object(), {}, new regexp(), /(?:)/, new string(), 'test' // remains unchanged ] for (let i = 0; i < types.length; i++) { types[i].constructor = type types[i] = [types[i].constructor, types[i] instanceof type, types[i].tostring()] } console.log(types.join('\n')) this example displays the following output (comments added for reference): function type() {},false, // new array() function type() {},false, // [] function type() {},false,false // new boolean() function boolean() { [native code] },false,true // true function type() {},false,m...
... take the following case: the object has the create() method to create itself.
Object.defineProperties() - JavaScript
data descriptors and accessor descriptors may optionally contain the following keys: configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
... a data descriptor also has the following optional keys: value the value associated with the property.
... an accessor descriptor also has the following optional keys: get a function which serves as a getter for the property, or undefined if there is no getter.
... polyfill assuming a pristine execution environment with all names and properties referring to their initial values, object.defineproperties is almost completely equivalent (note the comment in iscallable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable.
Object.prototype.toString() - JavaScript
the following code illustrates this: const o = new object(); o.tostring(); // returns [object object] note: starting in javascript 1.8.5, tostring() called on null returns [object null], and undefined returns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata.
... the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); if you call the tostring() method on this custom object, it returns the default value inherited from object: thedog.tostring(); // return...
...s [object object] the following code creates and assigns dogtostring() to override the default tostring() method.
...ame + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; return ret; } or, using es6 template strings: dog.prototype.tostring = function dogtostring() { return `dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`; } with the preceding code in place, any time thedog is used in a string context, javascript automatically calls the dogtostring() function, which returns the following string: "dog gabby is a female chocolate lab" using tostring() to detect object class tostring() can be used with every object and (by default) allows you to get its class.
handler.defineProperty() - JavaScript
syntax const p = new proxy(target, { defineproperty: function(target, property, descriptor) { } }); parameters the following parameters are passed to the defineproperty() method.
... interceptions this trap can intercept these operations: object.defineproperty() reflect.defineproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be added, if the target object is not extensible.
... examples trapping of defineproperty the following code traps object.defineproperty().
...st p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); return true; } }); const desc = { configurable: true, enumerable: true, value: 10 }; object.defineproperty(p, 'a', desc); // "called: a" when calling object.defineproperty() or reflect.defineproperty(), the descriptor passed to defineproperty() trap has one restriction—only following properties are usable (non-standard properties will be ignored): enumerable configurable writable value get set const p = new proxy({}, { defineproperty(target, prop, descriptor) { console.log(descriptor); return reflect.defineproperty(target, prop, descriptor); } }); object.defineproperty(p, 'name', { value: 'proxy', type: 'custom' }); // { value: 'proxy' } specific...
handler.get() - JavaScript
syntax const p = new proxy(target, { get: function(target, property, receiver) { } }); parameters the following parameters are passed to the get() method.
... interceptions this trap can intercept these operations: property access: proxy[foo]and proxy.bar inherited property access: object.create(proxy)[foo] reflect.get() invariants if the following invariants are violated, the proxy will throw a typeerror: the value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property.
... examples trap for getting a property value the following code traps getting a property value.
... const p = new proxy({}, { get: function(target, property, receiver) { console.log('called: ' + property); return 10; } }); console.log(p.a); // "called: a" // 10 the following code violates an invariant.
handler.getOwnPropertyDescriptor() - JavaScript
syntax const p = new proxy(target, { getownpropertydescriptor: function(target, prop) { } }); parameters the following parameters are passed to the getownpropertydescriptor() method.
... interceptions this trap can intercept these operations: object.getownpropertydescriptor() reflect.getownpropertydescriptor() invariants if the following invariants are violated, the proxy will throw a typeerror: getownpropertydescriptor() must return an object or undefined.
... examples trapping of getownpropertydescriptor the following code traps object.getownpropertydescriptor().
... const p = new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(object.getownpropertydescriptor(p, 'a').value); // "called: a" // 10 the following code violates an invariant.
handler.has() - JavaScript
syntax const p = new proxy(target, { has: function(target, prop) { } }); parameters the following parameters are passed to has() method.
... interceptions this trap can intercept these operations: property query: foo in proxy inherited property query: foo in object.create(proxy) with check: with(proxy) { (foo); } reflect.has() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
... examples trapping the in operator the following code traps the in operator.
... const p = new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return true; } }); console.log('a' in p); // "called: a" // true the following code violates an invariant.
handler.isExtensible() - JavaScript
syntax const p = new proxy(target, { isextensible: function(target) { } }); parameters the following parameter is passed to the isextensible() method.
... interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the following invariants are violated, the proxy will throw a typeerror: object.isextensible(proxy) must return the same value as object.isextensible(target).
... examples trapping of isextensible the following code traps object.isextensible().
... const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant.
handler.ownKeys() - JavaScript
syntax const p = new proxy(target, { ownkeys: function(target) { } }); parameters the following parameter is passed to the ownkeys() method.
... interceptions this trap can intercept these operations: object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() invariants if the following invariants are violated, the proxy will throw a typeerror: the result of ownkeys() must be an array.
... examples trapping of getownpropertynames the following code traps object.getownpropertynames().
... const p = new proxy({}, { ownkeys: function(target) { console.log('called'); return ['a', 'b', 'c']; } }); console.log(object.getownpropertynames(p)); // "called" // [ 'a', 'b', 'c' ] the following code violates an invariant.
handler.preventExtensions() - JavaScript
syntax const p = new proxy(target, { preventextensions: function(target) { } }); parameters the following parameter is passed to the preventextensions() method.
... interceptions this trap can intercept these operations: object.preventextensions() reflect.preventextensions() invariants if the following invariants are violated, the proxy will throw a typeerror: object.preventextensions(proxy) only returns true if object.isextensible(proxy) is false.
... examples trapping of preventextensions the following code traps object.preventextensions().
... const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant.
String.prototype.indexOf() - JavaScript
for example, the following expression returns -1: 'blue whale'.indexof('blue') // returns -1 checking occurrences note that 0 doesn't evaluate to true and -1 doesn't evaluate to false.
... therefore, when checking if a specific string exists within another string, the correct way to check would be: 'blue whale'.indexof('blue') !== -1 // true 'blue whale'.indexof('bloe') !== -1 // false ~('blue whale'.indexof('bloe')) // 0, which is falsy examples using indexof() the following example uses indexof() to locate values in the string "brave new world".
... const str = 'brave new world' console.log('index of first w from start is ' + str.indexof('w')) // logs 8 console.log('index of "new" from start is ' + str.indexof('new')) // logs 6 indexof() and case-sensitivity the following example defines two string variables.
... const mystring = 'brie, pepper jack, cheddar' const mycapstring = 'brie, pepper jack, cheddar' console.log('mystring.indexof("cheddar") is ' + mystring.indexof('cheddar')) // logs 19 console.log('mycapstring.indexof("cheddar") is ' + mycapstring.indexof('cheddar')) // logs -1 using indexof() to count occurrences of a letter in a string the following example sets count to the number of occurrences of the letter e in the string str: const str = 'to be, or not to be, that is the question.' let count = 0 let position = str.indexof('e') while (position !== -1) { count++ position = str.indexof('e', position + 1) } console.log(count) // displays 4 specifications specification ecmascript (ecma-262)the definition of '...
yield - JavaScript
description the yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller.
...each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's new value.
... unfortunately, next() is asymmetric, but that can’t be helped: it always sends a value to the currently suspended yield, but returns the operand of the following yield.
... examples using yield the following code is the declaration of an example generator function.
switch - JavaScript
if no default clause is found, the program continues execution at the statement following the end of switch.
... the optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch.
... examples using switch in the following example, if expr evaluates to bananas, the program matches the value with case case 'bananas' and executes the associated statement.
... when break is encountered, the program breaks out of switch and executes the statement following switch.
throw - JavaScript
each of the following throws an exception: throw 'error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw true; // generates an exception with the value true throw new error('required'); // generates an error object with the message of required also note that the throw statement is affected by automatic semicolon insertion (asi) as no line termin...
...the following example creates an object of type userexception and uses it in a throw statement.
...) { return months[mo]; } else { throw new userexception('invalidmonthno'); } } try { // statements to try var mymonth = 15; // 15 is out of bound to raise the exception var monthname = getmonthname(mymonth); } catch (e) { monthname = 'unknown'; console.error(e.message, e.name); // pass exception object to err handler } another example of throwing an object the following example tests an input string for a u.s.
...the following example catches an exception with a numeric value and rethrows it if the value is over 50.
Template literals (Template strings) - JavaScript
using normal strings, you would have to use the following syntax in order to get multi-line strings: console.log('string text line 1\n' + 'string text line 2'); // "string text line 1 // string text line 2" using template literals, you can do the same like this: console.log(`string text line 1 string text line 2`); // "string text line 1 // string text line 2" expression interpolation in order to embed expressions within normal strings, you would u...
...se the following syntax: let a = 5; let b = 10; console.log('fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.'); // "fifteen is 15 and // not 20." now, with template literals, you are able to make use of the syntactic sugar, making substitutions like this more readable: let a = 5; let b = 10; console.log(`fifteen is ${a + b} and not ${2 * a + b}.`); // "fifteen is 15 and // not 20." nesting templates in certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings.
...(alternatively, it can return something completely different, as described in one of the following examples.) the name of the function used for the tag can be whatever you want.
... let str = string.raw`hi\n${2+3}!`; // "hi\n5!" str.length; // 6 array.from(str).join(','); // "h,i,\,n,5,!" tagged templates and escape sequences es2016 behavior as of ecmascript 2016, tagged templates conform to the rules of the following escape sequences: unicode escapes started by "\u", for example \u00a9 unicode code point escapes indicated by "\u{}", for example \u{2f804} hexadecimal escapes started by "\x", for example \xa9 octal literal escapes started by "\0o" and followed by one or more digits, for example \0o251 this means that a tagged template like the following is problematic, because, per ecmascript grammar, a...
MathML documentation index - MathML
WebMathMLIndex
10 <maction> mathml, mathml reference, mathml:element, mathml:enlivening expressions the following example uses the "toggle" actiontype: 11 <math> mathml, mathml reference, mathml:element the top-level element in mathml is <math>.
...use the following syntax: <mover> base overscript </mover> 23 <mpadded> mathml, mathml reference, mathml:element, mathml:general layout schemata the mathml <mpadded> element is used to add extra padding and to set the general adjustment of position and size of enclosed contents.
...the square root accepts only one argument, which leads to the following syntax: <msqrt> base </msqrt>.
...it uses the following syntax: <munder> base underscript </munder> 39 <munderover> mathml, mathml reference, mathml:element, mathml:script and limit schemata the mathml <munderover> element is used to attach accents or limits both under and over an expression.
Autoplay guide for media and Web Audio APIs - Web media technologies
that means that both of the following are considered autoplay behavior, and are therefore subject to the browser's autoplay blocking policy: <audio src="/music.mp4" autoplay> and audioelement.play(); the following web features and apis may be affected by autoplay blocking: the html <audio> and <video> elements the web audio api from the user's perspective, a web page or app that spontaneously starts making noise without war...
... autoplay availability as a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true: the audio is muted or its volume is set to 0 the user has interacted with the site (by clicking, tapping, pressing keys, etc.) if the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features if the autoplay feature policy is used to grant autoplay support to an <iframe> and its document.
...this sets the autoplay property on the element to true, and when autoplay is true, the media will automatically begin to play as soon as possible after the following have occurred: the page is allowed to use autoplay functionality the element has been created during page load enough media has been received to begin playback and continue to play through to the end of the media without interruption, assuming there are no dramatic changes in network performance or bandwidth.
...ument's domain to use the feature-policy header to only allow media to autoplay from the document's origin: feature-policy: autoplay 'self' to do the same for an <iframe>: <iframe src="mediaplayer.html" allow="autoplay 'src'"> </iframe> example: allowing autoplay and fullscreen mode adding fullscreen api permission to the previous example results in a feature-policy header like the following if fullscreen access is allowed regardless of the domain; a domain restriction can be added as well as needed.
Image file type and format guide - Web media technologies
image file type details the following sections provide a brief overview of each of the image file types supported by web browsers.
... 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.
...following the directory comes the data for the icons.
...for example, the following code represents an xbm image which is 8 pixels by 8 pixels, with those pixels in a black-and-white checkerboard pattern: #define square8_width 8 #define square8_height 8 static unsigned char square8_bits[] = { 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 }; mime type image/xbm, image-xbitmap file extension(s) .xbm specification none browser comp...
Codecs used by WebRTC - Web media technologies
for details on webrtc-related considerations for each codec, see the sub-sections below by following the links on each codec's name.
...those are listed in the following table.
...those are listed in the following table.
... bit rate recommendations given a 20 millisecond frame size, the following table shows the recommended bit rates for various forms of media.
requiredFeatures - SVG: Scalable Vector Graphics
feature strings the following are the feature strings for the requiredfeatures attribute.
... http://www.w3.org/tr/svg11/feature#svg at least one of the following feature is supported: http://www.w3.org/tr/svg11/feature#svg-static http://www.w3.org/tr/svg11/feature#svg-animation http://www.w3.org/tr/svg11/feature#svg-dynamic http://www.w3.org/tr/svg11/feature#svgdom http://www.w3.org/tr/svg11/feature#svgdom at least one of the following feature is supported: http://www.w3.org/tr/svg11/feature#svgdom-static http://www.w3.org/tr/svg...
...11/feature#svgdom-animation http://www.w3.org/tr/svg11/feature#svgdom-dynamic http://www.w3.org/tr/svg11/feature#svg-static the browser supports all the following features: http://www.w3.org/tr/svg11/feature#coreattribute http://www.w3.org/tr/svg11/feature#structure http://www.w3.org/tr/svg11/feature#containerattribute http://www.w3.org/tr/svg11/feature#conditionalprocessing http://www.w3.org/tr/svg11/feature#image http://www.w3.org/tr/svg11/feature#style http://www.w3.org/tr/svg11/feature#viewportattribute http://www.w3.org/tr/svg11/feature#shape http://www.w3.org/tr/svg11/feature#text http://www.w3.org/tr/svg11/feature#paintattribute http://www.w3.org/tr/svg11/feature#opacityattribute http://www.w3.org/tr/svg11/feature#graphicsattribute http://www.w3.org/tr/...
... http://www.w3.org/tr/svg11/feature#svg-dynamic the browser supports all of the language features from http://www.w3.org/tr/svg11/feature#svg-animation plus the following features: http://www.w3.org/tr/svg11/feature#hyperlinking http://www.w3.org/tr/svg11/feature#scripting http://www.w3.org/tr/svg11/feature#view http://www.w3.org/tr/svg11/feature#cursor http://www.w3.org/tr/svg11/feature#graphicaleventsattribute http://www.w3.org/tr/svg11/feature#documenteventsattribute http://www.w3.org/tr/svg11/feature#animationeventsattribute http://www.w3...
SVG animation with SMIL - SVG: Scalable Vector Graphics
animating attributes of an element the following example animates the cx attribute of a circle.
...itle> <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> <rect x="0" y="50" width="15" height="34" fill="blue" stroke="black" stroke-width="1"> <animatetransform attributename="transform" begin="0s" dur="20s" type="rotate" from="0 60 60" to="360 100 60" repeatcount="indefinite" /> </rect> </svg> animation following a path the <animatemotion> element lets you animate an element position and rotation according to a path.
...you can set the attribute to define whether the object rotates following the tangent of the path.
...tle>svg smil animate with path</title> <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> <circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="3s" repeatcount="indefinite" /> </circle> </svg> view live sample example 2: curved motion same example as before with a curved path and following the direction of the path.
Same-origin policy - Web security
(a "tuple" is a set of items that together comprise a whole — a generic form for double/triple/quadruple/quintuple/etc.) the following table gives examples of origin comparisons with the url http://store.company.com/dir/page.html: url outcome reason http://store.company.com/dir2/other.html same origin only the path differs http://store.company.com/dir/inner/another.html same origin only the path differs https://store.company.com/page.html failure different protocol ...
... for example, assume a script from the document at http://store.company.com/dir/other.html executes the following: document.domain = "company.com"; afterward, the page can pass the same-origin check with http://company.com/dir/page.html (assuming http://company.com/dir/page.html sets its document.domain to "company.com" to indicate that it wishes to allow that - see document.domain for more).
... window the following cross-origin access to these window properties is allowed: methods window.blur window.close window.focus window.postmessage attributes window.closed read only.
... location the following cross-origin access to location properties is allowed: methods location.replace attributes urlutils.href write-only.
Introduction to using XPath in JavaScript - XPath
simple types when the desired result type in resulttype is specified as either: number_type - a double string_type - a string boolean_type - a boolean we obtain the returned value of the expression by accessing the following properties respectively of the xpathresult object.
... numbervalue stringvalue booleanvalue example the following uses the xpath expression count(//p) to obtain the number of <p> elements in an html document: var paragraphcount = document.evaluate( 'count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.numbervalue + ' paragraph elements' ); although javascript allows us to convert the number to a string for display, the xpath interface will not automatically convert the numerical result if the stringvalue property is requested, so the following code will not work: var paragraphcount = document.evaluate('count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.stringvalue + ' paragraph elements' ); instead, it will return an except...
...none yet =====any_type example===== <pre> </pre> examples within an html document the following code is intended to be placed in any javascript fragment within or linked to the html document against which the xpath expression is to be evaluated.
... evaluating against an xml document within an extension the following uses an xml document located at chrome://yourextension/content/peopledb.xml as an example.
Compiling from Rust to WebAssembly - WebAssembly
install rust install rust by going to the install rust page and following the instructions.
...to download and install it, enter the following command into your terminal: $ cargo install wasm-pack install node.js we are building an npm package in this tutorial, and so you need to have node.js and npm installed.
...$ mkdir site $ cd site $ npm link hello-wasm create a new file, package.json, and put the following code in it: { "scripts": { "serve": "webpack-dev-server" }, "dependencies": { "hello-wasm": "^0.1.0" }, "devdependencies": { "webpack": "^4.25.1", "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.10" } } note that you need to fill in your own username, after the @, in the dependencies section.
...create webpack.config.js and put the following in it: const path = require('path'); module.exports = { entry: "./index.js", output: { path: path.resolve(__dirname, "dist"), filename: "index.js", }, mode: "development" }; now we need an html file; create index.html and give it the following contents: <!doctype html> <html> <head> <meta charset="utf-8"> <title>hello-wasm example</title> </head> <body> <script src="./index.js"></script> </body> </html> finally, create the index.js referenced in the html file and give it these contents: const js = import("./node_modules/hello-wasm/hello_wasm.js"); js.then(js => { js.greet("webassembly"); }); note that you need to fill in your npm username again.
Working with Events - Archive of obsolete content
for example, the following add-on registers a listener with the tabs module to listen for the ready event, and logs a string to the console reporting the event: var tabs = require("sdk/tabs"); tabs.on("ready", function () { console.log("tab loaded"); }); it is not possible to enumerate the set of listeners for a given event.
... the following add-on creates a button and assigns a listener to the onclick property of the options object supplied to the button's constructor.
... in the following add-on, we add two listeners to the tabs module's ready event.
widget - Archive of obsolete content
this may take one of the following values: "start": load content scripts immediately after the document element for the widget is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the widget has been loaded...
...this may have one of the following values: "start": load content scripts immediately after the document element for the widget is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the widget has been loaded, at the time th...
...this may have one of the following values: "start": load content scripts immediately after the document element for the widget view is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the widget view has been loaded, at t...
content/loader - Archive of obsolete content
example: the following code creates a wrapper on a hidden frame that reloads a web page in the frame every time the contenturl property is changed: var hiddenframes = require("sdk/frame/hidden-frame"); var { loader } = require("sdk/content/content"); var pageloader = loader.compose({ constructor: function pageloader(options) { options = options || {}; if (options.contenturl) this.contenturl = options.c...
...this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the wi...
... allow permissions for the content, with the following keys: ...
content/symbiont - Archive of obsolete content
this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at...
... allow object permissions for the content, with the following keys: script boolean whether or not to execute script in the content.
...this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the wi...
window/utils - Archive of obsolete content
options : object options for the function, with the following properties: name type parent nsidomwindow parent for the new window.
... parameters options : object options for the function, with the following properties: name type url string uri of the document to be loaded into the window.
... options : object options object containing the following property: name type includeprivate boolean whether to include private windows.
package.json - Archive of obsolete content
"name": "my-addon", "title": "my-addon", "id": "jid1-1fergv45e4f4f@jetpack", "description": "a basic add-on", "author": "", "license": "mpl-2.0", "version": "0.1" } if you are using the new jpm tool, you can easily access manifest data from package.json by requiring it like any other module: var title = require("./package.json").title; key reference package.json may contain the following keys: author the name of the package's original author; this could be the name of a person or a company.
... locales an object holding json objects referenced by a locale name that use the following keys: title, description and homepage.
... preferences an array of json objects that use the following keys: name,type, value, title, and description.
Unit Testing - Archive of obsolete content
now create a new file called "base64.js", and give it the following contents: const { atob, btoa } = require("resource://gre/modules/services.jsm"); exports.atob = a => atob(a); exports.btoa = b => btoa(b); this code exports two functions, which just call the platform's btoa() and atob() functions.
...if we run the add-on and click the button, we should see the following logging output: info: agvsbg8= info: hello testing the base64 module navigate to the add-on's test directory and delete the test-index.js file.
... in its place create a file called test-base64.js with the following contents: var base64 = require("../base64"); exports["test atob"] = function(assert) { assert.ok(base64.atob("agvsbg8=") == "hello", "atob works"); } exports["test btoa"] = function(assert) { assert.ok(base64.btoa("hello") == "agvsbg8=", "btoa works"); } exports["test empty string"] = function(assert) { assert.throws(function() { base64.atob(); }, "empty string check works"); } require("sdk/test").run(exports); note that with jpm we must give the exact relative path to the base64.js module.
Dialogs and Prompts - Archive of obsolete content
simple dialog code the following xul code defines a simple dialog with two buttons, ok and cancel (buttons="accept,cancel" attribute on dialog).
...for example, to add an apply button to your dialog, use the following code: <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="..." buttons="accept,cancel,extra1" ondialogaccept="onaccept();" ondialogextra1="onapply();" buttonlabelextra1="apply" buttonaccesskeyextra1="a"> <!-- content --> </dialog> you can even get the element object for any of predefined buttons with gdialog.getbutton(dlgtype);, where gdialog is the <...
... passing arguments and displaying a dialog the following code demonstrates how to pass custom arguments to a dialog, process those arguments in the dialog, and return user-modified arguments to the caller.
File I/O - Archive of obsolete content
however, you can enumerate available drives using the following code: components.utils.import("resource://gre/modules/fileutils.jsm"); var root = new fileutils.file("\\\\."); var drivesenum = root.directoryentries, drives = []; while (drivesenum.hasmoreelements()) { drives.push(drivesenum.getnext().
... storing nsifile in preferences the following two snippets show the right way to store a file path in user preferences (more about preferences in mozilla): absolute path (nsifile) to store an arbitrary path in user preferences, use this code: // |file| is nsilocalfile.
...read path from prefs var file = prefs.getcomplexvalue("filename", components.interfaces.nsilocalfile); relative path (nsirelativefilepref) to store paths relative to one of the predefined folders listed above, for example file relative to profile folder, use the following code: // 1.
Windows - Archive of obsolete content
example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typeerror from firefox console.
...the following code does not care which element is clicked on, simply responding to all mousedown events equally.
...for example, the following code will add a horizontal rule.
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
add the following line at the end of the file: ac_add_options --enable-extensions=default,myextension now launch make from the mozilla root: make -f client.mk build even if you have an up-to-date firefox build, you'll have to wait a while for make to recurse over the entire mozilla source tree looking for new stuff (on my machine, which is pretty fast, this takes a good 10-15 minutes).
...you also have to make one small change to the makefile in the same directory, adding the following line: use_extension_manifest = 1 this tells make to create a single manifest file called chrome.manifest instead of creating separate manifests with goofy names for each package.
...the following makefile rule can be used to copy these files into the final target directory of the extension: export:: if test !
Jetpack Processes - Archive of obsolete content
privileged apis when script is evaluated in a jetpack process via a call to nsijetpack.evalscript(), the script's global scope is endowed with the following privileged apis: sendmessage(amessagename [, v1 [, v2 [, ...]]]) similar to nsijetpack.sendmessage(), this function asynchronously sends a message to the chrome process.
...handles have the following native methods and properties: invalidate() invalidates the handle.
...the error object contains the following properties: filename, linenumber, and message.
Listening to events in Firefox extensions - Archive of obsolete content
simple dom events registering for a dom event is done using with code such as the following: function callback(evt) { // do your processing here.
...both browser and tabbrowser elements support the following: var progresslistener = { // add nsiwebprogressimplementation here } b.addprogresslistener(progresslistener); where b is the browser or tabbrowser you want to listen to events for.
...in order to listen to events from all browsers, including those not currently being displayed, the following example can be used: var tabsprogresslistener = { // add tabs progress listener implementation here } gbrowser.addtabsprogresslistener(tabsprogresslistener); this lets you receive events related to all tabs.
Chapter 1: Introduction to Extensions - Archive of obsolete content
« previousnext » note: if you want contribute to this document please following guidelines from the contribute page.
... the add-ons manager handles the following tasks: safely installs and uninstalls add-ons makes sure add-ons are compatible with the version of firefox you're using manages a whitelist of sites trusted for installing add-ons helps troubleshoot add-ons by disabling them and offering a safe mode confirms and runs updates provides access to add-ons' settings dialogs provides access to add-ons' support sites development environment ...
...the following chapters explain in detail the extension-writing techniques of some of japan's leading extension authors.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
<hbox> <label value="label1" flex="1" style="border: 1px solid;"/> <label value="label2" flex="2" style="border: 1px solid;"/> </hbox> listing 4: growing with flex figure 3: output of listing 4 ordinal within a xul box, elements will ordinarily be laid out following their order of appearance in the source code (laid out left to right or top to bottom).
... key keycode name return vk_return enter vk_enter backspace vk_back_space delete vk_delete escape vk_escape ↑ vk_up ↓ vk_down ← vk_left → vk_right table 3: typical keycode names using modifier keys use the modifiers attribute with one or more of the following comma-delimited values: "control", "alt", "shift", and "meta" in order to limit the use of keyboard shortcuts to only operate when those modifier keys are pressed together with another key.
... figure 20: output from listing 23 and 25 furthermore, following the declaration insertbefore="label1", the "button2" button now has been inserted before the element with the id "label1".
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
the following methods will all safely create a dom tree without risk of remote execution.
...it is safe, though inefficient, to assign dynamic values to innerhtml if any dynamic content in the value is escaped with the following function: function escapehtml(str) { return str.replace(/[&"'<>]/g, (m) => ({ "&": "&amp;", '"': "&quot;", "'": "&#39;", "<": "&lt;", ">": "&gt;" })[m]); } or slightly more verbose, but slightly more efficient: function escapehtml(str) { return str.replace(/[&"'<>]/g, (m) => escapehtml.replacements[m]); } escapehtml.replacements = { "&": "&amp;", '"': "&quot;", "'": "&#39;", "<": "&lt;", ">": ...
...the following two code fragments are roughly equivalent: function clickify(elem, address) { elem.addeventlistener("click", function (event) { openwindow(address) }, false); } function clickify(elem, address) { elem.onclick = function (event) { openwindow(address) }; } multiple attributes sometimes there is a need for event listeners to appear as attributes in the dom.
Handling Preferences - Archive of obsolete content
to open the preferences window in firefox, select the following from the main menu: on windows, tools > options on mac, firefox > preferences on linux, edit > preferences note: keep in mind the usage of the terms "preferences" and "options" in different platforms.
...the following files are used: default preferences: these are stored in the directory defaults/pref in the firefox installation directory.
...in order to have this button enabled in your extension you need to add the following line to install.rdf: <em:optionsurl>chrome://xulschoolhello/content/preferenceswindow.xul</em:optionsurl> if you want to open this window from a different place in the ui, such as a menu item or a button in a toolbar, you need to take into account that the opening behavior of a preferences window is different depending on the operating system.
JavaScript Object Management - Archive of obsolete content
once you have this working right, try the following: open the message a few times, so that the number increments.
... module files can be imported to a chrome script or to other code modules with the following line: components.utils.import("resource://xulschoolhello/messagecount.js"); when using components.utils.import, code modules must be loaded using a file: or resource: url pointing to a file on the disk.
...in the following section we'll discuss xpcom, which is an older alternative to jsm and one of the foundations of mozilla applications.
Local Storage - Archive of obsolete content
having that function in place, we do something like the following: let myfile = xulschool.getlocaldirectory(); myfile.append("somefile.txt"); // do stuff with the file.
...in the initialization method of your one of your "common" or startup objects, add the following code: let formatter = new log4moz.basicformatter(); let root = log4moz.repository.rootlogger; let logfile = this.getlocaldirectory(); // remember this?
... and then logging is done with any of the following methods, depending on the kind of message being logged: this._logger.fatal("this is a fatal message."); this._logger.error("this is an error message."); this._logger.warn("this is a warning message."); this._logger.info("this is an info message."); this._logger.config("this is a config message."); this._logger.debug("this is a debug message."); this._logger.trace("this is a trace message."); y...
Getting Started - Archive of obsolete content
skin\classic classic contains the following directories.
...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:maxversion>max_sm_version</em:maxversion> </description> </em:targetapplication> establishing both minimum and maximum compatible versions lets you avoid conflicts with versions of seamo...
...more after i get done with some tests repackaging jar now all you need to do is repackage a jar file with the following directory structure, using your favorite archive manager to create a zip archive: /chrome/my_theme.jar!/communicator/* /chrome/my_theme.jar!/editor/* /chrome/my_theme.jar!/global/* /chrome/my_theme.jar!/help/* /chrome/my_theme.jar!/messenger/* /chrome/my_theme.jar!/messenger-newsblog/* /chrome/my_theme.jar!/mozapps/* /chrome/my_theme.jar!/navigator/* /chrome.manifest /install.rdf /icon.png /previ...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
skin\classic classic contains the following directories.
... 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>max_ff_version</em:maxversion> </description> </em:targetapplication> establishing both minimum and maximum compatible versions lets you avoid conflicts with versions of firef...
... repackaging jar now all you need to do is repackage a jar file with the following directory structure, using your favorite archive manager to create a zip archive: /browser/* /communicator/* /global/* /help/* /mozapps/* /contents.rdf /install.rdf /icon.png /preview.png make sure not to just zip up the my_theme parent directory since that will cause the drag and drop install in the next section to fail without error messages.
Dehydra Function Reference - Archive of obsolete content
gcc command line -fplugin=/path/to/gcc_dehydra.so -fplugin-arg-gcc_dehydra=/path/to/your/script.js callback functions the following functions may be provided by the analysis script and will be called by dehydra while compiling.
...builtin functions the following functions are provided by dehydra and may be called by the user: print(msg) print a string to stdout (or stderr if the compiler is piping output).
...the default value is the following directories: the directory of the dehydra script being processed the libs directory next to the gcc_dehydra.so plugin user script may add additional directories sys.aux_base_name exposes the base filename part of the file being compiled sys.frontend exposes the compiler frontend (e.g.
Drag and Drop JavaScript Wrapper - Archive of obsolete content
the following is an example of calling the nsdraganddrop object.
...if we wanted to handle the other cases also, we can call the other functions, as in the following example: <description value="click and drag this text." ondraggesture="nsdraganddrop.startdrag(event,textobserver)" ondragover="nsdraganddrop.dragover(event,textobserver)" ondragexit="nsdraganddrop.dragexit(event,textobserver)" ondragdrop="nsdraganddrop.drop(event,textobserver)" /> as mentioned earlier, there is nothing special that happens dur...
...the following table describes some of the flavours you might use.
Documentation for BiDi Mozilla - Archive of obsolete content
bidi processing for a given html document will only take place if one of the following is true: the page includes a hebrew or arabic character or a hindi digit.
...in a bidi-enabled document, the following things happen: during a reflow, nsbidipresutils::resolve is called.
... framemanager::setframeproperty is used to set the following flags and pointers (for terminology see the specification of the uba): embeddinglevel: the embedding level of the frame textclass: the text class of the frame.
Introducing the Audio API extension - Archive of obsolete content
this event has the following attributes: mozchannels: number of channels mozsamplerate: sample rate per second mozframebufferlength: number of samples collected in all channels this information is needed later to decode the audio data stream.
... the following example extracts the data from an audio element: <!doctype html> <html> <head> <title>javascript metadata example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> the mozaudioavailable event as the audio is played, sample data is made available to the audio layer and the audio buffer (size defined in mo...
...you can see an example below: // write samples using a js array var samples = [0.242, 0.127, 0.0, -0.058, -0.242, ...]; var numbersampleswritten = audiooutput.mozwriteaudio(samples); // write samples using a typed array var samples = new float32array([0.242, 0.127, 0.0, -0.058, -0.242, ...]); var numbersampleswritten = audiooutput.mozwriteaudio(samples); in the following example, we create an audio pulse: <!doctype html> <html> <head> <title>generating audio in real time</title> <script type="text/javascript"> function playtone() { var output = new audio(); output.mozsetup(1, 44100); var samples = new float32array(22050); for (var i = 0; i < samples.length ; i++) { samples[i] = math.sin( i / 20 ); } ...
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
creating menuitems to pass a new menuitem into the api, pass one of the following types: null a simple menu separator.
...they are: add(items) clear() insertbefore(newitems, target) remove(target) replace(target, newitems) reset() set(items) the following jetpack.menu properties can also be defined on a contextmenuset: beforehide beforeshow note that a jetpack.menu object is passed to beforehide and beforeshow, since they are called during a context menu's invocation.
...they have the following properties: property description node the dom node on which the menu is shown.
Selection - Archive of obsolete content
this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user.
... jetpack.import.future("selection");var textofsel = jetpack.selection.text;var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user.
...function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select.
Selection - Archive of obsolete content
this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user.
... jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user.
...function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select.
Selection - Archive of obsolete content
ArchiveMozillaJetpackdocsUISelection
this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user.
... jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user.
...function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select.
Mozilla Crypto FAQ - Archive of obsolete content
however, in an advisory opinion issued in reference to the bernstein case, the bureau of export administration (bxa) has stated the following: "concerning the posting onto a mirror or archive site of already-posted source code, notification is required only for the initial posting." bxa and nsa have already been notified of the posting of encryption-related source code on the mozilla site, and in light of this opinion we have therefore decidednot to ask mirror sites to provide notification themselves.
...export control of encryption software and related topics, see the following online references: the itar, ear and encryption export archive maintained by the electronic freedom foundation (eff).
... the following books may also be of interest if you want to know more about the history and politics of u.s.
Nanojit - Archive of obsolete content
example the following code works with spidermonkey's hacked version of nanojit.
... figuring out how to compile it is left as an exercise for the reader; the following works when run in the object directory of an --enable-debug spidermonkey shell: g++ -ddebug -g3 -wno-invalid-offsetof -fno-rtti -include js-confdefs.h -i dist/include/ -i..
...(typedef js_fastcall int32_t (*addtwofn)(int32_t); ) then, printf is hardcoded to call it with a parameter 5, and on linking with nanojit library, the following program will display 2+5=7 now, what i need to do is generate output for this: start two = int 2 twoplustwo = add two, two ret twoplustwo this adds two and two in the most hardcoded way possible.
Scripting - Archive of obsolete content
it can contain the following functions: startup when the app starts, before the user interface is displayed.
...the platform property implements the nsiplatformglue interface, whose methods are described in the following section.
...the following code can be used by web content to determine whether it is running in prism: if ("platform" in window) { // prism-specific code goes here } see the nsiplatformglue idl definition file for details of the methods available to prism apps.
Supporting private browsing mode - Archive of obsolete content
} in addition, you can install watcher functions to be called when private browsing turns on and off, as shown in the following example.
...for example, if you want to use a different background color for the url bar when in private browsing mode, you could do the following: [browsingmode=private] #urlbar { -moz-appearance: none; background: #eee } similarly, if you want to theme the firefox button in firefox 4 differently when private browsing mode is permanent: #main-window[privatebrowsingmode=temporary] #appmenu-button:not(:-moz-window-inactive) { -moz-border-left-colors: rgba(255,255,255,.5) rgba(43,8,65,.9); -moz-border-bottom-colors: rgba(255,255,255,...
...the following categories define what's considered "sensitive" data: the urls of pages the user has visited.
Tamarin mercurial commit hook - Archive of obsolete content
the hook is located in the tamarin-redux repository in the file utils/hooks/tamarin-commit-hook.py this is a simple mercurial hook that checks the following filetypes ('.cpp', '.h', '.as', '.abs', '.py') for the following: tabs anywhere in the line trailing whitespace windows line endings (\r\n) "mark_security_change" - looks for this text and warns user as security changes should not be checked into the public tamarin-redux repository.
... installing the commit hook the easiest way to implement the hook is to sync to the tip of tamarin-redux then add the following to your tamarin-redux/.hg/hgrc file (or to ~/.hgrc to implement for all local repos): [hooks] pretxncommit.commit = python:/path/to/tamarin-redux/utils/hooks/tamarin-commit-hook.py:master_hook once added, all commits will run the commit hook.
... when a violation is found the following will be displayed: > hg commit -m "change with a tab" tab(s) found in test/test.txt for rev 1458 (change 53543674b8e6): @@ -65,4 +65,6 @@ +# tab here ^ (n)o, (y)es, (a)llow tabs for current file are you sure you want to commit this change?
Binding Implementations - Archive of obsolete content
the following is currently not implemented in mozilla, it seems.
... note: the following paragraphs suggest a syntax for how javascript might enable access to base class methods and properties.
... for example, given a binding with an implementation colorpickergrid that derives from an implementation colorpicker where the two implementations both specify the setcolor method, a caller could invoke colorpicker's method with the following syntax: ...
Creating XPI Installer Modules - Archive of obsolete content
package creation overview this tutorial describes the following sequence of steps for creating a new package: developing the resources organizing the resources creating the contents.rdf file making the barley install script creating a xpi you can examine (or install!) the package described here by downloading the barley xpi file and using a zip unarchiver[zip] to open it.
...in the following listing, the items in red are particular to the barley package and can be edited for your own distribution: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <!-- list all the packages being supplied --> <rdf:seq about="urn:mozilla:package:root"> <rdf:li resource="urn:mozilla:package:barley"/> </rdf:se...
...the archive, named barley.xpi, should contain the following two files: barley.jar install.js this zip file, when opened from mozilla using file -> open, will initialize its own installation and display a message like the following: when you click ok, mozilla installs the new package.
compareTo - Archive of obsolete content
method of installversion object syntax compareto ( installversion version); compareto ( string version); compareto ( int major, int minor, int release, int build); parameters the compareto method has the following parameters: maj the major version number.
...in particular, this method returns one of the following values: -4 this version object has a smaller (earlier) major number than version.
... the following constants are defined and available for checking the value returned by compareto: installversion.major_diff installversion.minor_diff installversion.rel_diff installversion.bld_diff installversion.equal installversion.major_diff_minus installversion.minor_diff_minus installversion.rel_diff_minus installversion.bld_diff_minus example...
Menus - Archive of obsolete content
the following is a brief summary of these elements, examples of each will be provided later.
... menu tag overview the following shows a simple menu example, containing a menubar with a single menu labeled 'file'.
...the following shows a simple help menu.
Actions - Archive of obsolete content
for result b, the builder would have generated the following content: <button id="http://www.xulplanet.com/rdf/b" label="http://www.xulplanet.com/rdf/b"/> naturally, you wouldn't use an id attribute inside a template action since the id would be replaced anyway.
...after all the results have been examined, the dom tree will look like the following: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/a"> <template> <query> <content uri="?start"/> <triple subject="?start" predicate="http://www.xulplanet.com/rdf/relateditem" object="?relateditem"/> </query> <action> <button uri="?relateditem" label="?relateditem"/> </action> </t...
...for example, if the example were modified to the following: <action> <toolbar> <button uri="?relateditem" label="?relateditem"/> </toolbar> </action> here, only the button would be repeated for each result; the toolbar will only be generated once.
Simple Example - Archive of obsolete content
this will result in the following: <member container="http://www.xulplanet.com/rdf/myphotos" child="?photo"/> as with processing a triple, the builder will now try to find as many values for the ?photo variable as possible and create potential results using them.
...in the end, the network will contain the following data: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/palace.jpg, ?title = 'palace from above') (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg, ?title = 'canal') (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg, ?t...
...the action body might look like the following, which displays the image using its url and title in a label.
Template Logging - Archive of obsolete content
each result is logged in a form much like the following: in template with id root using ref http://www.some-fictitious-zoo.com/birds new active result for query 2 matching rule 1: http://www.some-fictitious-zoo.com/birds/emperorpenguin in the example above, a new result has been added.
...to summarize, the following forms of message may be logged: new active result for query 1 matching rule 2 a new data result has been added.
...the following lists the errors that can occur and an explanation of what the problem is.
XML Templates - Archive of obsolete content
for this and the following examples, we are going to use the following xml document containing a list of people: <people> <person name="napoleon bonaparte" gender="male"/> <person name="cleopatra" gender="female"/> <person name="julius caesar" gender="male"/> <person name="ferdinand magellan" gender="male"/> <person name="laura secord" gender="female"/> </people> xml query syntax the query syntax is fairly sim...
...for each node generated by the xpath expression used in the query, the attribute on the generated xml node is taken and substituted for the question mark and following string.
...for instance, the following query returns only those results for female people.
Box Objects - Archive of obsolete content
the following example shows this.
...to retrive or modify the hidden or collapsed state use the corresponding properties as in the following example.
...the following example demonstrates this.
Creating a Window - Archive of obsolete content
the simplest xul file has the following structure: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <!-- other elements go here --> </window> this window will not do anything since it doesn't contain any ui elements.
...(usually the browser window.) for example, we could open the find files dialog with either of the following: mozilla -chrome chrome://findfile/content/findfile.xul mozilla -chrome resource:/chrome/findfile/content/findfile.xul if you run this command from a command-line (assuming you have one on your platform), the find files dialog will open by default instead of the mozilla browser window.
... to see the effect though, the following will open the bookmarks window: mozilla -chrome chrome://communicator/content/bookmarks/bookmarksmanager.xul if you are using firefox, try below.
Input Controls - Archive of obsolete content
the following are some of them: id a unique identifier so that you can identify the textbox.
... the following example shows some textboxes: example 1 : source view <label control="some-text" value="enter some text"/> <textbox id="some-text"/> <label control="some-password" value="enter a password"/> <textbox id="some-password" type="password" maxlength="8"/> multiline textbox the textbox examples above will create text inputs that can only be used for entering one line of text.
...the following example demonstrates this.
Manifest Files - Archive of obsolete content
doesn't work with utf-8 with bom.) add the following line to it: content tests file:///c:/testfiles/ the file path in that line should point to the directory created above.
...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.
...the following describes how to set up a package for earlier versions.
Modifying the Default Skin - Archive of obsolete content
for example, by adding the following to the end of the file, you can change all menubar elements to have a red background.
...for example, to add a red border around the menu commands in the bookmarks manager window, add the following to bookmarksmanager.css in the classic.jar or your favorite skin archive.
... you can assign images to a button, checkbox and other elements by using the list-style-image property as in the following: checkbox { list-style-image: url("chrome://findfile/skin/images/check-off.jpg"); } checkbox[checked="true"] { list-style-image: url("chrome://findfile/skin/images/check-on.jpg"); } this code changes the image associated with a checkbox.
More Event Handlers - Archive of obsolete content
to manually stop event propagation, call the event object's stoppropagation method, as in the following example.
...the following sections list some of the events that may be used.
...you can do this by subtracting the element's position from the event position, as in the following code.
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
tree elements trees can be created with the tree element, which is described in the following sections.
...the following tags are used: treeitem this contains a single parent row and all its descendants.
...the following code should be added in place of the iframe.
XUL Structure - Archive of obsolete content
remote xul was disabled in firefox 8, so the following is of historic interest only.
...or, just manually edit your user.js preferences file and add the following line: pref("nglayout.debug.disable_xul_cache", true); there are usually three different parts to a chrome package, although they are all optional.
...if you extract the files in browser.jar, you will find that it contains a directory structure much like the following: content browser browser.xul browser.js -- other browser xul and js files goes here -- bookmarks -- bookmarks files go here -- preferences -- preferences files go here -- .
XUL Event Propagation - Archive of obsolete content
the following image describes in a very basic way how the various actors in the event model interact with one another.
... the widget hierarchy consider the following xul file: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="events" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" oncommand="alert('window handler')"> <vbox> <vbox style="background-color: lightgrey;" oncommand="alert('box handler')"> <menu class="menu" label="file" oncom...
...for example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a javascript function determines which menuitem was selected and responds appropriately: <script> function docmd(el) { v = el.getattribute("value"); if (v == "new") alert("new clicked"); else if (v == "open") alert("open clicked"); else alert("close clicked"); } </script> ...
prefwindow - Archive of obsolete content
prefer the classical window.opendialog() with the following window features: "chrome,titlebar,toolbar,centerscreen,dialog=yes".
...the following values can be used in the list: accept: the ok button, which will accept the changes when pressed.
...the following values can be used in the list: accept: the ok button, which will accept the changes when pressed.
toolbarbutton - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } dir type: one of the values below the direction in which the child elements of the element are placed.
...the following values can be used as the dialog type: accept the ok button, which will accept the changes when pressed.
...the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded.
treecol - Archive of obsolete content
label="name" flex="1" /> </treecols> <treechildren> <treeitem> <treerow> <treecell value="true"/> <treecell label="alice"/> </treerow> </treeitem> <treeitem> <treerow> <treecell value="false"/> <treecell label="bob"/> </treerow> </treeitem> </treechildren> </tree> to make the checkbox visible on some platforms, the following styles need to be added to the stylesheet (see treecol.type).
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } cycler type: boolean if true, then the column is a cycler column.
...nodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following class may be used to style the element.
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
make sure you change the application name (following ac_add_app_options to that of your app.
...and what's more, you can skip the following section, partially compensating you for all that extra work you put in just now.
...to build your application, make sure you have the right .mozconfig file in your top-level source directory, then run the following from that directory: make -f client.mk build so if you are building xulrunner as well as your app, this will cause both to be built in sequence.
Gecko Compatibility Handbook - Archive of obsolete content
review your results the following scenarios all relate to browser detection.
...the xhtml backward compatibility guidelines state that empty elements can be coded by following the tag name with a space followed with as slash as in <tag />.
...to understand why, consider the following: html without optional ending tags equivalent html with optional ending tags <select> <option>optionvalue </select> <select> <option>optionvalue</option> </select> now consider if we used the xml empty tag notation: the <option />.
NPN_GetURL - Archive of obsolete content
syntax #include <npapi.h> nperror npn_geturl(npp instance, const char* url, const char* target); parameters the function has the following parameters: instance pointer to the current plug-in instance.
... target name of the target window or frame, or one of the following special target names.
...the following recommendations about target choice apply to other methods that handle urls as well.
SAX - Archive of obsolete content
to create one, use the following code: var xmlreader = components.classes["@mozilla.org/saxparser/xmlreader;1"] .createinstance(components.interfaces.nsisaxxmlreader); after you created the sax parser, you need to set the handlers for the events you're interested in and fire off the parsing process.
...the following handlers are available: interface purpose nsisaxcontenthandler receive notification of the logical content of a document (e.g.
...below is an example of parsing from a string: xmlreader.parsefromstring("<f:a xmlns:f='g' d='1'><bbq/></f:a>", "text/xml"); this call results in the following output (assuming the content handler from the example above is used): startdocument startelement: namespace='g', localname='a', qname='f:a', attributes={d='1'} startelement: namespace='', localname='bbq', qname='bbq', attributes={} endelement: namespace='', localname='bbq', qname='bbq' endelement: namespace='g', localname='a', qname='f:a' enddocument ...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
due to a limitation of the present implementation of nspr io on nt, programs must follow the following guideline: if a thread calls an nspr io function on a file descriptor and the io function fails with <tt>pr_io_timeout_error</tt> or <tt>pr_pending_interrupt_error</tt>, the file descriptor must be closed before the thread exits.
... limitations this seemingly harsh way to force the completion of outstanding overlapped io request has the following limitations: it is difficult for threads to shared a file descriptor.
...following the rule of thumb, both threads would close the socket.
Using SSH to connect to CVS - Archive of obsolete content
the following command should generate a suitable key pair: ssh-keygen -t dsa this will take a moment, followed by a prompt for a passphrase.
... download, build, and install corkscrew by following the instructions in the install file in the corkscrew source distribution.
... make sure you have a ~/.ssh/config file that has at least the following directives preferredauthentications hostbased,publickey,password host cvs.mozilla.org proxycommand corkscrew <i>proxyserver.foo.com</i> <i>port</i> %h %p replaceproxyserver.foo.com with the hostname of your proxy server, andport with the numeric tcp port on which the http tunnel is running.
Processing XML with E4X - Archive of obsolete content
variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotation marks that would normally go around an attribute value, as the following example illustrates: var a = 2; var b = <foo bar={a}>"hi"</foo>; upon execution the variable is evaluated and quotes are automatically added where appropriate.
... it is possible to create an xmllist using xml literal syntax without needing to create a well-formed xml document, using the following syntax: var xmllist = <> <lang>javascript</lang> <lang>python</lang> </>; the += operator can be used to append new elements to an xmllist within a document: languages.lang += <lang>ruby</lang>; note that unlike node lists returned by regular dom methods, xmllists are static and are not automatically updated to reflect changes in the dom.
...while the following is already achievable by iterating an e4x object with for each...in, it demonstrates how a more customized one could be created.
Debug.setNonUserCodeExceptions - Archive of obsolete content
example the following code shows how to set this property.
... } })(); requirements supported in the following document modes: internet explorer 10 standards and internet explorer 11 standards.
... not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards.
New in JavaScript 1.3 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 4.0 to 4.5.
... non-ecma-262 features of javascript 1.3 the following is a comparison between the june 1998 version of ecma-262 and javascript 1.3.
... the following features were not part of the standard at that time, but implemented in javascript 1.3.
JSException - Archive of obsolete content
constructor summary the netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information.
... method summary the netscape.javascript.jsexception class has the following methods: getwrappedexception instance method getwrappedexception.
... declaration public int getwrappedexceptiontype() description getwrappedexceptiontype() returns an int that matches one of the following static ints declared by the jsexception class: exception_type_empty exception_type_void exception_type_object exception_type_function exception_type_string exception_type_number exception_type_boolean ...
Building Mozilla XForms - Archive of obsolete content
the following table gives you an overview of which version you want to build: firefox version gecko/toolkit version source code notes status firefox 2.0 gecko 1.8.1 cvs, branch mozilla_1_8_branch not developed any more last release: 0.8.5ff2 firefox 3.0 gecko 1.9.0 cvs, branch head not developed any more last release: 0.8.5ff3 firefox 3.5 gecko 1.9.1 xforms/schema-validation code does not build wi...
...for xforms, you will need to add the following line: ac_add_options --enable-extensions="default,xforms" # if you're using a mozilla source before 2010-11-06 (e.g.
...the following scheme usually works (replace {geckoversion} with the used gecko/toolkit version): <em:minversion>{geckoversion}.0</em:minversion> <em:maxversion>{geckoversion}.*</em:maxversion> for example, for the firefox 3.5 version of the extension, it might look like that: <em:minversion>1.9.1.0</em:minversion> <em:maxversion>1.9.1.*</em:maxversion> then zip the files again (or use an editor like vim that...
Troubleshooting XForms Forms - Archive of obsolete content
any instance, no controls get bound if no controls show with either inline instance or an <xf:instance src="...">, check the following: as with inline instance, make sure the instance of the form control ref binding expression matches the namespace of the data.
...the xss sub-tab has the following options: turn cross-site post requests into data-less get requests anti-xss protection exceptions you can temporarily fix the problem by unchecking the turn cross-site post requests into data-less get requests check box.
...if you are developing on your local machine using apache tomcat for example then add the following regular expression on a new line: ^http://localhost:8080/.* use the xforms buddy to view instance data the xforms buddy extension allows you to dynamically view model instance data while the xforms is running in the firefox browser.
Build the brick field - Game development
add the following lines to your code below the variables which you have previously declared in your program.
...add the following just below your variables: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } the code above will loop through the rows and columns and create the new bricks.
...add the following just above the drawball() call: drawbricks(); compare your code at this point, the game has got a little more interesting again : exercise: try changing the number of bricks in a row or a column, or their positions.
Collision detection - Game development
for the center of the ball to be inside the brick, all four of the following statements need to be true: the x position of the ball is greater than the x position of the brick.
...update the following part of the code as indicated by the highlighted line: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0, status: 1 }; } } next we'll check the value of each brick's status property in the drawbricks() function before drawing it — if status is 1, then draw it, but if it's 0, then it was...
...add the following line to the draw() function, just below the drawpaddle() call: collisiondetection(); compare your code the collision detection of the ball is now checked on every frame, with every brick.
Finishing up - Game development
let's first add a variable to store the number of lives in the same place where we declared our other variables: var lives = 3; drawing the life counter looks almost the same as drawing the score counter — add the following function to your code, below the drawscore() function: function drawlives() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("lives: "+lives, canvas.width-65, 20); } instead of ending the game immediately, we will decrease the number of lives until they are no longer available.
...so, in the draw() function replace the following three lines: alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game with this, we can add slightly more complex logic to it as given below: lives--; if(!lives) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } else { x = canvas.width/2; y = canvas.height-30; dx = 2; dy = -2; paddlex = (canvas.width-paddlewidth)/2; } now, when the ball hits the bottom edge of the screen, we're subtracting one life from the lives variable.
...replace the following line: var interval = setinterval(draw, 10); with simply: draw(); and remove each instance of: clearinterval(interval); // needed for chrome to end game then, at the very bottom of the draw() function (just before the closing curly brace), add in the following line, which causes the draw() function to call itself over and over again: requestanimationframe(draw); the draw() function is now...
Build the brick field - Game development
defining new variables first, let's define the needed variables — add the following below your previous variable definitions: var bricks; var newbrick; var brickinfo; the bricks variable will be used to create a group, newbrick will be a new object added to the group on every iteration of the loop, and brickinfo will store all the data we need.
... rendering the brick image next, let's load the image of the brick — add the following load.image() call just below the others: function preload() { // ...
... now, let's start creating the bricks themselves — add an empty group first to contain the bricks, by adding the following line at the bottom of the initbricks() function: bricks = game.add.group(); we can loop through the rows and columns to create new brick on each iteration — add the following nested loop below the previous line of code: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { // create new brick and add it to the group } } this way we will create the e...
Extra lives - Game development
new variables add the following new variables below the existing ones in your code: var lives = 3; var livestext; var lifelosttext; these respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives.
...add the following lines below the existing scoretext definition inside your create() function: livestext = game.add.text(game.world.width-5, 5, 'lives: '+lives, { font: '18px arial', fill: '#0095dd' }); livestext.anchor.set(1,0); lifelosttext = game.add.text(game.world.width*0.5, game.world.height*0.5, 'life lost, click to continue', { font: '18px arial', fill: '#0095dd' }); lifelosttext.anchor.set(0.5); lifelosttext.visible = false; the livestext and lifelosttext objects look very similar to the scoretext one — they define a position on the screen, the actual text to display, and the font styling.
...instead of executing an anonymous function and showing the alert right away : ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); we will assign a new function called ballleavescreen; delete the previous event handler (shown above) and replace it with the following line: ball.events.onoutofbounds.add(ballleavescreen, this); we want to decrease the number of lives every time the ball leaves the canvas.
Load the assets and print them on screen - Game development
add the following line between the game initialization code (our var game...
...add the following new line just inside the preload() function, at the bottom: function preload() { // ...
... now, to show it on the screen we will use another phaser method called add.sprite(); add the following new code line inside the create() function as shown: function create() { ball = game.add.sprite(50, 50, 'ball'); } this will add the ball to the game and render it on the screen.
Gecko FAQ - Gecko Redirect 1
gecko has been known previously by the code names "raptor" and "nglayout"; the new name was chosen following a trademark infringement dispute.
... by the end of calendar year 2000, gecko is expected to support the following recommended open internet standards fully except for the areas noted below and open bugs documented in bugzilla: html 4.0 - full support except for: elements: bdo, basefont attributes: shape attribute on the a element, abbr, axis, headers, scope-row, scope-col, scope-rowgroup, scope-colgroup, charoff, datasrc, datafld, dataformat, datapagesize, summary, event, dir, align on table colu...
... gecko includes the following components: document parser (handles html and xml) layout engine with content model style system (handles css, etc.) javascript runtime (spidermonkey) image library networking library (necko) platform-specific graphics rendering and widget sets for win32, x, and mac user preferences library mozilla plug-in api (npapi) to support the navigator plug-in interface open java interface (oji...
CSS and JavaScript accessibility best practices - Learn web development
the following sections summarize the main html features to consider.
...the following image shows the highlight in both firefox (a dotted outline) and chrome (a blue outline): you can be creative with link styles, as long as you keep giving users feedback when they interact with the links.
...the code features two functions that show and hide the zoomed-in image; these are run by the following lines that set them as event handlers: imgthumb.onmouseover = showimg; imgthumb.onmouseout = hideimg; 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.
WAI-ARIA basics - Learn web development
previous overview: accessibility next following on from the previous article, sometimes making complex ui controls that involve unsemantic html and dynamic javascript-updated content can be difficult.
...let's look at an example — our website-no-roles example (see it live) has the following structure: <header> <h1>...</h1> <nav> <ul>...</ul> <form> <!-- search form --> </form> </nav> </header> <main> <article>...</article> <aside>...</aside> </main> <footer>...</footer> if you try testing the example with a screenreader in a modern browser, you'll already get some useful information.
... for example, voiceover gives you the following: on the <header> element — "banner, 2 items" (it contains a heading and the <nav>).
The box model - Learn web development
these characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page: if a box is defined as a block, it will behave in the following ways: the box will break onto a new line.
... if we assume that the box has the following css defining width, height, margin, border, and padding: .box { width: 350px; height: 150px; margin: 10px; padding: 25px; border: 5px solid black; } the space taken up by our box using the standard box model will actually be 410px (350 + 25 + 25 + 5 + 5), and the height 210px (150 + 25 + 25 + 5 + 5), as the padding and border are added to the width used for the content box.
... to set the properties of each side individually, you can use: border-top border-right border-bottom border-left to set the width, style, or color of all sides, use the following: border-width border-style border-color to set the width, style, or color of a single side, you can use one of the most granular longhand properties: border-top-width border-top-style border-top-color border-right-width border-right-style border-right-color border-bottom-width border-bottom-style border-bottom-color border-left-width border-left-style border-left-color in t...
How CSS works - Learn web development
the following diagram also offers a simple view of the process.
... take the following html code: <p> let's use: <span>cascading</span> <span>style</span> <span>sheets</span> </p> in the dom, the node corresponding to our <p> element is a parent.
...again, the html is as follows: <p> let's use: <span>cascading</span> <span>style</span> <span>sheets</span> </p> let's suppose we apply the following css to it: span { border: 1px solid black; background-color: lime; } the browser will parse the html and create a dom from it, then parse the css.
Styling links - Learn web development
default styles the following example illustrates what a link will behave like by default (the css is simply enlarging and centering the text to make it stand out more.) <p><a href="#">a simple link</a></p> p { font-size: 2rem; text-align: center; } note: all the links in the examples in this page are fake links — a # (hash, or pound sign) is put in place of the real url.
... the default styles can be turned off/changed using the following css properties: color for the text color.
...0%; } li { display: inline; } a { outline: none; text-decoration: none; display: inline-block; width: 19.5%; margin-right: 0.625%; text-align: center; line-height: 3; color: black; } li:last-child a { margin-right: 0; } a:link, a:visited, a:focus { background: yellow; } a:hover { background: orange; } a:active { background: red; color: white; } this gives us the following result: let's explain what's going on here, focusing on the most interesting parts: our second rule removes the default padding from the <ul> element, and sets its width to span 100% of the outer container (the <body>, in this case).
Styling web forms - Learn web development
these include the following elements: <form> <fieldset> and <legend> single-line text <input>s (e.g.
...to make your forms' appearance consistent with the rest of your content, you can add the following rules to your stylesheet: button, input, select, textarea { font-family: inherit; font-size: 100%; } the inherit property value causes the property value to match the computed value of the property of its parent element; inheriting the value of the parent.
... take the following example: to position the legend in this manner, we used the following css (other declarations removed for brevity): fieldset { position: relative; } legend { position: absolute; bottom: 0; right: 0; } the <fieldset> needs to be positioned too, so that the <legend> is positioned relative to it (otherwise the <legend> would be positioned relative to the <body>.) the <legend> element ...
HTML text fundamentals - Learn web development
consider the following: <span style="font-size: 32px; margin: 21px 0; display: block;">is this a top level heading?</span> this is a <span> element.
...lists are everywhere in life—from your shopping list to the list of directions you subconsciously follow to get to your house every day, to the lists of instructions you are following in these tutorials!
...for example, the following two sentences have different meanings.
HTML table advanced features and accessibility - Learn web development
inside this element, add the following lines of css code: tbody { font-size: 95%; font-style: italic; } tfoot { font-weight: bold; } save and refresh, and have a look at the result.
... your finished table should look something like the following: hidden example <!doctype html> <html> <head> <meta charset="utf-8"> <title>my spending record</title> <style> html { font-family: sans-serif; } table { border-collapse: collapse; border: 4px solid rgb(200,200,200); letter-spacing: 1px; font-size: 0.8rem; } td, th { border: 2p...
... the following markup shows a simple nested table: <table id="table1"> <tr> <th>title1</th> <th>title2</th> <th>title3</th> </tr> <tr> <td id="nested"> <table id="table2"> <tr> <td>cell1</td> <td>cell2</td> <td>cell3</td> </tr> </table> </td> <td>cell2</td> <td>cell3</td> </tr> <tr> <td>cell4</td> <td>cell5<...
Function return values - Learn web development
so when you execute the following: ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); if the three random() calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this: ctx.arc(500, 200, 35, 0, 2 * math.pi); the function calls on the line are run first, and their return values substituted for the function calls, before the line itself is then executed.
...below the two existing lines of javascript, add the following function definitions: function squared(num) { return num * num; } function cubed(num) { return num * num * num; } function factorial(num) { if (num < 0) return undefined; if (num == 0) return 1; let x = num - 1; while (x > 1) { num *= x; x--; } return num; } the squared() and cubed() functions are fairly obvious — they return the square or cube of the number that w...
...enter the following event handler below the existing functions: input.onchange = function() { const num = input.value; if (isnan(num)) { para.textcontent = 'you need to enter a number!'; } else { para.textcontent = num + ' squared is ' + squared(num) + '.
Silly story generator - Learn web development
project brief you have been provided with some raw html/css and a few text strings and javascript functions; you need to write the necessary javascript to turn this into a working program, which does the following: generates a silly story when the "generate random story" button is pressed.
... will generate another random silly story if you press the button again (and again...) the following screenshot shows an example of what the finished program should output: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do.
...the following for example turns the background of the <html> element red — so the entire browser window should go red if the javascript is applied properly: document.queryselector('html').style.backgroundcolor = 'red'; math.round() is a built-in javascript method that simply rounds the result of a calculation to the nearest whole number.
What is JavaScript? - Learn web development
next, go to your text editor and add the following in your head — just before your closing </head> tag: <script> // javascript goes here </script> now we'll add some javascript inside our <script> element to make the page do something more interesting — add the following code just below the "// javascript goes here" line: document.addeventlistener("domcontentloaded", function() { function createparagraph() { let para = docume...
... replace your current <script> element with the following: <script src="script.js" defer></script> inside script.js, add the following script: function createparagraph() { let para = document.createelement('p'); para.textcontent = 'you clicked the button!'; document.body.appendchild(para); } const buttons = document.queryselectorall('button'); for(let i = 0; i < buttons.length ; i++) { buttons[i].addeventlistener('click', createparagrap...
... for example, if you have the following script elements: <script async src="js/vendor/jquery.js"></script> <script async src="js/script2.js"></script> <script async src="js/script3.js"></script> you can't rely on the order the scripts will load in.
Website security - Learn web development
for example, the following code is intended to list all users with a particular name (username) that has been supplied from an html form: statement = "select * from users where name = '" + username + "';" if the user specifies a real name, the statement will work as intended.
... however, a malicious user could completely change the behavior of this sql statement to the new statement in the following example, by simply specifying the text in bold for the username.
... in the following statement, we escape the ' character.
Server-side website programming - Learn web development
we recommend that you first read the following topics: what is a web server what software do i need to build a website?
... modules this topic contains the following modules.
... you should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks.
Getting started with React - Learn web development
also, see the following for more information: "what is npm" on nodejs.org "introducing npx" on the npm blog the create-react-app documentation initializing your app create-react-app takes one argument: the name you'd like to give your app.
...make sure you cd to the place you'd like your app to live on your hard drive, then run the following in your terminal: npx create-react-app moz-todo-react this creates a moz-todo-react directory, and does several things inside it: installs some npm packages essential to the functionality of the app.
... some elements in the expression have attributes, which are written just like in html, following a pattern of attribute="value".
Getting started with Vue - Learn web development
installation to use vue in an existing site, you can drop one of the following <script> elements onto a page.
... to install the cli, run the following command in your terminal: npm install --global @vue/cli or if you'd prefer to use yarn: yarn global add @vue/cli once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>.
...your terminal should output something like the following: info starting development server...
Introduction to cross browser testing - Learn web development
browsers are much better at following standards these days, but differences and bugs still creep through sometimes.
... the workflow for testing and bug fixes on a project can be broken down into roughly the following four phases (this is only very rough — different people may do things quite differently to this): initial planning > development > testing/discovery > fixes/iteration steps 2–4 will tend to be repeated as many times as necessary to get all of the implementation done.
... testing on prerelease browsers it is often a good idea to test on prerelease versions of browsers; see the following links: firefox developer edition edge insider preview safari technology preview chrome canary opera developer this is especially prevalent if you are using very new technologies in your site, and you want to test against the latest implementations, or if you are coming across a bug in the latest release version of a browser, and you want to see if the browser's developers have fixed the ...
Command line crash course - Learn web development
try running the following, and you’ll see that in fact there are three redirects happening before we reach the final page: curl /docs/web/api/fetch -l -i | grep location your output should look something like this (curl will first output some download counters and suchlike): location: /docs/web/api/fetch location: /docs/web/api/globalfetch/globalfetch.fetch() location: /docs/web/api/globalfetch/fetch location: /docs/...
... once you've installed node, open up the terminal and run the following command to install prettier: npm install --global prettier once the command has finished running, the prettier tool is now available in your terminal, at any location in your file system.
... now save the following code in a new file called index.js, inside your test directory: const myobj = { a:1,b:{c:2}} function printme(obj){console.log(obj.b.c)} printme(myobj) we can run prettier against a codebase to just check if our code wants adjusting.
Accessibility/LiveRegionDevGuide
the following is a list of potential filtering techniques: the "event-from-input" object attribute can be used to filter events that were triggered by user action.
...the following are guidelines on how to implement each container-live this property determines the interruption policy or politeness level for the event and can have values of "off", "polite", "assertive" and "rude".
...the following describes actions that should be taken for an event with the given politeness level: off: no action should be taken.
Application cache implementation overview
the following loading process decisions are then the same as for the top level load with one addition: when the entry is neither found in the cache nor matches any namespace in that cache we fail the resource load with document_not_found.
...this new cache version is now pending to be activated after all following long and complicated download process passes.
...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.
Chrome registration
any following character in the same line is ignored.
... style style overlays (custom css which will be applied to a chrome page) are registered with the following syntax: style chrome://uri-to-style chrome://stylesheet-uri [flags] note: only stylesheets at chrome uris can be applied in this way.
.../pippki/ content global-platform jar:toolkit.jar!/content/global-platform/ platform skin global classic/1.0 jar:classic.jar!/skin/classic/global/ override chrome://global/content/neterror.xhtml jar:embedder.jar!/global/content/neterror.xhtml content inspector jar:inspector.jar!/content/inspector/ instructions supported in bootstrapped add-ons the following instructions are supported in bootstrapped extensions: manifest content locale skin override debugging a chrome manifest file the chrome list extension shows all registered chrome.
Debugging Table Reflow
debug_table_strategy editor's note: the following examples are not shown correctly due to the wiki's technical constraint.
... the table layout strategy can be visualized by defining in the makefiles the constant debug_table_strategy.if one takes for instance the following table code: <table border width="300"> <colgroup> <col> <col width="50%"> <col width="1*"> <col> </colgroup> <tr> <td style="width:80px">cell 1</td> <td>cell 2</td> <td>cell 3</td> <td>cell 4</td> </tr> </table> rendering: <colgroup><col><col width="50%"><col width="1*"><col></colgroup>cell 1cell 2cell 3cell 4 it will produce the following log at the entrance of assignnonpctcolwidths: assignnonpctcolwidths en max=4500 count=0 ***start table dump*** mcolwidths=-1 -1 -1 -1 col frame cache -> 0=00b93138 1=00b931f0 2=024dd728 3=024dd780 **start col dump** colindex=0 isanonymous=0 constraint=0 widths=-1 -1 -1 -1 -1 -1 -1 -1 -1 ...
...the following constraint types are known: enoconstraint = 0, epixelconstraint = 1, // pixel width epercentconstraint = 2, // percent width eproportionconstraint = 3, // 1*, 2*, etc.
Debugging on Windows
here are some entries that will make your life easier: ;; mozilla (1.7beta and later) nsautostring=<mdata,su> nsstring=<mdata,su> nscstring=<mdata,s> nscautostring=<mdata,s> nsrect=x=<x,d> y=<y,d> width=<width,d>; height=<height,d> nsstaticatomwrapper=<mstaticatom->mstring,s> nsiatom=<mstring,su> ; the following are not necessary in vc8 nscomptr<*>=<mrawptr,x> nsrefptr=<mrawptr,x> nsautoptr=<mrawptr,x> after you have made the changes and saved the file, you will need to restart visual c++ for the changes to take effect.
... for xpcom strings (the "external" string api) you can use the following values: ;; mozilla (1.9) ; internal strings nsastring_internal=<mdata,su>, length=<mlength,u> nsacstring_internal=<mdata,s>, length=<mlength,u> ; xpcom strings nsastring=<nsstringcontainer.v,su>, length=<nsstringcontainer.d1,u> nsacstring=<nscstringcontainer.v,s>, length=<nscstringcontainer.d1,u> nsstringcontainer=<v,su>, length=<d1,u> nscstringcontainer=<v,s>, length=<d1,u> there is a more extensive version of this file in progress in autoexpforvc8.
... here are some wildcards you can use (tested with vc 8): nscomptr.*\:\:.*=nostepinto (nsg|g)etter_*addrefs.*=nostepinto ns_convertutf.* ; might be too broad: (ns|promise)[^\:]*[ss]tring.* ...add common functions to this list should probably make a .reg file for easy importing obtaining stdout and other file handles running the following command in the command window in visual studio returns the value of stdout, which can be used with various debugging methods (such as nsgenericelement::list) that take a file* param: debug.evaluatestatement {,,msvcr80d}(&__iob_func()[1]) (alternatively you can evaluate {,,msvcr80d}(&__iob_func()[1]) in the quickwatch window) similarly, you can open a file on the disk using fopen: >debug.eval...
Simple Thunderbird build
so firstly complete the instructions for your os and then continue following these build instructions.
... build configuration to build thunderbird, you need to add a file named mozconfig to the root directory of the mozilla-central checkout that contains the following line: ac_add_options --enable-application=comm/mail you can create a file with this line by doing this in the source/ directory: echo 'ac_add_options --enable-application=comm/mail' > mozconfig if you omit this line, the build system will build firefox instead.
... add the following line to your mozconfig file: ac_add_options --enable-calendar to add that line you can do this in the source/ directory: echo 'ac_add_options --enable-calendar' >> mozconfig building before you start, make sure that the version you checked out is not busted.
Eclipse CDT Manual Setup
to avoid confusion in this and the following sections, note that "workspace preferences" and "project properties" are different things (we'll get to the details below).
... whenever you create a new workspace for a mozilla source tree, you should be sure to turn off the following two settings in the workspace preferences (window > preferences, or eclipse > preferences) before creating a project in that workspace: in "general > workspace", disable "build automatically" in "c/c++ > indexer", disable "automatically update the index" turning off automatic indexing prevents the cpu intensive indexer from running at various stages during the steps below before we're ready.
...select "resource > resource filters" on the left of the window that opens, then use the add button to add the following filters: add an "exclude all" filter for folders with a project relative path matching ".hg".
mach
mach's logic for determining which mozconfig to use is effectively the following: if a .mozconfig file (some say it is the file mozconfig without the dot) exists in the current directory, use that.
... for example: $ cd devtools/client $ mach build webconsole # rebuild only the files in the devtools/client/webconsole directory $ mach mochitest webconsole/test # run mochitests in devtools/client/webconsole/test enable tab completion to enable tab completion in bash, run the following command.
...if you don't use mach, you have to find another solution for the following problems: discovering what commands or make targets are available (mach exposes everything through mach help while inside "mozilla-central" , else you'll just get a cryptic error message) making more sense out of command output (mach offers terminal colorization and structured logging) getting productive tools in the hands of others (mach "advertises" tools to people through mach help (unles...
Message manager overview
it's a chromemessagebroadcaster object, which implements the following interfaces: nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster you can access the global message manager like this: // chrome script let globalmm = cc["@mozilla.org/globalmessagemanager;1"] .getservice(ci.nsimessagelistenermanager); window message manager the window message manager is associated with a specific browser window, and operates on every <browser> (that is...
... it's a chromemessagebroadcaster object, which implements the following interfaces: nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster the window message manager can be accessed as a property of the browser window: // chrome script let windowmm = window.messagemanager; browser message manager the browser message manager is specific to a single xul <browser> element (which essentially corresponds to a single tab): loadframescript() loads the given script only into its <browser> sendasyncmessage() sends the message only to that <browser>.
... it's a chromemessagesender object, which implements the following interfaces: nsiprocesschecker nsiframescriptloader nsimessagelistenermanager nsimessagesender the browser message manager can be accessed as a property of the xul <browser> element: // chrome script let browsermm = gbrowser.selectedbrowser.messagemanager; process message managers process message managers correspond to process boundaries, and enable code running in different processes to communicate.
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
we did this with the following functions: function canmovebwd() { var request = browser.getcangoback(); request.onsuccess = function() { if (request.result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled = true; console.log("it's not possible to navigate the history backward."); } } } function canmovefwd() { var requ...
...this is implemented in our sample app with the following functions: browser.addeventlistener('mozbrowserloadstart',function() { stopreload.textcontent = 'x'; }); browser.addeventlistener('mozbrowserloadend',function(e) { canmovebwd(); canmovefwd(); stopreload.textcontent = 'r'; console.log(e.detail.backgroundcolor); controls.style.background = e.detail.backgroundcolor; }); when the mozbrowserloadstart event fires, the latest page request...
...we do this with the following function, which runs the htmliframeelement.stop() method to stop the page loading if the button is displaying a cross, and the htmliframeelement.reload() method to reload the page otherwise.
Gecko Keypress Event
when the keypress event includes modifier keys, sometimes the charcode value is replaced with an ascii character according to the following rules.
...there are also some differences between the platforms, as described in the following sections.
... (bug 359638 partially addressed this issue by trying both characters on the key, but bug 303192 would provide a complete solution.) solution the following rules apply: key handlers should be provided with information about all the possible meanings of the event.
How to Report a Hung Firefox
what information to include in a bug report as usual, following bug writing guidelines will make your report much more likely to lead to a fix in firefox.
... the crash report link for a hang, obtained by following the steps below.
... another way to trigger a crash in a hung tab is to run the following script in the browser console (opened after selecting the hung tab): let wm = cc["@mozilla.org/appshell/window-mediator;1"].
Internationalized Domain Names (IDN) Support in Mozilla Browsers
as an example, an output string to be sent to a dns server for a japanese domain name, "http://ジェーピーニック.jp", will look like the following in ace form: http://xn--hckqz9bzb1cyrb.jp domain name registration after the technical standards were established by ietf, the last remaining issue was for domain name registrars to agree on an international guideline on the use of idn characters.
...for example, most sample links on the following test pages can be used without any further setting: http://www.nunames.nu/eu-lang-test.htm (domain names with latin 1 accented characters) http://www.nunames.nu/lldemo/default.htm (domain names in other languages) on july 10, 2003 and thereafter, you can access a large number of japanese domain name sites under the .jp top domain with no further setting on netscape 7.1/mozilla 1.4: http:...
...if you find idn test sites under the .com and .net top domains, and if you cannot successfully access these sites, you can use the following workaround until the conversion to punycode is completed for these top domains: using netscape 7.1 or mozilla 1.4: type about:config into the location/url bar.
PopupNotifications.jsm
a notification action object must contain the following properties: label a text label describing the action.
...any combination of the following properties may be provided: persistence an integer value indicating the number of page loads for which the notification will persist; once this many page loads have occurred, the notification may dismiss automatically.
...the first parameter to the callback is a string identifying the state change, and may be one of the following: "dismissed" the notification has been dismissed by the user (for example, by clicking away or by switching tabs).
Localizing with Koala
the easy way involves opening the console and issuing the following commands: c:\users\stas> cd c:\mozilla\l10n\application\firefox c:\mozilla\l10n\application\firefox> rmdir 3.6 c:\mozilla\l10n\application\firefox> hg clone http://hg.mozilla.org/releases/mozilla-1.9.2 3.6 requesting all changes adding changesets adding manifests adding file changes added 33099 changesets with 158636 changes to 50664 files (+9 heads) updating working directory 40357 files updated...
...just open the console and issue the following commands: c:\users\stas> cd c:\mozilla\l10n\locale\x-testing c:\mozilla\l10n\locale\x-testing> rmdir 3.6 c:\mozilla\l10n\locale\x-testing> hg clone http://hg.mozilla.org/releases/l10n-mozilla-1.9.2/x-testing 3.6 new localizations: if you have the bitbucket repository already set up by l10n-drivers, the steps are the same as above.
...committing your work hopefully by now, you have translated 3 strings in the following 2 files: searchbar.dtd: cmd_enginemanager.label searchendcap.label search.properties: cmd_addfoundengine it's time to put these files under mercurial's version control system.
SVN for Localizers
enter the following command in your command-line tool: svn checkout https://svn.mozilla.org/projects/mozilla.com/trunk/locales/[your locale code] mozilla-l10n-[your-localecode] this command creates the mozilla-l10n-[your-localecode] directory on your computer and copies into it all of the files from https://svn.mozilla.org/projects/moz...om/trunk/locales/[your locale code].
... once you're satisfied with changes, commit them to the appropriate mozilla svn repository by entering the following command: svn commit -m "minor modifications for firefox [version #] beta page for [your locale]" the svn commit command will commit your changes directly to the mozilla svn repositories.
...enter the following command from the command-line: svn update your local svn repository (i.e., working directory) will be updated with the newest files from the url you initially cloned your repository from.
Leak Gauge
getting a log file to get a log file, run the browser with the following environment variables set.
... if there are no leaks, output will look like the following.
... results of processing log leak.log : summary: leaked 0 out of 11 dom windows leaked 0 out of 44 documents leaked 0 out of 3 docshells leaked content nodes in 0 out of 0 documents if there are leaks, output will look like the following.
Profiling with the Firefox Profiler
however the following could have some potentially useful information for gecko-specific problems.
... the following information is old version of firefox for android.
...thgis requires the following command: $ xpcshell -m -i -n -e ' const ci = components.interfaces; const cc = components.classes; var profiler = cc["@mozilla.org/tools/profiler;1"].getservice(ci.nsiprofiler); profiler.startprofiler( 10000000 /* = profiler memory */, 1 /* = sample rate: 100µs with patch, 1ms without */, ["stackwalk", "js"], 2 /* = features, and number of features.
perf
the following example shows how to invoke it for this purpose.
... the output will look like the following.
... performance counter stats for 'system wide': 51.58 joules power/energy-pkg/ [100.00%] 14.80 joules power/energy-cores/ [100.00%] 9.93 joules power/energy-gpu/ [100.00%] 27.38 joules power/energy-ram/ [100.00%] 5.003049064 seconds time elapsed it's not clear from the output, but the following relationship holds.
tools/power/rapl
output the following is 10 seconds of output from a default invocation of rapl.
....02 w = 6.15 ( 2.62 + 0.43 + 3.10) + 3.86 w #05 14.63 w = 10.43 ( 4.41 + 0.81 + 5.22) + 4.19 w #06 11.16 w = 6.90 ( 1.91 + 1.68 + 3.31) + 4.26 w #07 5.40 w = 1.97 ( 0.20 + 0.10 + 1.67) + 3.44 w #08 5.17 w = 1.76 ( 0.07 + 0.08 + 1.60) + 3.41 w #09 5.17 w = 1.76 ( 0.09 + 0.08 + 1.58) + 3.42 w #10 8.13 w = 4.40 ( 1.55 + 0.11 + 2.74) + 3.73 w things to note include the following.
... once sampling is finished — either because the user interrupted it, or because the requested number of samples has been taken — the following summary data is shown: 10 samples taken over a period of 10.000 seconds distribution of 'total' values: mean = 8.85 w std dev = 3.50 w 0th percentile = 5.17 w (min) 5th percentile = 5.17 w 25th percentile = 5.17 w 50th percentile = 8.13 w 75th percentile = 11.16 w 95th percentile = 14.63 w 100th percentile = 14.63 w (max) the distribution data is omitted if t...
PR_Access
syntax #include <prio.h> prstatus pr_access( const char *name, praccesshow how); parameters the function has the following parameters: name the pathname of the file whose accessibility is to be determined.
...use one of the following values: pr_access_read_ok.
... returns one of the following values: if the requested access is permitted, pr_success.
PR_InitializeNetAddr
syntax #include <prnetdb.h> prstatus pr_initializenetaddr( prnetaddrvalue val, pruint16 port, prnetaddr *addr); parameters the function has the following parameters: val the value to be assigned to the ip address portion of the network address.
... returns the function returns one of the following values: if successful, pr_success.
... the special network address values are identified by the enum prnetaddrvalue: typedef enum prnetaddrvalue{ pr_ipaddrnull, pr_ipaddrany, pr_ipaddrloopback } prnetaddrvalue; the enum has the following enumerators: pr_ipaddrnull do not overwrite the ip address.
PR_Interrupt
syntax #include <prthread.h> prstatus pr_interrupt(prthread *thread); parameter pr_interrupt has the following parameter: thread the thread whose interrupt request you want to set.
... returns the function returns one of the following values: if the specified thread is currently blocked, pr_success.
... bugs pr_interrupt has the following limitations and known bugs: there can be a delay for a thread to be interrupted from a blocking i/o function.
PR_Open
syntax #include <prio.h> prfiledesc* pr_open( const char *name, printn flags, printn mode); parameters the function has the following parameters: name the pathname of the file to be opened.
...it is a bitwise or of the following bit flags.
...ite permission, group pr_ixgrp 0010 execute/search permission, group pr_irwxo 0007 read, write, execute/search by others pr_iroth 0004 read permission, others pr_iwoth 0002 write permission, others pr_ixoth 0001 execute/search permission, others returns the function returns one of the following values: if the file is successfully opened, a pointer to a dynamically allocated prfiledesc for the newly opened file.
PR_ReadDir
syntax #include <prio.h> prdirentry* pr_readdir( prdir *dir, prdirflags flags); parameters the function has the following parameters: dir a pointer to a prdir object that designates an open directory.
...values can include the following: pr_skip_none.
... description pr_readdir returns a pointer to a directory entry structure: struct prdirentry { const char *name; }; typedef struct prdirentry prdirentry; the structure has the following field: name name of entry, relative to directory name.
PR_Seek
syntax #include <prio.h> print32 pr_seek( prfiledesc *fd, print32 offset, prseekwhence whence); parameters the function has the following parameters: fd a pointer to a prfiledesc object.
...the value for the whence parameter can be one of the following: pr_seek_set.
... returns the function returns one of the following values: if the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file.
PR_Seek64
syntax #include <prio.h> print64 pr_seek64( prfiledesc *fd, print64 offset, prseekwhence whence); parameters the function has the following parameters: fd a pointer to a prfiledesc object.
...the value for the whence parameter can be one of the following: pr_seek_set.
... returns the function returns one of the following values: if the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file.
PR_Shutdown
syntax #include <prio.h> prstatus pr_shutdown( prfiledesc *fd, prshutdownhow how); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a connected socket.
...possible values include the following: pr_shutdown_rcv.
... returns the function returns one of the following values: upon successful completion of shutdown request, pr_success.
PR_Writev
syntax #include <prio.h> print32 pr_writev( prfiledesc *fd, priovec *iov, print32 size, printervaltime timeout); #define pr_max_iovector_size 16 parameters the function has the following parameters: fd a pointer to a prfiledesc object for a socket.
... returns one of the following values: a positive number indicates the number of bytes successfully written.
... this is the type definition for priovec: typedef struct priovec { char *iov_base; int iov_len; } priovec; the priovec structure has the following fields: iov_base a pointer to the beginning of the buffer.
NSS 3.16.3 release notes
notable changes in nss 3.16.3 the following 1024-bit ca certificates were removed cn = entrust.net secure server certification authority sha1 fingerprint: 99:a6:9b:e6:1a:fe:88:6b:4d:2b:82:00:7c:b8:54:fc:31:7e:15:39 cn = gte cybertrust global root sha1 fingerprint: 97:81:79:50:d8:1c:96:70:cc:34:d8:09:cf:79:44:31:36:7e:f4:74 ou = valicert class 1 policy validation authority sha1 fin...
...print: e5:df:74:3c:b6:01:c4:9b:98:43:dc:ab:8c:e8:6a:81:10:9f:e4:8e ou = valicert class 2 policy validation authority sha1 fingerprint: 31:7a:2a:d0:7f:2b:33:5e:f5:a1:c3:4e:4b:57:e8:b7:d8:f1:fc:a6 ou = valicert class 3 policy validation authority sha1 fingerprint: 69:bd:8c:f4:9c:d3:00:fb:59:2e:17:93:ca:55:6a:f3:ec:aa:35:fb additionally, the following ca certificate was removed as requested by the ca ou = tdc internet root ca sha1 fingerprint: 21:fc:bd:8e:7f:6c:af:05:1b:d1:b3:43:ec:a8:e7:61:47:f2:0f:8a the following ca certificates were added cn = certification authority of wosign sha1 fingerprint: b9:42:94:bf:91:ea:8f:b6:4b:e6:10:97:c7:fb:00:13:59:b6:76:cb cn = ca 沃通根证书 ...
...a 1 g3 sha1 fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67 cn = quovadis root ca 2 g3 sha1 fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36 cn = quovadis root ca 3 g3 sha1 fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d the trust bits were changed for the following ca certificates ou = class 3 public primary certification authority sha1 fingerprint: a1:db:63:93:91:6f:17:e4:18:55:09:40:04:15:c7:02:40:b0:ae:6b turned off websites and code signing trust bits (1024-bit root) ou = class 3 public primary certification authority sha1 fingerprint: 74:2c:31:92:e6:07:e4:24:eb:45:49:54:2b:e1:bb:c5:3e:61:74:e2 turned off ...
NSS 3.18.1 release notes
notable changes in nss 3.18.1 the following ca certificate had the websites and code signing trust bits restored to their original state to allow more time to develop a better transition strategy for affected sites.
... ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a the following ca certificate was removed after discussion about it in the mozilla.dev.security.policy forum.
... cn = e-guven kok elektronik sertifika hizmet saglayicisi sha1 fingerprint: dd:e1:d2:a9:01:80:2e:1d:87:5e:84:b3:80:7e:4b:b1:fd:99:41:34 the following intermediate ca certificate has been added as actively distrusted because it was misused to issue certificates for domain names the holder did not own or control.
NSS tools : crlutil
to run the certificate revocation list management tool, type the command crlutil option [arguments] where options and arguments are combinations of the options and arguments listed in the following section.
... crl generation script syntax crl generation script file has the following syntax: * line with comments should have # as a first symbol of a line * set "this update" or "next update" crl fields: update=yyyymmddhhmmssz nextupdate=yyyymmddhhmmssz field "next update" is optional.
... reasoncode non-critical code where: reasoncode: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension code: the following codes are available: unspecified (0), keycompromise (1), cacompromise (2), affiliationchanged (3), superseded (4), cessationofoperation (5), certificatehold (6), removefromcrl (8), privilegewithdrawn (9), aacompromise (10) * add invalidity date extension: the invalidity date is a non-critical crl entry extension that provides the date on which it is known or suspected that the private key ...
NSS tools : vfychain
options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more.
... -r following certfile is raw binary der (default) -t following cert is explicitly trusted (overrides db trust) -u usage 0=ssl client, 1=ssl server, 2=ssl stepup, 3=ssl ca, 4=email signer, 5=email recipient, 6=object signer, 9=protectedobjectsigner, 10=ocsp responder, 11=any ca -v verbose mode.
... prints root cert subject(double the argument for whole root cert info) -w password database password -w pwfile password file revocation options for pkix api (invoked with -pp options) is a collection of the following flags: [-g type [-h flags] [-m type [-s flags]] ...] ...
ssltyp.html
syntax #include <seccomon.h> typedef enum { secwouldblock = -2, secfailure = -1, secsuccess = 0 } secstatus; enumerators the enum includes the following enumerators: secwouldblock reserved for internal use.
... syntax #include <prtypes.h> secstatus secitem_freeitem ( secitem *item, prbool freeitem) parameter this function has the following parameter: item a pointer to a secitem structure.
... syntax #include <prtypes.h> secstatus secitem_zfreeitem ( secitem *item, prbool freeitem) parameter this function has the following parameter: item a pointer to a secitem structure.
NSS tools : crlutil
MozillaProjectsNSStoolscrlutil
to run the certificate revocation list management tool, type the command crlutil option [arguments] where options and arguments are combinations of the options and arguments listed in the following section.
... crl generation script syntax crl generation script file has the following syntax: * line with comments should have # as a first symbol of a line * set "this update" or "next update" crl fields: update=yyyymmddhhmmssz nextupdate=yyyymmddhhmmssz field "next update" is optional.
... reasoncode non-critical code where: reasoncode: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension code: the following codes are available: unspecified (0), keycompromise (1), cacompromise (2), affiliationchanged (3), superseded (4), cessationofoperation (5), certificatehold (6), removefromcrl (8), privilegewithdrawn (9), aacompromise (10) * add invalidity date extension: the invalidity date is a non-critical crl entry extension that provides the date on which it is known or suspected that...
NSS tools : vfychain
options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, ...
... -r following certfile is raw binary der (default) -t following cert is explicitly trusted (overrides db trust) -u usage 0=ssl client, 1=ssl server, 2=ssl stepup, 3=ssl ca, 4=email signer, 5=email recipient, 6=object signer, 9=protectedobjectsigner, 10=ocsp responder, 11=any ca -v verbose mode.
... prints root cert subject(double the argument for whole root cert info) -w password database password -w pwfile password file revocation options for pkix api (invoked with -pp options) is a collection of the following flags: [-g type [-h flags] [-m type [-s flags]] ...] ...
Rhino license
license for portions of the rhino debugger additionally, some files (currently the contents of toolsrc/org/mozilla/javascript/tools/debugger/treetable/) are available under the following license: * copyright 1997, 1998 sun microsystems, inc.
... * * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer.
... * * - redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution.
Creating JavaScript jstest reftests
non262 tests the directory js/src/tests/non262/ should contain all tests of the following type: regressions of spidermonkey non-standard spidermonkey extensions to the javascript language test of "implementation-defined" details of the ecmascript standard for example, the exact definition of pi or some details of array sorting.
... you should not add tests of the following type: tests of the jit test of jit correctness belong in the jit-test suite, read more here.
... you should contribute directly to test262 in the following scenarios: you are writing tests for the implementation of a new feature or feature proposal for ecmascript.
GCIntegration - SpiderMonkey Redirect 1
consider the following example.
...to see how weak pointers can cause trouble, consider the following situation: {{ svg{source: "http://people.mozilla.org/~wmccloskey/incremental2.svg", embedding: "iframe", height:"130"} }} in the left frame, a has a weak pointer to c.
...for example, the following code will be incorrect: autorootedobject obj1 = ...; jsobject *obj2 = obj1; // use obj2 if a gc runs in the middle of this code, and if obj1/obj2 is moved, then the obj1 pointer will be updated to point to the new location.
Introduction to the JavaScript shell
after following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ if you get " symbol lookup error: ./js: undefined symbol: pr_setcurrentthreadname" e.g.
... atline when atline is enabled, comments of the form //@line num set the number of the following line to num.
...for example, if you want to display a message when line 6 of a function, dosomething() is executed, you can enter the following: trap(dosomething, line2pc(dosomething, 6), "print('line 6!\n')"); note: when a trap is set, the corresponding bytecode in the program is replaced with a trap bytecode until you use untrap() to remove the trap.
JSPropertyDescriptor
properties a descriptor is an object that can have the following key values field name description getter the get syntax binds an object property to a function that will be called when that property is looked up.
... examples the following example demonstrates how to use the object.defineproperty() function to create a property under an object in a javascript via a descriptor.
... in other words, the above code is equivalent to the following code.
Parser API
additional options may be provided via the options object, which can include any of the following properties: loc boolean default: true when loc is true, the parser includes source location information in the returned ast nodes.
...all node types implement the following interface: interface node { type: string; loc: sourcelocation | null; } the type field is a string representing the ast variant type.
... interface catchclause <: node { type: "catchclause"; param: pattern; guard: expression | null; body: blockstatement; } a catch clause following a try block.
SpiderMonkey 1.8.5
migrating to spidermonkey 1.8 the following features in earlier versions of spidermonkey have been dropped.
...the following builds are known to not work: i686-apple-darwin9-g++-4.2.1 (gcc) 4.2.1 (apple inc.
...if you are building your project with a gnu-make based build system, the following workaround can be integrated into your build system to generate the correct ldflags, with a strong likelihood that it will work with future versions when js-config is fixed: js_config ?= /path/to/js-config uname_system = $(shell uname -s) jsapi_ldflags = $(shell $(js_config) --libs) ifeq ($(uname_system),darwin) jsapi_ldflags := $(filter -l%,$(jsapi_ldflags)) $(filter -l%,$...
SpiderMonkey 1.8.7
the following features in earlier versions of spidermonkey have been dropped.
...the following builds are known to not work: i686-apple-darwin9-g++-4.2.1 (gcc) 4.2.1 (apple inc.
... if you are building your project with a gnu-make based build system, the following workaround can be integrated into your build system to generate the correct ldflags, with a strong likelihood that it will work with future versions when js-config is fixed: js_config ?= /path/to/js-config uname_system = $(shell uname -s) jsapi_ldflags = $(shell $(js_config) --libs) ifeq ($(uname_system),darwin) jsapi_ldflags := $(filter -l%,$(jsapi_ldflags)) $(filter -l%,$...
TPS History Lists
the history list used for operations other than delete has the following properties: uri: required.
...an array of objects representing visits to the page, each object has the following properties: type: required.
...se an object with begin and end properties, which should have integer values that express time since the present in hours (see date above) for example: var history_to_delete = [ { uri: "http://www.cnn.com/" }, { begin: -24, end: -1 }, { host: "www.google.com" } ]; history lists and phase actions history lists cannot be modified, they can only be added, deleted, and verified, using the following functions: history.add history.delete history.verify history.verifynot ...
TPS Tests
tps tests tend to be broken down into three sections, in the following order (we'll cover these out of order, for the sake of simplicity) phase declarations (mandatory).
...tps iterates through the phase blocks in alphanumeric order, and for each phase, it does the following: launches firefox with the profile from the phases object that corresponds to this test phase.
... otherwise, a special sync can be performed if one of the following are passed: sync_wipe_server, sync_wipe_client, sync_reset_client.
Secure Development Guidelines
the following content will likely see significant revision, though can be used as a reference for security best practices to follow when developing code for mozilla.
... xss: example the following snippet of javascript: document.write("welcome to " + document.location); ...
...&fdset); } file i/o: race conditions operating on files can often lead to race conditions since the file system is shared with other processes you check the state of a file at one point in time and immediately after the state might have changed most file name operations suffer from these race conditions, but not when performed on file descriptors file i/o: race conditions consider the following example int main(int argc, char **argv) { char *file = argv[1]; int fd; struct stat statbuf; stat(file, &statbuf); if (s_islink(statbuf.st_mode)) { bailout(“symbolic link”); } else if (statbuf.st_uid != getuid) { bailout(“you don’t own the file”); } fd = open(file, o_rdwr); write(fd, argv[2], strlen(argv[2])); } file i/o...
Accessing the Windows Registry Using XPCOM
— probably not useful type_string — a unicode string value type_binary — binary data type_int — a 32 bit integer type_int64 — a 64 bit integer each of these types (except type_none) has a corresponding method to read the value data: readstringvalue() readbinaryvalue() readintvalue() readint64value() since javascript is a dynamically-typed language, you may wish to use the following code to handle all types of data.
...you can use it as shown in the following example: var wss = components.classes["@mozilla.org/browser/shell-service;1"] .getservice(components.interfaces.nsiwindowsshellservice); var id = wss.getregistryentry(wss.hklm, "software\\microsoft\\windows\\currentversion", "productid"); note: there's no way to set a registry value using this interface.
...the following skeleton code will allow you to determine which interface to use: if ("@mozilla.org/windows-registry-key;1" in components.classes) { // firefox 1.5 or newer } else if ("@mozilla.org/winhooks;1" in components.classes) { // seamonkey or other older non-toolkit application } else if ("@mozilla.org/browser/shell-service;1" in components.classes) { var wss = components.classes["@mozilla.org/bro...
XPCOM changes in Gecko 2.0
}; // the following line is what xpcom uses to create components.
...to add a category entry, you must insert the following line to your chrome.manifest: category profile-after-change mycomponent @foobar/mycomponent;1 important: formerly, the contract id of the category entry was prefixed with "service," if the component was implemented as a service.
...therefore the following categories have changed: old name new name javascript global constructor javascript-global-constructor javascript global constructor prototype alias javascript-global-constructor-prototype-alias javascript global property javascript-global-property javascript global privileged property javascript-global-privileged-property javascript global static nameset javascript-global-static-nameset javascript global dynamic nameset javascript-global-dynamic-nameset javascript dom class javascript-dom-...
Building the WebLock UI
in the following chapter we'll describe how you can take these files and create a package, an installable archive that includes the weblock component and the new ui.
... weblock.css the following style rules are defined in weblock.css, a css file that is loaded by the overlay and applied to the icon in the browser that reflects the current status of the web lock and provides access to the web lock manager dialog.
... image resources if you are following along with this tutorial and want to use the images we use here for the states of the weblock component in the statusbar, you can download them and the other resources for weblock from http://www.brownhen.com/weblock.
Finishing the Component
see the following sidebar for information about how frozen and unfrozen interfaces can affect your component development, and for technical details about how interface changes beneath your code can cause havoc.
... instead of extracting the string spec out of the nsiuri to do a string comparison, which would require you to do the parsing yourself, you can compare the nsiuri objects with each other, as in the following section.
...ng the io service from the service manager looks like this: // get a pointer to the ioservice rv = servman->getservicebycontractid("@mozilla.org/network/io-service;1", ns_get_iid(nsiioservice), getter_addrefs(mioservice)); once you have this interface pointer, you can easily create nsiuri objects from a string, as in the following snippet: nscomptr<nsiuri> uri; nsembedcstring urlstring(node->urlstring); mioservice->newuri(urlstring, nsnull, nsnull, getter_addrefs(uri)); this code wraps a c-string with a nsembedcstring, which you'll recall is a string class that many of the gecko apis require.
Packaging WebLock
the following sections describe the steps you can take to organize the weblock component for distribution and installation.
... once you have the component and the other resources for weblock packaged properly (see the following section, archiving resources), the installation script for weblock is a simple one (see the weblock installation script).
...the following html specifies a complete webpage in which the trigger script is defined as a javascript function, installweblock, that gets called when the user clicks the hyperlink.
nsIAbCard
following a huge refactoring of the address book code, most of the documentation below is out of date.
... astring generatename(in long agenerateformat,[optional] in nsistringbundle abundle) parameters agenerateformat the format to present the name in: 0 generated name is displayname 1 lastfirst, formatted following lastfirstformat property in addressbook.properties.
... 2 firstlast, formatted following firstlastformat property in addressbook.properties.
nsIAccessible
nsiaccessible.role to get the role of the accessible nsiaccessible.getstate() to get states of the accessibe nsiaccessible.name, nsiaccessible.value to get the name and the value of the accessible tree navigation you can navigate through the accessible tree by the following methods and attributes.
...the following methods are intended for this nsiaccessible.actioncount, nsiaccessible.getactionname(), nsiaccessible.getactiondescription() and nsiaccessible.doaction().
...following methods are used to get them nsiaccessible.defaultkeybinding(), nsiaccessible.getkeybindings(), nsiaccessible.keyboardshortcut.
nsIRequest
the following flags control the flow of data into the cache.
... the following flags control what happens when the cache contains data that could perhaps satisfy this request.
... the following flags control the frequency of cached content validation when neither load_bypass_cache or load_from_cache are set.
nsITelemetry
{ name1: {data1}, name2:{data2}...} where data consists of the following properties: min - minimal bucket size max - maximum bucket size histogram_type - histogram_exponential or histogram_linear counts - an array representing the values of buckets in the histogram.
... return value the returned jsval object has the following functions: add(value) - adds an integer value to the appropriate bucket snapshot() - returns a snapshot of the histogram with the same data fields as in histogramsnapshots.
... return value the returned jsval object has the following functions: add(key, [optional] value) - adds an integer value to the appropriate bucket.
nsITextInputProcessor
you can create an instance of this interface with the following code: var tip = components.classes["@mozilla.org/text-input-processor;1"].
... the following example sets "foo-bar-buzz", "bar" is selected clause to convert, and caret position is the end of the selected clause: // first, sets composition string.
... you should/can specify following attribute values at creating a keyboardevent instance.
LDAP Support
this can be accomplished by setting the following preferences: user_pref("mail.autocomplete.commentcolumn", 2); user_pref("ldap_2.servers.directoryname.autocomplete.commentformat", "[ou]"); the first preference tells us to use a comment column in the type down (the default value is 0 for no comment), and that the value for the comment is a custom string unique to each directory.
...it expects the following format: the desired ldap attribute should be wrapped in square brackets.
... ldap schema the following table summarizes the schema used by thunderbird to map between ldap attributes and attributes within the the address book.
Adding items to the Folder Pane
the following code snippet listens for that event: let gnumbersext = { load: function gne_load() { window.removeeventlistener("load", gnumbersext.load, false); let tree = document.getelementbyid("foldertree"); tree.addeventlistener("maprebuild", gnumbersext._insert, false); }, _insert: function gne__insert() { // this function is called when a rebuild occurs } }; window.addeventlisten...
...each item in this array satisfies the following interface: id (attribute) a unique string for this object.
...ur css attributes here }, command: function gne_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) .alert(window, null, this.text); } }; second, our child items (the numbers 1, 2, and 3) are copies of the following prototype: function numberrow(anumber) { this._number = anumber; } numberrow.prototype = { get id() { return "numbers-child-row-" + this._number; }, get text() { return this._number; }, level: 1, open: false, children: [], getproperties: function gne_kid_getprops() {}, // no-op command: function gne_kid_command() { // just going...
Creating a Custom Column
the following step through will get you well on the road to creating your own columns and populating them with custom data.
...for this we overlay messenger.xul, by placing the following line in our chrome.manifest file: overlay chrome://messenger/content/messenger.xul chrome://replyto_col/content/replyto_col_overlay.xul now that our overlay is set up we need to connect a column to the current columns that exist.
...the following is a list of functions that must be implemented to ensure that your extension works well with thunderbird.
Theme Packaging
theme file layout thunderbird themes are packaged in an xpi file with the following structure: theme.xpi: install.rdf preview.png icon.png chrome/ browser/files communicator/files global/files mozapps/files ...
... install.rdf your install.rdf manifest will look something like this: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:type>4</em:type> more properties </description> </rdf> required install.rdf properties your install.rdf file must have the following properties.
...--> <em:name>new theme 1</em:name> <em:description>a test theme for thunderbird</em:description> <em:creator>ben goodger</em:creator> <em:contributor>john doe</em:contributor> <em:homepageurl>http://www.bengoodger.com/</em:homepageurl> <!-- front end integration hooks (used by theme manager)--> <em:internalname>newtheme1</em:internalname> </description> </rdf> the following are some common target application guids that you can use in your targetapplication properties: thunderbird {3550f703-e582-4d05-9a08-453d09bdfdc6} seamonkey {92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a} pale moon {8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} official references for toolkit api official references.
Using the Multiple Accounts API
to create accounts using the api, you should do the following: create a fresh identity with createidentity(); assign values to the various identity properties as necessary.
...- boolean, should we download new messags on biff (true) or just alert user that there is new mail (false) preference: mail.server.server.directory - local platform-specific path to store messages and folder indexes preference: mail.server.server.name - user-visible name of server the following are specific to imap: preference: mail.server.server.admin_url - administration url for server preference: mail.server.server.using_subscription - boolean, should we use subscriptions?
...preference: mail.server.server.capability - list of capabilities of this server preference: mail.server.server.namespace.public - the server's namespace for public folders preference: mail.server.server.namespace.personal - the server's namespace for personal folders preference: mail.server.server.namespace.other_users - the server's namespace for other user's folders the following are specific to pop: the following are specific to news: preference: mail.server.server.leave_on_server - boolean, should we leave messages on the server after we have downloaded them?
libmime content type handlers
the following xp-com interface is implemented by libmime and is necessary for content type handler plugin development.
...the primary * purpose of these handlers will be to represent the attached data in a * viewable html format that is useful for the user * * note: these will all register by their content type prefixed by the * following: mimecth:text/vcard * * libmime will then use nscomponentmanager::contractidtoclsid() to * locate the appropriate content type handler */ #ifndef nsimimecontenttypehandler_h_ #define nsimimecontenttypehandler_h_ typedef struct { prbool force_inline_display; } contenttypehandlerinitstruct; #include "prtypes.h" #include "nsisupports.h" #include "mimecth.h" // {20dabd99-f8b5-11d2-8ee0-00a024a7d1...
... sample content type handler plugin to see an example of a content type handler plugin, the source for the handler of the content type "text/calendar" can be viewed at the following link: calendar plugin note: this plugin simply creates a blue table in the output stream to identify the fact that it is operational, but the basic constructs of what is needed to build a functional content type handler can be seen.
Toolkit version format
versions in at least the following places must conform to this format: addon's and target application's version in install and update manifests.
... the following preferences: app.extensions.version, extensions.lastappversion versions returned by nsixulappinfo.
...note, that since missing version parts are treated as if they were 0, the following version strings are equal: 1, 1.0, 1.0., 1.0.0, and even 1.0...
Using COM from js-ctypes
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.
... iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->speak(l"hello, firefox!", spf_default, null); pvoice->release(); } } // msdn documentation says that even if coinitalize fails, counitialize // must be called couninitialize(); return 0; } to run the code, save it as test.cpp, and run following command in the directory (needs visual studio).
... &iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->lpvtbl->speak(pvoice, l"hello, firefox!", 0, null); pvoice->lpvtbl->release(pvoice); } } // msdn documentation says that even if coinitalize fails, counitialize // must be called couninitialize(); return 0; } to run the code, save it as test.c, and run following command in the directory.
Debugging Tips
running the following code shows only partial value information.
... let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i); let point = ctypes.structtype("point", [{ x: ctypes.int32_t }, { y: ctypes.int32_t }]) let p = point(10, 20); console.log(p); let pp = p.address(); console.log(pp); the result will be as following: cdata { value: 10 } cdata { x: 10, y: 20 } cdata { contents: cdata } to see more descriptive information, you can use .tosource().
... let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i.constructor.tosource()); let point = ctypes.structtype("point", [{ x: ctypes.int32_t }, { y: ctypes.int32_t }]) let p = point(10, 20); console.log(p.constructor.tosource()); let pp = p.address(); console.log(pp.constructor.tosource()); the result will be as per the following: ctypes.int32_t ctypes.structtype("point", [{ "x": ctypes.int32_t }, { "y": ctypes.int32_t }]) ctypes.structtype("point", [{ "x": ctypes.int32_t }, { "y": ctypes.int32_t }]).ptr ...
Using js-ctypes
this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use.
... windows on windows, the following locations are searched for the library, in this order: the application's directory.
... 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.
Streams - Plugins
the browser can create a stream for several different types of data: for the file specified in the data attribute of the object element or the src attribute of the embed element for a data file for a full-page instance the npp_newstream method has the following syntax: nperror npp_newstream(npp instance, npmimetype type, npstream *stream, npbool seekable, uint16* stype); the instance parameter refers to the plug-in instance receiving the stream; the type parameter represents the stream's mime type.
... the npn_requestread method has the following syntax: nperror npn_requestread(npstream *stream, npbyterange *rangelist); the stream parameter is the stream from which to read bytes; the rangelist parameter specifies the range of bytes in the form of a linked list of npbyterange objects, which the plug-in must allocate.
... 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 sending a stream." example of sending a stream the following code creates a new stream of html text displayed by the browser in a new window, writes it, and destroys the stream.
Inspecting web sockets - Firefox Developer Tools
the following filters are available: all displays all messages (by default, except control messages).
... columns in the response pane in the response pane, you can choose to show the following information about each frame: data size time opcode maskbit finbit the data and time columns are visible by default, but you can customize the interface to see more columns by choosing which ones to show from the context menu that is opened by right-clicking in the table header.
... supported ws protocols the inspector currently supports the following web socket protocols: plain json socket.io sockjs signalr wamp the payload based on those protocols is parsed and displayed as an expandable tree for easy inspection, although you can of course still see the raw data (as sent over the wire) as well.
AudioParam.setValueCurveAtTime() - Web APIs
the setvaluecurveattime() method of the audioparam interface schedules the parameter's value to change following a curve defined by a list of values.
... duration a double representing the total time (in seconds) over which the parameter's value will change following the specified curve.
... usage notes when the parameter's value finishes following the curve, its value is guaranteed to match the last value in the set of values specified in the values parameter.
Using the Beacon API - Web APIs
the following example specifies a handler for the load and beforeunload events.
...function analytics(event) { if (!navigator.sendbeacon) return; var url = "https://example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status = navigator.sendbeacon(url, data); // log the data and result console.log("sendbeacon: url = ", url, "; data = ", data, "; status = ", status); }; the following example creates a submit handler and when that event is fired, the handler calls sendbeacon().
... in the following example, a worker sends a beacon using the url and data from the global context.
Blob - Web APIs
WebAPIBlob
for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data.
...the following code reads the content of a blob as a typed array: const reader = new filereader(); reader.addeventlistener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readasarraybuffer(blob); another way to read content from a blob is to use a response.
... the following code reads the content of a blob as text: const text = await (new response(blob)).text(); or by using blob.prototype.text(): const text = await blob.text(); by using other methods of filereader, it is possible to read the contents of a blob as a string or a data url.
Drawing text - Web APIs
the following diagram from the whatwg demonstrates the various baselines supported by the textbaseline property.
....width, canvas.height); eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', drawcanvas); window.addeventlistener('load', drawcanvas); advanced text measurements in the case you need to obtain more details about the text, the following method allows you to measure it.
... the following code snippet shows how you can measure a text and get its width.
Pixel manipulation with canvas - Web APIs
it contains the following read-only attributes: width the width of the image in pixels.
... for example, to read the blue component's value from the pixel at column 200, row 50 in the image, you would do the following: bluecomponent = imagedata.data[((50 * (imagedata.width * 4)) + (200 * 4)) + 2]; if given a set of coordinates (x and y), you may end up doing something like this: var xcoord = 50; var ycoord = 100; var canvaswidth = 1024; function getcolorindicesforcoord(x, y, width) { var red = y * (width * 4) + x * 4; return [red, red + 1, red + 2, red + 3]; } var colorindices = getcolorindicesforcoor...
... for example, to paint the entire image represented by myimagedata to the top left corner of the context, you can simply do the following: ctx.putimagedata(myimagedata, 0, 0); grayscaling and inverting colors in this example we iterate over all pixels to change their values, then we put the modified pixel array back to the canvas using putimagedata().
DOMTokenList.replace() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
... first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let result = classes.replace("c", "z"); console.log(result); if (result) { span.textcontent = classes; } else { span.textcontent = 'token not replaced successfully'; } the output looks like this: polyfill the following polyfill will add the replace method to the domtokenlist class.
... the following code will only work with ie10-11.
DirectoryReaderSync - Web APIs
example in the following code snippet from html5rocks, we create web workers and pass data from it to the main app.
... console.log(fileentry.name); }); }); }; worker.postmessage({'cmd': 'list'}); the following is worker.js code that gets the contents of the directory.
... entrysync readentries ( ) raises (fileexception); returns parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist.
EventTarget.addEventListener() - Web APIs
this is shown in the following example: <script> function logid() { console.log(this.id); } </script> <table id="my_table" onclick="logid();"><!-- when called, `this` will refer to the global object --> ...
... polyfill you can work around addeventlistener(), removeeventlistener(), event.preventdefault(), and event.stoppropagation() not being supported by internet explorer 8 by using the following code at the beginning of your script.
...the following code only adds ie 8 support.
Using Fetch - Web APIs
have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); here we are fetching a json file across the network and printing it to the console.
...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).
...a body is an instance of any of the following types: arraybuffer arraybufferview (uint8array and friends) blob/file string urlsearchparams formdata the body mixin defines the following methods to extract a body (implemented by both request and response).
HTMLAnchorElement - Web APIs
living standard the following property has been added: download.
... the following properties are now obsolete: charset, coords, name, rev, and shape.
... the following properties have been added: hash, host, hostname, media, pathname, port, protocol, rellist, search, and text.
HTMLAreaElement - Web APIs
living standard the following property has been added: download.
... the following property is now obsolete: nohref.
... the following properties have been added: rel, rellist, media, hreflang, type, host, hostname, pathname, port, protocol, search, and hash.
HTMLIFrameElement - Web APIs
living standard the following property has been added: allowfullscreen.
... recommendation the following properties are now obsolete: scrolling, marginwidth, marginheight, longdesc, frameborder, and align.
... the following properties have been added: srcdoc, sandbox, and contentwindow.
HTMLLinkElement - Web APIs
living standard adds the following properties: crossorigin, referrerpolicy, and as.
... recommendation the following properties are now obsolete: charset, rev, and shape.
... the following properties have been added: rellist, and sizes.
HTMLObjectElement - Web APIs
the following properties are now obsolete: align, archive, border, code, codebase, codetype, declare, hspace, standby, and vspace.
... the following properties have been added: typemustmatch, contentwindow, willvalidate, validity, and validationmessage.
... the following methods have been added: checkvalidity() and setcustomvalidity().
HTMLOrForeignElement.dataset - Web APIs
it must contain only letters, numbers, and the following characters: dash (-), dot (.), colon (:), underscore (_)—but not any ascii capital letters (a to z).
... name conversion dash-style to camelcase conversion a custom data attribute name is transformed to a key for the domstringmap entry with the following rules the prefix data- is removed (including the dash); for any dash (u+002d) followed by an ascii lowercase letter a to z, the dash is removed, and the letter is transformed into its uppercase counterpart; other characters (including other dashes) are left unchanged.
... camelcase to dash-style conversion the opposite transformation, which maps a key to an attribute name, uses the following rules: restriction: before the transformation, a dash must not be immediately followed by an ascii lowercase letter a to z; the prefix data- is added; any ascii uppercase letter a to z is transformed into a dash, followed by its lowercase counterpart; other characters are left unchanged.
HTMLTableElement - Web APIs
obsolete properties warning: the following properties are obsolete.
...it reflects the obsolete frame attribute and can take one of the following values: "void", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", or "border".
...it reflects the obsolete rules attribute and can take one of the following values: "none", "groups", "rows", "cols", or "all".
Using microtasks in JavaScript with queueMicrotask() - Web APIs
the rest will have to wait until the following iteration.
... 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.
... 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.
Recommended Drag Types - Web APIs
the following example shows how to create an area for receiving dropped files: <listbox ondragenter="return checkdrag(event)" ondragover="return checkdrag(event)" ondrop="dodrop(event)"/> <script> function checkdrag(event) { return event.datatransfer.types.contains("application/x-moz-file"); } function dodrop(event) { var file = event.datatransfer.mozgetdataat("application/x-moz-file",...
... as a result, the contains method no longer works; the includes method should be used instead to check if a specific type of data is provided, using code like the following: if ([...event.datatransfer.types].includes('text/html')) { // do something } you could use feature detection to determine which method is supported on types, then run code as appropriate.
...the following sample offers an overview of this advanced case: // currentevent is an existing drag operation event currentevent.datatransfer.setdata("text/x-moz-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-dest-filename", leafname); currentevent.datatransfer.mozsetdataat('application/x-moz-file-prom...
Working with the History API - Web APIs
example of pushstate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar", } history.pushstate(stateobj, "page 2", "bar.html") this will cause the url bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
... example of replacestate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar" } history.pushstate(stateobj, "page 2", "bar.html") the explanation of these two lines above can be found at the above section example of pushstate() method section.
... next, suppose http://mozilla.org/bar.html executes the following javascript: history.replacestate(stateobj, "page 3", "bar2.html") this will cause the url bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.
IDBDatabase.transaction() - Web APIs
therefore the following lines are equivalent: var transaction = db.transaction(['my-store-name']); var transaction = db.transaction('my-store-name'); if you need to access all object stores in the database, you can use the property idbdatabase.objectstorenames: var transaction = db.transaction(db.objectstorenames); passing an empty array will throw an exception.
... if you need to open the object store in readwrite mode to change data, you would use the following: var transaction = db.transaction('my-store-name', "readwrite"); as of firefox 40, indexeddb transactions have relaxed durability guarantees to increase performance (see bug 1112702), which is the same behaviour as other indexeddb-supporting browsers.
... exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror the close() method has previously been called on this idbdatabase instance.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
exceptions this method may raise a domexception of the following types: exception description typeerror the value of version is zero or a negative number or not a number.
... example example of calling open with the current specification's version parameter: var request = window.indexeddb.open("todolist", 4); in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
... for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes // of implementations you want to test.
IDBObjectStore.add() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode.
... dataerror any of the following conditions apply: the object store uses in-line keys or has a key generator, and a key parameter was provided.
... example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
IDBObjectStore.createIndex() - Web APIs
objectparameters optional an idbindexparameters object, which can include the following properties: attribute description unique if true, the index will not allow duplicate values for a single key.
... exceptions this method may raise a domexception of one of the following types: exception description constrainterror occurs if an index with the same name already exists in the database.
...has been deleted or removed.) in firefox previous to version 41, an invalidstateerror was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
IDBObjectStore.put() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode.
... dataerror any of the following conditions apply: the object store uses in-line keys or has a key generator, and a key parameter was provided.
... example the following example requests a given record title; when that request is successful the onsuccess function 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 into the object store in another request with put().
IDBTransactionSync - Web APIs
void abort( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following code: non_transient_err if this transaction has already been committed or aborted.
... void commit( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if this transaction has already been committed or aborted.
... exceptions the method can raise an idbdatabaseexception with the following code: not_found_err if the requested object store is not in this transaction's scope.
compareVersion - Web APIs
method of installtrigger object syntax int compareversion ( string registryname, installversion version); int compareversion ( string registryname, string version); int compareversion ( string registryname, int major, int minor, int release, int build); parameters the compareversion method has the following parameters: registryname the pathname in the client version registry for the component whose version is to be compared.
...in particular, this method returns one of the following values: -5 component not present or not registered.
... the following constants can be used to check the value returned by compareversion: int major_diff = 4; int minor_diff = 3; int rel_diff = 2; int bld_diff = 1; int equal = 0; in communicator 4.5, the following constants are defined and available for checking the value returned by compareversion: <code>installtrigger.major_diff installtrigger.minor_diff installtrigger.rel_diff installtrigger.bld_diff install...
Timing element visibility with the Intersection Observer API - Web APIs
the following style is applied to that: main { grid-column: 2; grid-row: 2; margin: 0; margin-left: 16px; font-size: 16px; } the primary feature here is that the grid position is set to place the body content in column 2, row 2.
... ads finally, the ads have the following initial styling.
...following every odd-numbered article, an ad is "loaded" and inserted into the page.
MediaStreamAudioSourceNode - Web APIs
properties in addition to the following properties, mediastreamaudiosourcenode inherits the properties of its parent, audionode.
... if you do chooose to use mediastreamaudiosourcenode, you should keep the following in mind.
...music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; note: as a consequence of calling createmediastreamsource(), audio playback from the media stream will be re-routed into the processing graph of the audiocontext.
MediaTrackConstraints - Web APIs
properties some combination—but not necessarily all—of the following properties will exist on the object.
...the value may be a single one of the following strings, or an array of them to allow the browser flexibility in deciding what to do about the cursor.
...this may be a single one of the following strings, or a list of them to allow multiple source surfaces: application the stream contains all of the windows of the application chosen by the user rendered into the one video track.
Navigator.sendBeacon() - Web APIs
historically, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest call in unload or beforeunload event handlers.
... the following example shows theoretical analytics code that attempts to submit data to a server with a synchronous xmlhttprequest in an unload handler.
... the following example shows a theoretical analytics code pattern that submits data to a server using the sendbeacon() method.
OscillatorNode - Web APIs
properties inherits properties from its parent, audioscheduledsourcenode, and adds the following properties: oscillatornode.frequency an a-rate audioparam representing the frequency of oscillation in hertz (though the audioparam returned is read-only, the value it represents is not).
... methods inherits methods from its parent, audioscheduledsourcenode, and adds the following: oscillatornode.setperiodicwave() sets a periodicwave which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the type to custom.
... examples the following example shows basic usage of an audiocontext to create an oscillator node and to start playing a tone on it.
PaintWorklet - Web APIs
examples the following three examples go together to show creating, loading, and using a paintworklet.
... create a paintworklet the following shows an example worklet module.
...< geom.height/size; y++) { for(let x = 0; x < geom.width/size; x++) { const color = colors[(x + y) % colors.length]; ctx.beginpath(); ctx.fillstyle = color; ctx.rect(x * size, y * size, size, size); ctx.fill(); } } } } // register our class under a specific name registerpaint('checkerboard', checkerboardpainter); load a paintworklet the following example demonstrates loading the above worklet from its js file and does so by feature detection.
Using the Payment Request API - Web APIs
in the following snippet, a merchant page performs this check, and if it returns true updates the checkout button to use paymentrequest instead of legacy web forms.
... in the following snippet we do just this — depending on whether the user can make a fast payment or needs to add payment credentials first, the title of the checkout button changes between "fast checkout with w3c" and "setup w3c checkout".
... }); the payment handler would include the following code: self.addeventlistener('canmakepayment', function(evt) { // pre-authorize here.
PerformanceNavigationTiming - Web APIs
t x="201" y="1" width="270" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="336" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancenavigationtiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface extends the following performanceentry properties for navigation performance entry types by qualifying and constraining them as follows: performanceentry.entrytype read only returns "navigation".
... this interface also extends following performanceresourcetiming properties for navigation performance entry types by qualifying and constraining them as follows: performanceresourcetiming.initiatortyperead only returns "navigation".
... the interface also supports the following properties: performancenavigationtiming.domcomplete read only a domhighrestimestamp representing a time value equal to the time immediately before the browser sets the current document readiness of the current document to complete.
RTCPeerConnection.setRemoteDescription() - Web APIs
this lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's u...
... exceptions the following exceptions are reported to the rejection handler for the promise returned by setremotedescription(): invalidaccesserror the content of the description is invalid.
... 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.
ServiceWorkerContainer.register() - Web APIs
the following example uses the default value of scope (by omitting it).
... navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } the following code, if included in example.com/index.html, at the root of a site, would apply to exactly the same pages as the example above.
... the following code, if included in example.com/index.html, at the root of a site, would only apply to resources under example.com/product.
ShadowRoot - Web APIs
properties included from documentorshadowroot the shadowroot interface includes the following properties defined on the documentorshadowroot mixin.
... methods the shadowroot interface includes the following methods defined on the documentorshadowroot mixin.
... examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
Using Touch Events - Web APIs
interfaces touch events consist of three interfaces (touch, touchevent and touchlist) and the following event types: touchstart - fired when a touch point is placed on the touch surface.
...this interface's attributes include the state of several modifier keys (for example the shift key) and the following touch lists: touches - a list of all of the touch points currently on the screen.
... examples and demos the following documents describe how to use touch events and include example code: touch events overview implement custom gestures introduction to touch events in javascript add touch screen support to your website (the easy way) touch event demonstrations: paint program (by rick byers) touch/pointer tests and demos (by patrick h.
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer.
... when using a webgl 2 context, the following values can be returned additionally: gl.framebuffer_incomplete_multisample: the values of gl.renderbuffer_samples are different among attached renderbuffers, or are non-zero if the attached images are a mix of renderbuffers and textures.
... when using the ovr_multiview2 extension, the following value can be returned additionally: ext.framebuffer_incomplete_view_targets_ovr: if baseviewindex is not the same for all framebuffer attachment points where the value of framebuffer_attachment_object_type is not none, the framebuffer is considered incomplete.
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer.
... when using a webgl 2 context, the following values are available additionally: gl.color_attachment1 gl.color_attachment2 gl.color_attachment3 gl.color_attachment4 gl.color_attachment5 gl.color_attachment6 gl.color_attachment7 gl.color_attachment8 gl.color_attachment9 gl.color_attachment10 gl.color_attachment11 gl.color_attachment12 gl.color_attachment13 gl.color_attac...
... when using a webgl 2 context, the following values are available additionally: gl.framebuffer_attachment_alpha_size gl.framebuffer_attachment_blue_size gl.framebuffer_attachment_color_encoding gl.framebuffer_attachment_component_type gl.framebuffer_attachment_depth_size gl.framebuffer_attachment_green_size gl.framebuffer_attachment_red_size gl.framebuffer_attachment_stencil_size gl.framebuffer_attach...
WebGLRenderingContext.getParameter() - Web APIs
parameter names webgl 1 you can query the following pname parameters when using a webglrenderingcontext.
...ebgltexture or null gl.unpack_alignment glint gl.unpack_colorspace_conversion_webgl glenum gl.unpack_flip_y_webgl glboolean gl.unpack_premultiply_alpha_webgl glboolean gl.vendor domstring gl.version domstring gl.viewport int32array (with 4 elements) webgl 2 you can query the following pname parameters when using a webgl2renderingcontext.
... webgl extensions you can query the following pname parameters when using webgl extensions: constant returned type extension description ext.max_texture_max_anisotropy_ext glfloat ext_texture_filter_anisotropic maximum available anisotropy.
WebGL model view projection - Web APIs
the following code sample defines a method on the cubedemo object that will create the model matrix.
...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 below is that it flips the z axis.
... the following computeviewmatrix() method animates the view matrix by moving it in and out, and left and right.
WebXR Device API - Web APIs
to accomplish these things, the webxr device api provides the following key capabilities: find compatible vr or ar output devices render a 3d scene to the device at an appropriate frame rate (optionally) mirror the output to a 2d display create vectors representing the movements of input controls at the most basic level, a scene is presented in 3d by computing the perspective to apply to the scene in order to render it from the viewpoint of each of the user's...
... event interfaces the following interfaces are used to represent the events used by the webxr api.
... guides and tutorials the following guides and tutorials are a great resource to learn how to comprehend webxr and the underlying 3d and vr/ar graphics concepts.
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
example the following example sets up two simple buttons in a web page and hooks them to the settimeout() and cleartimeout() routines.
... see the following example: myarray = ['zero', 'one', 'two']; myarray.mymethod = function (sproperty) { alert(arguments.length > 0 ?
...however, in the following: settimeout(myarray.mymethod, 1.0*1000); // prints "[object window]" after 1 second settimeout(myarray.mymethod, 1.5*1000, '1'); // prints "undefined" after 1.5 seconds the myarray.mymethod function is passed to settimeout, then when it's called, its this is not set so it defaults to the window object.
XRSession.requestAnimationFrame() - Web APIs
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.
... example the following example requests xrsession with "inline" mode so that it can be displayed in an html element (without the need for a separate ar or vr device).
... } }) }) the following example was taken directly from the spec draft.
XRSession.updateRenderState() - Web APIs
the specified object may have any combination of the following fields.
... exceptions this method may throw any of the following exceptions.
... invalidstateerror this may occur for one of the following reasons: the xrsession has already ended, so you cannot change its render state.
XRSystem: requestSession() - Web APIs
exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: invalidstateerror the requested session mode is immersive-vr but there is already an immersive vr session either currently active or in the process of being set up.
... examples creating an immersive vr session the following example calls requestsession() requesting an "immersive-vr" session.
... xrsession.requestanimationframe(onxranimationframe); }).catch(function(error) { // "immersive-vr" sessions are not supported console.warn("'immersive-vr' isn't supported, or an error occurred activating vr!"); }); verifying webxr support and using a button to start vr mode the following example shows how to use both issessionsupported() and requestsession().
ARIA: checkbox role - Accessibility
anging the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user onkeypress handle the case where the user presses the space key to change the state of the checkbox by changing the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user examples the following example creates a simple checkbox element using css and javascript to handle the checked or unchecked status of the element.
... let item = document.getelementbyid('chkpref'); switch(item.getattribute('aria-checked')) { case "true": item.setattribute('aria-checked', "false"); break; case "false": item.setattribute('aria-checked', "true"); break; } } accessibility concerns when the checkbox role is added to an element, the user agent should do the following: expose the element as having a checkbox role in the operating system's accessibility api.
... assistive technology products should do the following: screen readers should announce the element as a checkbox, and optionally provide instructions on how to activate it.
Accessibility documentation index - Accessibility
the following is intended to provide implementation guidance that respects screen readers developers' need to try different things.
... 8 forms aria, accessibility the following pages provide various techniques for improving the accessibility of web forms: 9 alerts aria, accessibility, forms, web you have a form — a contact form, for example — that you want to put some accessible error checking into.
...this can generally be achieved by following web standards and testing rigorously.
Operable - Accessibility
see ui controls and building keyboard accessibility back in 2.1.4 character key shortcuts (a) added in 2.1 if a single character key shortcut exists, then at least one of the following is true: single character key shortcuts can be turned off, remapped or are only active when the relevant user interface component is in focus.
... understanding pointer gestures 2.5.2 pointer cancellation (a) added in 2.1 for functionality that can be operated using a single-pointer at least one of the following is true: no down-event, abort/undo, up reversal or essential.
... understanding label in name 2.5.4 motion actuation (a) added in 2.1 ensure that for functionality that can be triggered by a) device motion (like shaking, tilting) or b) user gestures detected by device sensors (including a camera) that both of the following are true: 1) motion actuation can be disabled, and 2) the functionality can be operated without using device motion or user gestures.
Text labels and names - Accessibility
examples the following example show a simple image map (taken from h24: providing text alternatives for the area elements of image maps): <img src="welcome.gif" usemap="#map1" alt="areas in the library.
... examples the following example shows a simple dialog box, defined as such using role="dialog" and labelled using aria-labelledby.
... example the following example shows code for a figure with a caption.
CSS Box Alignment - CSS: Cascading Style Sheets
basic examples the following examples demonstrate how some of the box alignment properties are applied in grid and flexbox.
... positional alignment keyword values the following values are defined for positional alignment, and can be used as values for content alignment with justify-content and align-content and also for self alignment with justify-self and align-self.
... pages detailing individual alignment properties as the css box alignment properties are implemented differently depending on the specification they interact with, refer to the following pages for each layout type for details of how to use the alignment properties with it: box alignment in flexbox box alignment in css grid layout box alignment in multiple-column layout box alignment for block, absolutely positioned and table layout reference css properties justify-content align-content place-content justify-items align-items place-items justify-self align-self...
Basic concepts of flexbox - CSS: Cascading Style Sheets
you can read more about the relationship between flexbox and the writing modes specification in a later article; however, the following description should help explain why we do not talk about left and right and top and bottom when we describe the direction that our flex items flow in.
...as with all properties in css, some initial values are defined, so when creating a flex container all of the contained flex items will behave in the following way.
... try the following values of justify-content in the live example: flex-start flex-end center space-around space-between space-evenly in the article aligning items in a flex container we will explore these properties in more depth, in order to have a better understanding of how they work.
In Flow and Out of Flow - CSS: Cascading Style Sheets
in the following example i have a heading, paragraph, a list and a final paragraph which contains a strong element.
... you can see the background colour of the following paragraph running underneath, it is only the line boxes of that paragraph that have been shortened to cause the effect of wrapping content around the float.
...you cannot apply anything to the following in-flow content to achieve that.
Using CSS transitions - CSS: Cascading Style Sheets
you can control the individual components of the transition with the following sub-properties: (note that these transitions loop infinitely only for the purpose of our examples; css transitions only visualize a property change from start to finish.
...for example: div { transition-property: opacity, left, top, height; transition-duration: 3s, 5s; } this is treated as if it were: div { transition-property: opacity, left, top, height; transition-duration: 3s, 5s, 3s, 5s; } similarly, if any property's value list is longer than that for transition-property, it's truncated, so if you have the following css: div { transition-property: opacity, left; transition-duration: 3s, 5s, 2s, 1s; } this gets interpreted as: div { transition-property: opacity, left; transition-duration: 3s, 5s; } using transitions when highlighting menus a common use of css is to highlight items in a menu as the user hovers the mouse cursor over them.
...take the following example.
WebKit CSS extensions - CSS: Cascading Style Sheets
t-size-adjust -webkit-text-underline-position -webkit-transform -webkit-transform-origin -webkit-transform-style -webkit-transition -webkit-transition-delay -webkit-transition-duration -webkit-transition-property -webkit-transition-timing-function u-w -webkit-user-select -epub-word-break -epub-writing-mode supported in non-webkit browsers without a prefix, but not standard the following properties are supported in at least one browser without a prefix, but are not on the standards track.
... supported in firefox with -webkit- prefix the following properties are supported with the -webkit- prefix in firefox.
... deprecated -webkit- properties the following properties were once supported with the -webkit- prefix but are no longer supported in evergreen browsers, with or without the -webkit- prefix.
animation - CSS: Cascading Style Sheets
WebCSSanimation
* @keyframes duration | timing-function | delay | iteration-count | direction | fill-mode | play-state | name */ animation: 3s ease-in 1s 2 reverse both paused slidein; /* @keyframes name | duration | timing-function | delay */ animation: 3s linear 1s slidein; /* @keyframes name | duration */ animation: slidein 3s; <div class="grid"> <div class="col"> <div class="note"> given the following animation: <pre>@keyframes slidein { from { transform: scalex(0); } to { transform: scalex(1); } }</pre> </div> <div class="row"> <div class="cell"> <button class="play" title="play"></button> </div> <div class="cell flx"> <div class="overlay">animation: 3s ease-in 1s 2 reverse both paused slidein;</div> <div class="animation a1"></div...
... constituent properties this property is a shorthand for the following css properties: animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function syntax the animation property is specified as one or more single animations, separated by commas.
... each individual animation is specified as: zero or one occurrences of the following values: <single-transition-timing-function> <single-animation-iteration-count> <single-animation-direction> <single-animation-fill-mode> <single-animation-play-state> an optional name for the animation, which may be none, a <custom-ident>, or a <string> zero, one, or two <time> values the order of values within each animation definition is important: the first value that can be parsed as a <time> is assigned to the animation-duration, and the second one is assigned to animation-delay.
calc() - CSS: Cascading Style Sheets
WebCSScalc
the expression can be any simple expression combining the following operators, using standard operator precedence rules: + addition.
...then, the following html makes use of this css: <form> <div id="formbox"> <label>type something:</label> <input type="text"> </div> </form> nested calc() with css variables you can also use calc() with css variables.
... consider the following code: .foo { --widtha: 100px; --widthb: calc(var(--widtha) / 2); --widthc: calc(var(--widthb) / 2); width: var(--widthc); } after all variables are expanded, widthc's value will be calc( calc( 100px / 2) / 2), then when it's assigned to .foo's width property, all inner calc()s (no matter how deeply nested) will be flattened to just parentheses, so the width property's value will be eventually calc( ( 100px / 2) / 2), i.e.
flex - CSS: Cascading Style Sheets
WebCSSflex
constituent properties this property is a shorthand for the following css properties: flex-grow flex-shrink flex-basis syntax /* keyword values */ flex: auto; flex: initial; flex: none; /* one value, unitless number: flex-grow */ flex: 2; /* one value, width/height: flex-basis */ flex: 10em; flex: 30%; flex: min-content; /* two values: flex-grow | flex-basis */ flex: 1 30px; /* two values: flex-grow | flex-shrink */ flex: 2 2; /* three values: flex-gro...
... three-value syntax: the values must be in the following order: a <number> for <flex-grow>.
... description for most purposes, authors should set flex to one of the following values: auto, initial, none, or a positive unitless number.
<image> - CSS: Cascading Style Sheets
WebCSSimage
syntax the <image> data type can be represented with any of the following: an image denoted by the <url> data type a <gradient> data type a part of the webpage, defined by the element() function an image, image fragment or solid patch of color, defined by the image() function a blending of two or more images defined by the cross-fade() function.
... description css can handle the following kinds of images: images with intrinsic dimensions (a natural size), like a jpeg, png, or other raster format.
...if supported, the browser-defined size matching the usual cursor size on the client's system content for a pseudo-element (::after/::before) a 300px × 150px rectangle the concrete object size is calculated using the following algorithm: if the specified size defines both the width and the height, these values are used as the concrete object size.
line-height-step - CSS: Cascading Style Sheets
/* point values */ line-height-step: 18pt; syntax the line-height-step property is specified as any one of the following: a <length>.
... formal definition initial value0applies toblock containersinheritedyescomputed valueabsolute <length>animation typediscrete formal syntax <length> examples setting step unit for line box height in the following example, the height of line box in each paragraph is rounded up to the step unit.
... :root { font-size: 12pt; --my-grid: 18pt; line-height-step: var(--my-grid); } h1 { font-size: 20pt; margin-top: calc(2 * var(--my-grid)); } the result of these rules is shown below in the following screenshot: specifications specification status comment css rhythmic sizingthe definition of 'line-height-step' in that specification.
perspective-origin - CSS: Cascading Style Sheets
syntax /* one-value syntax */ perspective-origin: x-position; /* two-value syntax */ perspective-origin: x-position y-position; /* when both x-position and y-position are keywords, the following is also valid */ perspective-origin: y-position x-position; /* global values */ perspective-origin: inherit; perspective-origin: initial; perspective-origin: unset; values x-position indicates the position of the abscissa of the vanishing point.
... it can have one of the following values: <length-percentage> indicating the position as an absolute length value or relative to the width of the element.
...it can have one of the following values: <length-percentage> indicating the position as an absolute length value or relative to the height of the element.
Audio and Video Delivery - Developer guides
checking whether the browser supports the supplied formats use the following verified sources within your audio and video elements to check support.
...the media server is not delivering the correct mime types with the file although this is usually supported, you may need to add the following to your media server's .htaccess file.
...your files have been encoded incorrectly your files may have been encoded incorrectly — try encoding using one of the following tools, which are proven to be pretty reliable: audacity — free audio editor and recorder miro — free, open-source music and video player handbrake — open source video transcoder firefogg — video and audio encoding for firefox ffmpeg2 — comprehensive command line encoder libav — comprehensive command line encoder vid.ly — video player,transcoding and delivery internet archive — free transcoding and storag...
Block formatting context - Developer guides
a block formatting context is created by at least one of the following: the root element of the document (<html>).
... in the following example, we have a floated element inside a <div> with a border applied.
... section { height:150px; } .box { background-color: rgb(224, 206, 247); border: 5px solid rebeccapurple; } .box[style] { background-color: aliceblue; border: 5px solid steelblue; } .float { float: left; width: 200px; height: 100px; background-color: rgba(255, 255, 255, .5); border:1px solid black; padding: 10px; } exclude external floats in the following example, we are using display:flow-root and floats to implement double columns layout, beacuse an element in the normal flow that establishes a new bfc must not overlap the margin box of any floats in the same block formatting context as the element itself.
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
this change has the following consequences for web developers: if you omit the closing tag for <title>, <style>, <textarea>, or <xmp>, the page will fail to be parsed.
...(there are also some element whose end tags can be omitted in some cases, such as <p> in the example below, but it's simpler to always use end tags for those elements than to make sure that the end tags are only omitted when they aren't necessary.) for example, the following code writes a balanced sub-tree: <script> document.write("<div>"); document.write("<p>some content goes here.</p>"); document.write("</div>"); </script> <!-- non-script html goes here.
... --> in contrast, the following code contains two scripts with unbalanced sub-trees, which causes speculative parsing to fail and therefore the time to parse the document is longer.
Writing forward-compatible websites - Developer guides
it's not always possible to follow all of these, but following as many of them as possible will help future-proof your website.
...if you are following the advice given above so that you have a single code path for all current and unknown browsers, testing that this single code path works in all the major engines makes it extremely probable that your code won't break in the future.
...missing those can lead to unexpected situations due to a following tag name being treated as an attribute on a previous tag.
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
then the following colors are established: the background-color is set using the hsl value specified using hsl(270deg, 50%, 75%).
... for more information about color blindness, see the following articles: medline plus: color blindness (united states national institute of health) american academy of ophthamology: what is color blindness?
...for example, if we don't like the proposed greenish-blue color, we can click the triad color scheme icon, which presents us with the following: that greyish blue in the top-right looks pretty good.
The HTML autocomplete attribute - HTML: Hypertext Markup Language
perhaps the browser offers the ability to save encrypted credit card information, for autocompletion following an authentication procedure.
...using "name" rather than breaking the name down into its components is generally preferred because it avoids dealing with the wide diversity of human names and how they are structured; however, you can use the following autocomplete values if you do need to break the name down into its components: "honorific-prefix" the prefix or title, such as "mrs.", "mr.", "miss", "ms.", "dr.", or "mlle.".
...for example: 〒381-0000 長野県長野市某町123 "〒" and following seven digits shows the postal code.
<hgroup> - HTML: Hypertext Markup Language
WebHTMLElementhgroup
ght be shown in a rendered outline in with a colon character and space (“: ”) or other such punctuation after the primary heading and before the first secondary heading (and with the same or similar punctuation before any other secondary headings an <hgroup> might be shown in a rendered outline in with the primary heading followed by parentheses around the secondary heading(s) consider the following html document: <!doctype html> <title>html standard</title> <body> <hgroup id="document-title"> <h1>html</h1> <h2>living standard — last updated 12 august 2016</h2> </hgroup> <p>some intro to the document.</p> <h2>table of contents</h2> <ol id=toc>...</ol> <h2>first section</h2> <p>some intro to the first section.</p> </body> a rendered outline for that document might lo...
...ok like the following: that is, the rendered outline might show the primary title, html, followed by a colon and space, followed by the secondary title, living standard — last updated 12 august 2016.
... or, the rendered outline for that document might instead look like the following: that is, the rendered outline might show the primary title, html, followed by the secondary title shown in parentheses: (living standard — last updated 12 august 2016).
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
additional attributes along with the attributes common to all <input> elements, date inputs have the following attributes: attribute description max the latest acceptable date min the earliest acceptable date step the stepping interval, when clicking up and down spinner buttons and validating the date max the latest date to accept.
...in the following example, we set a minimum date of 2017-04-01 and a maximum date of 2017-04-30: <form> <label for="party">choose your preferred party date: <input type="date" name="party" min="2017-04-01" max="2017-04-30"> </label> </form> the result is that only days in april 2017 can be selected — the month and year parts of the textbox will be uneditable, and dates outside april 2017 can't be sel...
...for example, try viewing the following in a unsupporting browser: <form> <label for="bday">enter your birthday: <input type="date" name="bday" required pattern="\d{4}-\d{2}-\d{2}"> <span class="validity"></span> </label> <p> <button>submit</button> </p> </form> if you submit it, you'll see that the browser displays an error and highlights the input as invalid if your entry doesn't match the pattern ####-##-## (...
<input type="datetime-local"> - HTML: Hypertext Markup Language
additional attributes in addition to the attributes common to all <input> elements, datetime-local inputs offer the following attributes: attribute description max the latest date and time to accept min the earliest date and time to accept step the stepping interval to use for this input, such as when clicking arrows on spinner controls or performing validation max the latest date and time to accept.
...in the following example we are setting a minimum datetime of 2017-06-01t08:30 and a maximum datetime of 2017-06-30t16:30: <form> <label for="party">enter a date and time for your party booking:</label> <input id="party" type="datetime-local" name="partydate" min="2017-06-01t08:30" max="2017-06-30t16:30"> </form> the result here is that: only days in june 2017 can be selected — only the "days...
...for example, try viewing the following demo in a non-supporting browser: <form> <div> <label for="party">choose your preferred party date and time (required, june 1st 8.30am to june 30th 4.30pm):</label> <input id="party" type="datetime-local" name="partydate" min="2017-06-01t08:30" max="2017-06-30t16:30" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}t[0-9]{2}:[0-9]{2}" required> <span class="validity"></span...
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
using the htmlinputelement.value property, for example: <label for="bday-month">what month were you born in?</label> <input id="bday-month" type="month" name="bday-month" value="2017-06"> var monthcontrol = document.queryselector('input[type="month"]'); monthcontrol.value = '1978-06'; additional attributes in addition to the attributes common to <input> elements, month inputs offer the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options max the latest year and month to accept as a valid input min the earliest year and month to accept as a valid input readonly a boolean which, if present, indicates that the input's value can't be edited...
...in the following example we specify a minimum month of 1900-01 and a maximum month of 1999-12: <form> <label for="bday-month">what month were you born in?</label> <input id="bday-month" type="month" name="bday-month" min="1900-01" max="1999-12"> </form> the result here is that: only months between in january 1900 and december 1999 can be selected; months outside that range can't be scrolled to...
...for example, try viewing the following demo in a browser that doesn't support month inputs: <form> <div> <label for="month">what month would you like to visit us?
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
the following screenshot is taken from firefox for android: a simple number input in its most basic form, a number input can be implemented like this: <label for="ticketnum">number of tickets you would like to buy:</label> <input id="ticketnum" type="number" name="ticketnum" value="0"> a number input is considered valid when empty and when a single number is entered, but is otherwise invalid.
... the following example exhibits all of the above features, as well as using some css to display valid and invalid icons, depending on the input's value: <form> <div> <label for="balloons">number of balloons to order (multiples of 10):</label> <input id="balloons" type="number" name="balloons" step="10" min="0" max="100" required> <span class="validity"></span> </div> <div> <input type="su...
... in the following example is a form for entering the user's height.
<input type="range"> - HTML: Hypertext Markup Language
WebHTMLElementinputrange
events change and input supported common attributes autocomplete, list, max, min, and step idl attributes list, value, and valueasnumber methods stepdown() and stepup() validation there is no pattern validation available; however, the following forms of automatic validation are performed: if the value is set to something which can't be converted into a valid floating-point number, validation fails because the input is suffering from a bad input.
... additional attributes in addition to the attributes shared by all <input> elements, range inputs offer the following attributes: attribute description list the id of the <datalist> element that contains optional pre-defined options max the maximum permitted value min the minimum permitted value step the stepping interval, used both for user interface and validation purposes list the values of the list attribute is the id of a <datalist> el...
... note: the following input attributes do not apply to the input range: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, readonly, required, size, src, and width.
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, telephone number inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum length, in utf-16 characters, to accept as a valid input minlength the minimum length that is considered valid for the field's contents pattern a regular expression the entered val...
... non-standard attributes the following non-standard attributes are available to telephone number input fields.
...for example, let's use this html: <form> <div> <label for="telno">enter a telephone number (required): </label> <input id="telno" name="telno" type="tel" required> <span class="validity"></span> </div> <div> <button>submit</button> </div> </form> and let's include the following css to highlight valid entries with a checkmark and invalid entries with a cross: div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; color: #8b0000; } input:valid+span:after { position: absolute; content: '✓'; paddi...
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
additional attributes in addition to the attributes common to all <input> elements, time inputs offer the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options max the latest time to accept, in the syntax described under time value format min the earliest time to accept as a valid input readonly a boolean attribute which, if present, indicates that the content...
...in the following example we are setting a minimum time of 12:00 and a maximum time of 18:00: <form> <label for="appt-time">choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00"> <span class="validity"></span> </form> here's the css used in the above example.
...for example, try viewing the following demo in a browser that doesn't support time inputs: <form> <div> <label for="appt-time">choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required pattern="[0-9]{2}:[0-9]{2}"> <span class="validity"></span> </div> <div> <input type="submit" value="submit form...
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, url inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid pattern a regular expression the input's...
... non-standard attributes the following non-standard attributes are also available on some browsers.
...submitting this form would cause the following data to be sent to the server: myurl=http%3a%2f%2fwww.example.com.
<table>: The Table element - HTML: Hypertext Markup Language
WebHTMLElementtable
content categories flow content permitted content in this order: an optional <caption> element, zero or more <colgroup> elements, an optional <thead> element, either one of the following: zero or more <tbody> elements one or more <tr> elements an optional <tfoot> element tag omission none, both the starting and ending tag are mandatory.
...it may have the following values: left: the table is displayed on the left side of the document; center: the table is displayed in the center of the document; right: the table is displayed on the right side of the document.
...it can have the following values: none, which indicates that no rules will be displayed; it is the default value; groups, which will cause the rules to be displayed between row groups (defined by the <thead>, <tbody> and <tfoot> elements) and between column groups (defined by the <col> and <colgroup> elements) only; rows, which will cause the rules to be displayed between rows; columns, which will cause the rul...
Browser detection using the user agent - HTTP
although it is off-topic, perhaps the following detailed example might give you insights and ideas that persuade you to forgo user agent sniffing.
...also consider the following.
... the following table summarizes the way major browser vendors indicate that their browsers are running on a mobile device: common browsers user agent strings browser rule example mozilla (gecko, firefox) mobile or tablet token in the comment.
CSP: report-uri - HTTP
content-security-policy: default-src https:; report-uri /csp-violation-report-endpoint/ /csp-violation-report-endpoint/ could for example run a php something like the following that logs the json detailing the violation and, if the violation is the first one added to the log file, sends an email to an administrator: <?php // start configure $log_file = dirname(__file__) .
...$current_domain; http_response_code(204); // http 204 no content $json_data = file_get_contents('php://input'); // we pretty print the json before adding it to the log file if ($json_data = json_decode($json_data)) { $json_data = json_encode($json_data, json_pretty_print | json_unescaped_slashes); if (!file_exists($log_file)) { // send an email $message = "the following content-security-policy violation occurred on " .
... "\n\nfurther cps violations will be logged to the following log file, but no further email notifications will be sent until this log file is deleted:\n\n" .
CSP: script-src - HTTP
syntax one or more sources can be allowed for the script-src policy: content-security-policy: script-src <source>; content-security-policy: script-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation case given this csp header: content-security-policy: script-src https://example.com/ the following script is blocked and won't be loaded or executed: <script src="https://not-example.com/js/library.js"></script> note that inline event handlers are blocked as well: <button id="btn" onclick="dosomething()"> you should replace them with addeventlistener calls: document.getelementbyid("btn").addeventlistener('click', dosomething); unsafe inline script note: disallowing inline styles and in...
...if 'unsafe-eval' isn't specified with the script-src directive, the following methods are blocked and won't have any effect: eval() function() when passing a string literal like to methods like: window.settimeout("alert(\"hello world!\");", 500); window.settimeout window.setinterval window.setimmediate window.execscript (ie < 11 only) strict-dynamic the 'strict-dynamic' source expression specifies that the trust explicitly given to a script pres...
CSP: style-src - HTTP
syntax one or more sources can be allowed for the style-src policy: content-security-policy: style-src <source>; content-security-policy: style-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: style-src https://example.com/ the following stylesheets are blocked and won't load: <link href="https://not-example.com/styles/main.css" rel="stylesheet" type="text/css" /> <style> #inline-style { background: red; } </style> <style> @import url("https://not-example.com/styles/print.css") print; </style> as well as styles loaded using the link header: link: <https://not-example.com/styles/stylesheet.css>;rel=stylesheet inline style...
...if 'unsafe-eval' isn't specified with the style-src directive, the following methods are blocked and won't have any effect: cssstylesheet.insertrule() cssgroupingrule.insertrule() cssstyledeclaration.csstext specifications specification status comment content security policy level 3the definition of 'style-src' in that specification.
Content-Security-Policy-Report-Only - HTTP
content-security-policy: default-src https:; report-uri /csp-violation-report-endpoint/ violation report syntax the report json object contains the following data: blocked-uri the uri of the resource that was blocked from loading by the content security policy.
...it uses the following policy, disallowing everything but stylesheets from cdn.example.com.
...a browser capable of enforcing csp will send the following violation report as a post request to http://example.com/_/csp-reports, when the document is visited: { "csp-report": { "document-uri": "http://example.com/signup.html", "referrer": "", "blocked-uri": "http://example.com/css/style.css", "violated-directive": "style-src cdn.example.com", "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-rep...
Feature-Policy: fullscreen - HTTP
syntax feature-policy: fullscreen <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
...it can do so by delivering the following http response header to define a feature policy: feature-policy: fullscreen 'self' https://example.com with an <iframe> element fastcorp inc.
...it can do so by delivering the following http response header to define a feature policy: feature-policy: fullscreen 'self' then include an allow attribute on the <iframe> element: <iframe src="https://other.com/videoplayer" allow="fullscreen"></iframe> iframe attributes can selectively enable features in certain frames, and not in others, even if those frames contain documents from the same origin.
Feature-Policy: geolocation - HTTP
syntax feature-policy: geolocation <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
...it can do so by delivering the following http response header to define a feature policy: feature-policy: geolocation 'self' https://example.com with an <iframe> element fastcorp inc.
...it can do so by delivering the following http response header to define a feature policy: feature-policy: geolocation 'self' then include an allow attribute on the <iframe> element: <iframe src="https://other.com/map" allow="geolocation"></iframe> iframe attributes can selectively enable features in certain frames, and not in others, even if those frames contain documents from the same origin.
An overview of HTTP - HTTP
WebHTTPOverview
http flow when a client wants to communicate with a server, either the final server or an intermediate proxy, it performs the following steps: open a tcp connection: the tcp connection is used to send a request, or several, and receive an answer.
... requests an example http request: requests consists of the following elements: an http method, usually a verb like get, post or a noun like options or head that defines the operation the client wants to perform.
... responses an example response: responses consist of the following elements: the version of the http protocol they follow.
JavaScript data types and data structures - JavaScript
data property associates a key with a value, and has the following attributes: attributes of a data property attribute type description default value [[value]] any javascript type the value retrieved by a get access of the property.
... accessor property associates a key with one of two accessor functions (get and set) to retrieve or store a value, and has the following attributes: attributes of an accessor property attribute type description default value [[get]] function object or undefined the function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed.
...the following table helps determine the equivalent c data types: type value range size in bytes description web idl type equivalent c type int8array -128 to 127 1 8-bit two's complement signed integer byte int8_t uint8array 0 to 255 1 8-bit unsigned integer octet uint8_t uint8clampedarray 0 to 255 1 8-bit unsigned in...
Keyed collections - JavaScript
the following code shows some basic operations with a map.
...the following example is from nick fitzgerald's blog post "hiding implementation details with ecmascript 6 weakmaps".
... the following code shows some basic operations with a set.
Character classes - JavaScript
types the following table is also duplicated on this cheatsheet.
... has one of the following meanings: matches any single character except line terminators: \n, \r, \u2028 or \u2029.
... \ indicates that the following character should be treated specially, or "escaped".
Regular expression syntax cheatsheet - JavaScript
has one of the following meanings: matches any single character except line terminators: \n, \r, \u2028 or \u2029.
... \ indicates that the following character should be treated specially, or "escaped".
... quantifiers if you are looking to contribute to this document, please also edit the original article note: in the following, item refers not only to singular characters, but also includes character classes, unicode property escapes, groups and ranges.
Inheritance and the prototype chain - JavaScript
following the ecmascript standard, the notation someobject.[[prototype]] is used to designate the prototype of someobject.
... try the following code: function dosomething(){} dosomething.prototype.foo = "bar"; // add a property onto the prototype var dosomeinstancing = new dosomething(); dosomeinstancing.prop = "some value"; // add a property onto the object console.log( dosomeinstancing ); this results in an output similar to the following: { prop: "some value", __proto__: { foo: "bar", constructor: ƒ dosomet...
...op: " + dosomeinstancing.prop); console.log("dosomeinstancing.foo: " + dosomeinstancing.foo); console.log("dosomething.prop: " + dosomething.prop); console.log("dosomething.foo: " + dosomething.foo); console.log("dosomething.prototype.prop: " + dosomething.prototype.prop); console.log("dosomething.prototype.foo: " + dosomething.prototype.foo); this results in the following: dosomeinstancing.prop: some value dosomeinstancing.foo: bar dosomething.prop: undefined dosomething.foo: undefined dosomething.prototype.prop: undefined dosomething.prototype.foo: bar different ways to create objects and the resulting prototype chain objects created with syntax constructs var o = {a: 1}; // the newly created object o has object.prototype as ...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
a "use strict" directive is written at the top of a function that has one of the following parameters: default parameters rest parameters destructuring parameters a "use strict" directive is not allowed at the top of such functions per the ecmascript specification.
...trict mode, you can move the "use strict" directive outside of the function: 'use strict'; function sum(a = 1, b = 2) { return a + b; } function expression a function expression can use yet another workaround: var sum = function sum([a, b]) { // syntaxerror: "use strict" not allowed in function with destructuring parameter 'use strict'; return a + b; }; this can be converted to the following expression: var sum = (function() { 'use strict'; return function sum([a, b]) { return a + b; }; })(); arrow function if an arrow function needs to access the this variable, you can use the arrow function as the enclosing function: var callback = (...args) => { // syntaxerror: "use strict" not allowed in function with rest parameter 'use strict'; return this.run(args); }; t...
...his can be converted to the following expression: var callback = (() => { 'use strict'; return (...args) => { return this.run(args); }; })(); ...
getter - JavaScript
note the following when working with the get syntax: it can have an identifier which is either a number or a string; it must have exactly zero parameters (see incompatible es5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); it must not appear in an object literal with another get or with a data entry for the same property ({ get x() { }, get x() { ...
...this is useful in the following situations: if the calculation of a property value is expensive (takes much ram or cpu time, spawns worker threads, retrieves remote file, etc).
... in the following example, the object has a getter as its own property.
Array.prototype.every() - JavaScript
you can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it.
... if (!testresult) { return false; } } k++; } return true; }; } examples testing size of all array elements the following example tests whether all elements in the array are bigger than 10.
... [12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true​ affecting initial array (modifying, appending, and deleting) the following examples tests the behaviour of the every method when the array is modified.
Array.prototype.find() - JavaScript
however, you can polyfill array.prototype.find with the following snippet: // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!array.prototype.find) { object.defineproperty(array.prototype, 'find', { value: function(predicate) { // 1.
...log(inventory.find(ischerries)); // { name: 'cherries', quantity: 5 } using arrow function and destructuring const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; const result = inventory.find( ({ name }) => name === 'cherries' ); console.log(result) // { name: 'cherries', quantity: 5 } find a prime number in an array the following example finds an element in the array that is a prime number (or returns undefined if there is no prime number): function isprime(element, index, array) { let start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isprime)); // undefined, not found console.log([4, 5, 8, 12].find(i...
...sprime)); // 5 the following examples show that nonexistent and deleted elements are visited, and that the value passed to the callback is their value when visited: // declare array with no elements at indexes 2, 3, and 4 const array = [0,1,,,,5,6]; // shows all indexes, not just those with assigned values array.find(function(value, index) { console.log('visited index ', index, ' with value ', value); }); // shows all indexes, including deleted array.find(function(value, index) { // delete element 5 on first iteration if (index === 0) { console.log('deleting array[5] with value ', array[5]); delete array[5]; } // element 5 is still visited even though deleted console.log('visited index ', index, ' with value ', value); }); // expected output: // deleting array[5] with value...
Array.prototype.lastIndexOf() - JavaScript
you can work around this by inserting the following code at the beginning of your scripts, allowing use of lastindexof in implementations which do not natively support it.
... examples using lastindexof the following example uses lastindexof to locate values in an array.
... var numbers = [2, 5, 9, 2]; numbers.lastindexof(2); // 3 numbers.lastindexof(7); // -1 numbers.lastindexof(2, 3); // 3 numbers.lastindexof(2, 2); // 0 numbers.lastindexof(2, -2); // 0 numbers.lastindexof(2, -1); // 3 finding all the occurrences of an element the following example uses lastindexof to find all the indices of an element in a given array, using push to add them to another array as they are found.
Date - JavaScript
date.prototype.toisostring() converts a date to a string following the iso 8601 extended format.
... examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
... let date = new date(98, 1) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) // deprecated method; 98 maps to 1998 here as well date.setyear(98) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) date.setfullyear(98) // sat feb 01 0098 00:00:00 gmt+0000 (bst) calculating elapsed time the following examples show how to determine the elapsed time between two javascript dates in milliseconds.
Function.prototype.apply() - JavaScript
in the following example we will create a global function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list.
...for alternative methods, please consider one of the following approaches: using object.__proto__: function.prototype.construct = function (aargs) { let onew = {}; onew.__proto__ = this.prototype; this.apply(onew, aargs); return onew; }; using closures: function.prototype.construct = function(aargs) { let fconstructor = this, fnewconstr = function() { fconstructor.apply(this, aargs); }; fnewconstr.prototype = fconstructor.prototype; return new fnewconstr(); }; using the function constructor: function.prototype.construct = function (aargs) { let fnewconstr = new functio...
... for example, imagine having an array like the following, to be used with date constructor: [2012, 11, 4]; in this case you have to write something like: new (function.prototype.bind.apply(date, [null].concat([2012, 11, 4])))().
Intl.Collator() constructor - JavaScript
the following unicode extension keys are allowed: co variant collations for certain locales.
...an object with some or all of the following properties: localematcher the locale matching algorithm to use.
... examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary betw...
Intl.NumberFormat() constructor - JavaScript
the following unicode extension key is allowed: nu the numbering system to be used.
... options optional an object with some or all of the following properties: compactdisplay only used when notation is "compact".
... the following properties fall into two groups: minimumintegerdigits, minimumfractiondigits, and maximumfractiondigits in one group, minimumsignificantdigits and maximumsignificantdigits in the other.
Object.defineProperty() - JavaScript
they share the following optional keys (note: the default value is in the case of defining properties using object.defineproperty()): configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
... a data descriptor also has the following optional keys: value the value associated with the property.
... an accessor descriptor also has the following optional keys: get a function which serves as a getter for the property, or undefined if there is no getter.
handler.apply() - JavaScript
syntax const p = new proxy(target, { apply: function(target, thisarg, argumentslist) { } }); parameters the following parameters are passed to the apply() method.
... interceptions this trap can intercept these operations: proxy(...args) function.prototype.apply() and function.prototype.call() reflect.apply() invariants if the following invariants are violated, the proxy will throw a typeerror.
... examples trapping a function call the following code traps a function call.
handler.deleteProperty() - JavaScript
syntax const p = new proxy(target, { deleteproperty: function(target, property) { } }); parameters the following parameters are passed to the deleteproperty() method.
... interceptions this trap can intercept these operations: property deletion: delete proxy[foo] and delete proxy.foo reflect.deleteproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be deleted, if it exists as a non-configurable own property of the target object.
... examples trapping the delete operator the following code traps the delete operator.
handler.set() - JavaScript
syntax const p = new proxy(target, { set: function(target, property, value, receiver) { } }); parameters the following parameters are passed to the set() method.
... interceptions this trap can intercept these operations: property assignment: proxy[foo] = bar and proxy.foo = bar inherited property assignment: object.create(proxy)[foo] = bar reflect.set() invariants if the following invariants are violated, the proxy will throw a typeerror: cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.
... examples trap setting of a property value the following code traps setting a property value.
RegExpInstance.lastIndex - JavaScript
the following rules apply: if lastindex is greater than the length of the string, test() and exec() fail, then lastindex is set to 0.
... otherwise, lastindex is set to the next position following the most recent match.
... examples using lastindex consider the following sequence of statements: var re = /(hi)?/g; matches the empty string.
RegExp - JavaScript
the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated.
... for example, the following are equivalent: let re = /\w+/ let re = new regexp('\\w+') perl-like regexp properties note that several of the regexp properties have both long and short (perl-like) names.
... examples using a regular expression to change data format the following script uses the replace() method of the string instance to match a name in the format first last and output it in the format last, first.
String.prototype.match() - JavaScript
examples using match() in the following example, match() is used to find 'chapter' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times.
... using global and ignore case flags with match() the following example demonstrates the use of the global and ignore case flags with match().
... using named capturing groups in browsers which support named capturing groups, the following code captures "fox" or "cat" into a group named "animal": const paragraph = 'the quick brown fox jumps over the lazy dog.
String.prototype.substring() - JavaScript
examples using substring() the following example uses substring() to display characters from the string 'mozilla': let anystring = 'mozilla' // displays 'm' console.log(anystring.substring(0, 1)) console.log(anystring.substring(1, 0)) // displays 'mozill' console.log(anystring.substring(0, 6)) // displays 'lla' console.log(anystring.substring(4)) console.log(anystring.substring(4, 7)) console.log(anystring.substring(7, 4)) // displ...
...ays 'mozilla' console.log(anystring.substring(0, 7)) console.log(anystring.substring(0, 10)) using substring() with length property the following example uses the substring() method and length property to extract the last characters of a particular string.
... replacing a substring within a string the following example replaces a substring within a string.
WebAssembly.Memory() constructor - JavaScript
syntax new webassembly.memory(memorydescriptor); parameters memorydescriptor an object that can contain the following members: initial the initial size of the webassembly memory, in units of webassembly pages.
...the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib).
...the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above.
encodeURIComponent() - JavaScript
to be more stringent in adhering to rfc 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized uri delimiting uses, the following can be safely used: function fixedencodeuricomponent(str) { return encodeuricomponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charcodeat(0).tostring(16); }); } examples encoding for content-disposition and link headers the following example provides the special encoding required within utf-8 content-disposition and link server response header parameters (e.g., utf-8 fil...
... // the following are not required for percent-encoding per rfc5987, // so we can allow for a little better readability over the wire: |`^ replace(/%(?:7c|60|5e)/g, unescape); } // here is an alternative to the above function function encoderfc5987valuechars2(str) { return encodeuricomponent(str).
...// i.e., %27 %28 %29 %2a (note that valid encoding of "*" is %2a // which necessitates calling touppercase() to properly encode) // the following are not required for percent-encoding per rfc5987, // so we can allow for a little better readability over the wire: |`^ replace(/%(7c|60|5e)/g, (str, hex) => string.fromcharcode(parseint(hex, 16))); } specifications specification ecmascript (ecma-262)the definition of 'encodeuricomponent' in that specification.
Comma operator (,) - JavaScript
examples if a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.
... the following code prints the values of the diagonal elements in the array: for (var i = 0, j = 9; i <= 9; i++, j--) console.log('a[' + i + '][' + j + '] = ' + a[i][j]); note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression.
... in the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result returned to console (i.e., 4).
export - JavaScript
note: the following is syntactically invalid despite its import equivalent: import defaultexport from 'bar.js'; // valid export defaultexport from 'bar.js'; // invalid the correct way of doing this is to rename the export: export { default as defaultexport } from 'bar.js'; examples using named exports in a module my-module.js, we could include the following code: // module "my-module.js" function cube(x) ...
...aw: function() { console.log('from graph draw function'); } } export { cube, foo, graph }; then in the top-level module included in your html page, we could have: import { cube, foo, graph } from './my-module.js'; graph.options = { color:'blue', thickness:'3px' }; graph.draw(); console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888 it is important to note the following: you need to include this script in your html with a <script> element of type="module", so that it gets recognised as a module and dealt with appropriately.
...if we want to export a single value or to have a fallback value for your module, you could use a default export: // module "my-module.js" export default function cube(x) { return x * x * x; } then, in another script, it is straightforward to import the default export: import cube from './my-module.js'; console.log(cube(3)); // 27 using export from let's take an example where we have the following hierarchy: childmodule1.js: exporting myfunction and myvariable childmodule2.js: exporting myclass parentmodule.js: acting as an aggregator (and doing nothing else) top level module: consuming the exports of parentmodule.js this is what it would look like using code snippets: // in childmodule1.js let myfunction = ...; // assign something useful to myfunction let myvariable = ...; // ass...
for...of - JavaScript
of iterable) { console.log(value); } // 1 // 2 // 3 iterating over the arguments object you can iterate over the arguments object to examine all of the parameters passed into a javascript function: (function() { for (const argument of arguments) { console.log(argument); } })(1, 2, 3); // 1 // 2 // 3 iterating over a dom collection iterating over dom collections like nodelist: the following example adds a read class to paragraphs that are direct descendants of an article: // note: this will only work in platforms that have // implemented nodelist.prototype[symbol.iterator] const articleparagraphs = document.queryselectorall('article > p'); for (const paragraph of articleparagraphs) { paragraph.classlist.add('read'); } closing iterators in for...of loops, abrupt iteration term...
... const gen = (function *(){ yield 1; yield 2; yield 3; })(); for (const o of gen) { console.log(o); break; // closes iterator } // the generator should not be re-used, the following does not make sense!
... the following example shows the difference between a for...of loop and a for...in loop when used with an array.
for - JavaScript
if the expression evaluates to false, execution skips to the first expression following the for construct.
... examples using for the following for statement starts by declaring the variable i and initializing it to 0.
... var i = 0; for (;;) { if (i > 3) break; console.log(i); i++; } using for without a statement the following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.
try...catch - JavaScript
for example, when the exception occurs in the following code, control transfers to the catch-block.
... function isvalidjson(text) { try { json.parse(text); return true; } catch { return false; } } the finally-block the finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block.
... the following example shows one use case for the finally-block.
<semantics> - MathML
the rules of determining the visible child in a <semantics> element are the following: if no rule other rule applies: by default only the first child is rendered, which is supposed to be presentation markup.
... beware that <annotation-xml> elements are only recognized, if the encoding attribute is set to one of the following: "application/mathml-presentation+xml" "mathml-presentation" "svg1.1" "text/html" "image/svg+xml" "application/xml".
... attributes the following attributes can be set on <annotation> and <annotation-xml>: definitionurl the location of the annotation key symbol.
class - SVG: Scalable Vector Graphics
WebSVGAttributeclass
white space in lists is defined as one or more of the following consecutive characters: "space" (u+0020), "tab" (u+0009), "line feed" (u+000a), "carriage return" (u+000d), and "form-feed" (u+000c).
... the following is a template for an ebnf grammar describing the <list-of-ts> syntax: list-of-ts ::= t | t, list-of-ts within the svg dom, values of a <list-of-ts> type are represented by an interface specific for the particular type t.
... } circle.circleclass { stroke: #006600; fill: #cc0000; } ]]> </style> <rect class="rectclass" x="10" y="10" width="100" height="100"/> <circle class="circleclass" cx="40" cy="50" r="26"/> </svg> </body> </html> elements the following elements can use the class attribute: <a> <altglyph> <circle> <clippath> <defs> <desc> <ellipse> <feblend> <fecolormatrix> <fecomponenttransfer> <fecomposite> <feconvolvematrix> <fediffuselighting> <fedisplacementmap> <feflood> <fegaussianblur> <feimage> <femerge> <femorphology> <feoffset> <fespecularlighting> <fetile> <feturbulence> <filter> <font> <foreignobject> <...
clip-rule - SVG: Scalable Vector Graphics
the following fragment of code will cause an evenodd clipping rule to be applied to the clipping path because clip-rule is specified on the <path> element that defines the clipping shape: <g> <clippath id="myclip"> <path d="..." clip-rule="evenodd" /> </clippath> <rect clip-path="url(#myclip)" ...
... /> </g> whereas the following fragment of code will not cause an evenodd clipping rule to be applied because the clip-rule is specified on the referencing element, not on the object defining the clipping shape: <g> <clippath id="myclip"> <path d="..." /> </clippath> <rect clip-path="url(#myclip)" clip-rule="evenodd" ...
...d --> <clippath id="emptystar"> <use xlink:href="#star" clip-rule="evenodd" /> </clippath> <rect clip-path="url(#emptystar)" width="50" height="90" fill="blue" /> <!-- right: nonzero --> <clippath id="filledstar"> <use xlink:href="#star" clip-rule="nonzero" /> </clippath> <rect clip-path="url(#filledstar)" width="50" height="90" x="50" fill="red" /> </svg> elements the following elements can use the clip-rule attribute, but only if they are inside a <clippath> element.
transform - SVG: Scalable Vector Graphics
value <transform-list> default value none animatable yes transform functions the following transform functions can be used by the transform attribute <transform-list> warning: as per the spec, you should be able to also use css transform functions.
...matrix(a,b,c,d,e,f) is equivalent to applying the transformation matrix:(acebdf001)\begin{pmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{pmatrix} which maps coordinates from a previous coordinate system into a new coordinate system by the following matrix equalities:(xnewcoordsysynewcoordsys1)=(acebdf001)(xprevcoordsysyprevcoordsys1)=(axprevcoordsys+cyprevcoordsys+ebxprevcoordsys+dyprevcoordsys+f1) \begin{pmatrix} x_{\mathrm{newcoordsys}} \\ y_{\mathrm{newcoordsys}} \\ 1 \end{pmatrix} = \begin{pmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} x_{\mathrm{prevcoordsys}} \\ y_{\mathrm{prevcoordsys}} \\ 1 \end{pmatrix} ...
...= \begin{pmatrix} a x_{\mathrm{prevcoordsys}} + c y_{\mathrm{prevcoordsys}} + e \\ b x_{\mathrm{prevcoordsys}} + d y_{\mathrm{prevcoordsys}} + f \\ 1 \end{pmatrix} example html,body,svg { height:100% } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="30" height="20" fill="green" /> <!-- in the following example we are applying the matrix: [a c e] [3 -1 30] [b d f] => [1 3 40] [0 0 1] [0 0 1] which transform the rectangle as such: top left corner: oldx=10 oldy=10 newx = a * oldx + c * oldy + e = 3 * 10 - 1 * 10 + 30 = 50 newy = b * oldx + d * oldy + f = 1 * 10 + 3 * 10 + 40 = 80 top right corner: oldx=40 oldy=10 newx = a * oldx + c * oldy + e = 3 * 40 - 1 * 10 + 30 = 140 newy = b * oldx + d * oldy + f = 1 * 40 + 3...
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
3 compatibility sources svg the following sources are used for the compatibility tables on svg elements and attributes: 4 content type needstechnicalreview, svg, types, data types svg makes use of a number of data types.
...but when you try to create a semicircle in svg, you will find out the use of the following properties quickly.
...take a look at the following code.
Namespaces crash course - SVG: Scalable Vector Graphics
consider the following example.
...knowing this will save you some confusion if you come across markup like in the following example: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <body> <h1>svg embedded inline in xhtml</h1> <svg:svg width="300px" height="200px"> <svg:circle cx="150" cy="100" r="50" fill="#ff0000"/> </svg:svg> </body> </html> note that because a namespace prefix is used for the <svg:svg> element and its child <svg:circle>, it wasn't ne...
...if you don't already have one, make one up starting with the following code: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations.
Getting started - SVG: Scalable Vector Graphics
take a look at the following code.
...it will render as shown in the following screenshot.
... (firefox users: click here) the rendering process involves the following: we start with the <svg> root element: a doctype declaration as known from (x)html should be left off because dtd based svg validation leads to more problems than it solves before svg 2, to identify the version of the svg for other types of validation the version and baseprofile attributes should always be used instead.
Subresource Integrity - Web security
therefore, the resource must be served with an access-control-allow-origin header that allows the resource to be shared with the requesting origin; for example: access-control-allow-origin: * examples in the following examples, assume that oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc is already known to be the expected sha-384 hash (digest) of a particular script example-framework.js, and there’s a copy of the script hosted at https://example.com/example-framework.js.
... subresource integrity with the <script> element you can use the following <script> element to tell a browser that before executing the https://example.com/example-framework.js script, the browser must first compare the script to the expected hash, and verify that there's a match.
... how browsers handle subresource integrity browsers handle sri by doing the following: when a browser encounters a <script> or <link> element with an integrity attribute, before executing the script or before applying any stylesheet specified by the <link> element, the browser must first compare the script or stylesheet to the expected hash given in the integrity value.
Using templates and slots - Web Components
let's look at a trivial quick example: <template id="my-paragraph"> <p>my paragraph</p> </template> this won't appear in your page until you grab a reference to it with javascript and then append it to the dom, using something like the following: let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; document.body.appendchild(templatecontent); although trivial, you can already start to see how this could be useful.
... the following set of code snippets show how to use <slot> together with <template> and some javascript to: create a <element-details> element with named slots in its shadow root design the <element-details> element in such a way that, when used in documents, it is rendered from composing the element’s content together with content from its shadow root—that is, pieces of the element’s content are used...
... screenshotlive sample notice the following points about this rendered result: even though the instances of the <element-details> element in the document do not directly use the <details> element, they get rendered using <details> because the shadow root causes them to get populated with that.
Axes - XPath
WebXPathAxes
the following is an extremely brief description of the thirteen available axes and the degree of support available in gecko.
... following indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.
... following-sibling indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
the following document passes the two parameters "color" and "size" to the stylesheet "style.xsl".
...xslt-param name="color" value="red"?> set the parameter 'columns' to the number 2: <?xslt-param name="columns" select="2"?> set the parameter 'books' to a nodeset containing all <book> elements in the null namespace: <?xslt-param name="books" select="//book"?> set the parameter 'show-toc' to boolean true: <?xslt-param name="show-toc" select="true()"?> the select attribute context the following context is used to parse and evaluate the expression in the select attribute.
... an xslt-param-namespace pi affects the expression in the select attribute for all xslt-params following the pi.
Cross-domain Content Scripts - Archive of obsolete content
cross-domain iframes the following "main.js" creates a page-worker which loads a local html file called "page.html", attaches a content script called "page.js" to the page, waits for messages from the script, and logs the payload.
... cross-domain xmlhttprequest the following add-on creates a panel whose content is the summary weather forecast for shetland.
Content Scripts - Archive of obsolete content
the content script simply replaces the content of the page: // main.js var tabs = require("sdk/tabs"); var contentscriptstring = 'document.body.innerhtml = "<h1>this page has been eaten</h1>";' tabs.activetab.attach({ contentscript: contentscriptstring }); the following high-level sdk modules can use content scripts to modify web pages: page-mod: enables you to attach content scripts to web pages that match a specific url pattern.
...the following add-on shows a content script added by page-mod receiving a customevent sent from a context-menu item when the context menu item is clicked.
Classes and Inheritance - Archive of obsolete content
consider the following: let circle = circle(2, 3, 5); circle.draw(); // => typeerror: circle.draw is not a function this is not quite right.
...consider the following: let circle = circle(2, 3, 5); circle instanceof shape; // => false since instances of circle inherit from shape, we definitely want the result of this expression to be true.
Modules - Archive of obsolete content
however, the following example shows how it can be used to load scripts from other locations: const { classes: cc interfaces: ci } = components; var instance = cc["@mozilla.org/moz/jssubscript-loader;1"]; var loader = instance.getservice(ci.mozijssubscriptloader); function loadscript(url) { loader.loadsubscript(url); } when a script is loaded, it is evaluated in the scope of the global object of the scr...
...if the script being loaded is less privileged than the loading script, the access is prevented, as the following example shows: // index.js: let a = loadscript("www.foo.com/a.js", { components: components }); // index.js has chrome privileges components.utils; // => [object nsxpccomponents_utils] // a.js: // a.js has content privileges imports.components.utils; // => undefined modules in the add-on sdk the module system used by the sdk is based on what we learned so far: it follows the commonjs spe...
Module structure of the SDK - Archive of obsolete content
for example, the following add-on contains an additional module directly under "lib", and other modules under subdirectories of "lib": my-addon lib main.js password-dialog.js secrets hash.js storage password-store.js to import modules into main: // main.js code var dialog = require("./password-dialog"); var hash = req...
...just call the following: const { require } = cu.import("resource://gre/modules/commonjs/toolkit/require.js", {}) this will import require() into your scope.
page-worker - Archive of obsolete content
this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at...
...this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the wi...
/loader - Archive of obsolete content
in order to load a module before a main one (for example to bootstrap an environment) the requirer must be created first: let { require, loader, module } = require('toolkit/loader'); let loader = loader(options); let requirer = module(requirerid, requireruri); let require = require(loader, requirer); let boostrap = require(bootstrapid); built-in modules each loader instance exposes the following built-in pseudo modules in addition to those passed via modules: chrome this pseudo module exposes everything that is typically available for js contexts with system principals under the components global.
...it takes the following set of configuration options: name: a string value which identifies the sandbox in about:memory.
content/mod - Archive of obsolete content
for example, the following code applies a style to a content window, adding a border to all divs in page: var attachto = require("sdk/content/mod").attachto; var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); parameters modification : object the modification we want to apply to the target.
... for example, the following code applies and removes a style to a content window, adding a border to all divs in page: var { attachto, detachfrom } = require("sdk/content/mod"); var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); // ...
stylesheet/utils - Archive of obsolete content
it accepts the following values: "agent", "user" and "author".
...it accepts the following values: "agent", "user" and "author".
Chrome Authority - Archive of obsolete content
to obtain these privileges, the module must declare its intent with a statement like the following: var {cc, ci} = require("chrome"); the "chrome" built-in pseudo module is provided by the "toolkit/loader" module.
... for example, none of the following code will be matched by the manifest scanner, leading to exceptions at runtime, when the require() call is prohibited from importing the named modules: // all of these will fail!
Creating Event Targets - Archive of obsolete content
then open "index.js" and add the following code: var {cc, ci} = require("chrome"); var { xpcomutils } = require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { onitemadded: function(aitemid, afolder, aindex) { console.log("added ", bookmarkservice.getbookmarkuri(aitemid).spec...
... create a new file in "lib" called "bookmarks.js", and add the following code: var { emit, on, once, off } = require("sdk/event/core"); var {cc, ci} = require("chrome"); var { xpcomutils }= require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { onitemadded: function(aitemid, afolder, aindex) { emit(expo...
Listening for Load and Unload - Archive of obsolete content
options.loadreason options.loadreason is one of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade exports.onunload() if your add-on exports a function called onunload(), that function will be called when the add-on is unloaded.
... exports.onunload = function (reason) {}; reason reason is one of the following strings describing the reason your add-on was unloaded: uninstall disable shutdown upgrade downgrade if your add-on is disabled, then uninstalled, your onunload listener will only be called once, with the disable reason.
Logging - Archive of obsolete content
the console.log() method prints an informational message: console.log("hello world"); try it out: create a new directory, and navigate to it execute jpm init, accepting all the defaults open "index.js" and add the line above execute jpm run firefox will start, and the following line will appear in the command window you used to execute jpm run: info: hello world!
...the following add-on logs the html content of every tab the user loads, by calling console.log() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentscript: "console.log(document.body.innerhtml);" }); }); console output if you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used.
Bootstrapped extensions - Archive of obsolete content
creating a bootstrapped extension to mark an extension as bootstrappable, you need to add the following element to its install manifest: <em:bootstrap>true</em:bootstrap> then you need to add a bootstrap.js file that contains the required functions; this should be alongside the install.rdf file in the extension's package.
...the data is a simple javascript object with the following properties: property type description id string the id of the add-on being bootstrapped.
JS XPCOM - Archive of obsolete content
with the preferences service from the previous example we can do the following: var preferences = preferences.queryinterface(components.interfaces.nsiprefbranch2); this allows you to use the methods in the nsiprefbranch2 interface.
... determining which interfaces an xpcom component supports to display a list of all interfaces that an xpcom component supports, do the following: // |c| is the xpcom component instance for each (i in components.interfaces) { if (c instanceof i) { alert(i); } } in this context, instanceof is the same as queryinterface except that it returns false instead of throwing an exception when |c| doesn't support interface |i|.
Miscellaneous - Archive of obsolete content
the meaning of the action preference is shown in the following table mousewheel.withxxxkey.action result 0 scroll by lines.
... these properties can be accessed from javascript in the following manner: var common = { _bundle: components.classes["@mozilla.org/intl/stringbundle;1"] .getservice(components.interfaces.nsistringbundleservice) .createbundle("chrome://myext/locale/myext.properties"), getlocalizedmessage: function(msg) { return this._bundle.getstringfromname(msg); } }; alert(common.getlocalizedmessage("invalid.url"...
Progress Listeners - Archive of obsolete content
ions see related documentation onprogresschange: function(awebprogress, arequest, curself, maxself, curtot, maxtot) {}, onstatuschange: function(awebprogress, arequest, astatus, amessage) {}, onsecuritychange: function(awebprogress, arequest, astate) {} } attach the progress listener to a <browser> or a <tabbrowser> element using addprogresslistener, for example for firefox put the following code in a load listener of a main window: gbrowser.addprogresslistener(mylistener); when used with a browser, the second argument is a mask which determines the type of events that will be received.
...using the following code, you will get notified when user navigates to another page (by clicking a link, using the back/forward button, by typing an address in the location bar, etc.) and also when user switches tabs.
Toolbar - Archive of obsolete content
the following code will place your button on the toolbar by default.
... you must not insert your toolbar button between any of the following elements: the combined back/forward button, the location bar, the stop botton, or the reload button.
Tree - Archive of obsolete content
e(i); } to collapse all tree nodes just change the condition: var treeview = tree.treeboxobject.view; for (var i = 0; i < treeview.rowcount; i++) { if (treeview.iscontainer(i) && treeview.iscontaineropen(i)) treeview.toggleopenstate(i); } getting the text from the selected row assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="ontreeselected()"> use the following javascript: function ontreeselected(){ var tree = document.getelementbyid("my-tree"); var cellindex = 0; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(cellindex)); alert(celltext); } getting the tree item from the focused row assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.getelementbyid("my-tr...
...for example, assuming the given <tree>: <tree id="my-tree" onclick="ontreeclicked(event)"> use the following javascript: function ontreeclicked(event){ var tree = document.getelementbyid("my-tree"); var tbo = tree.treeboxobject; // get the row, col and child element at the point var row = { }, col = { }, child = { }; tbo.getcellat(event.clientx, event.clienty, row, col, child); var celltext = tree.view.getcelltext(row.value, col.value); alert(celltext); } getting the selected indices ...
View Source for XUL Applications - Archive of obsolete content
the object can include the following properties: url (required) a string url for the document to view the source of.
... the viewsource method will also accept the following arguments in place of the object: aurl a string url for the document to view the source of.
Displaying web content in an extension without security issues - Archive of obsolete content
the following article explains these security mechanisms, ideally an extension that needs to display web content (which is always potentially dangerous) will use all of them.
...for example, your template document might have this code: <style type="text/css"> #entrytemplate { display: none; } </style> <div id="entrytemplate"> <div class="title"></div> <div class="description"></div> </div> now to insert a new entry in the document you would do the following: var template = doc.getelementbyid("entrytemplate"); var entry = template.clonenode(true); entry.removeattribute("id"); entry.getelementsbyclassname("title")[0].textcontent = title; entry.getelementsbyclassname("description")[0].textcontent = description; template.parentnode.appendchild(entry); the important difference here is that the result will always have the same structure as the template t...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
- #include "nsastring.h"- #include "nsstring.h"- #include "nsreadableutils.h"- #include "nsescape.h" + #include "nsstringapi.h" on windows, if you see the following error, you are including a header you shouldn't be: nsstringfwd.h(60) : fatal error c1001: internal compiler error to debug this error, make in the failing directory, adding the /showincludes directive to figure out what is being included incorrectly: make -c directory/that/failed os_cppflags=-showincludes the frozen string api is similar but not identical to the nonfrozen string api.
... the following functions, however, are implemented in the glue library and can be used from frozen-linkage code: ns_newarrayenumerator (excluding deprecated nsisupportsarray version) ns_newemptyenumerator ns_newunionenumerator nscrt functions in nscrt.h are not available to frozen-linkage code.
Adding windows and dialogs - Archive of obsolete content
the following features are very important and you should always keep them in mind: chrome.
...there isn't much we need to add from what the xul tutorial explains, so go ahead and read the following sections: input controls numeric controls list controls there are some other aspects to take into account when handling input controls, which we cover in the following sections.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
consider the following xul fragment throughout the rest of this section.
... alternative: using bracket-access to object properties object properties can always accessed using the bracket syntax: obj["property"] === obj.property hence the following will work just fine without having to resort to eval.
Connecting to Remote Content - Archive of obsolete content
following initialization, onload and onerror handlers are registered to a callback function to handle the response returned from the remote server.
... assume we need to parse the following data: {"shops": [{"name": "apple", "code": "a001"}, {"name": "orange"}], "total": 100} when the onload callback function is called, the response text is converted into a js object using the parse method.
Getting Started with Firefox Extensions - Archive of obsolete content
issue the following command to unzip the file on linux or mac os x: unzip xulschoolhello1.xpi -d xulschoolhello1 on windows, you can change the file extension from xpi to zip, or open the file directly, then unzip it, using a zip tool.
... you should see the following directory structure: xulschoolhello1 chrome.manifest install.rdf content browseroverlay.xul browseroverlay.js skin browseroverlay.css locale en-us browseroverlay.dtd browseroverlay.properties that's lots of files for something so simple!
The Box Model - Archive of obsolete content
any xul interface can be broken down into the following basic components: boxes text images alignment and flexibility widths and heights margins and paddings menus, toolbar buttons, and even the most complex elements in xul are composed of these simple ingredients.
...if we add flexibility to the hbox in our first example, we get the following result: the box flexes to cover the available horizontal space.
XPCOM Objects - Archive of obsolete content
if you want to see the list in your current firefox installation, just run the following code in the error console: var str = ""; for (var i in components.classes) { str += i + "\n" }; str a run on firefox 3.6.2 with a few extensions installed yields 876 strings.
...(your build will probably break, we'll cover this later on.) in the components directory, the file xsihellocounter.idl has the following contents: #include "nsisupports.idl" /** * counter for the hello world extension.
Extensions support in SeaMonkey 2 - Archive of obsolete content
for example, if you overlay some chrome before the status bar, like this: <vbox id="browser-bottombox"> <something insertbefore="status-bar" /> </vbox> use the following technique to make your overlay work on both seamonkey 2 and firefox 3: <window id="main-window"> <vbox id="browser-bottombox" insertbefore="status-bar"> <something insertbefore="status-bar" /> </vbox> </window> thunderbird 3 gfolderdisplay api seamonkey 2.0 only supports a reduced set of methods: selectedcount selectedmessage selectedmessageisfeed selectedmessageisimap selecte...
... in javascript code you can use the following technique to detect the application: const firefox_id = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"; const thunderbird_id = "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; const seamonkey_id = "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}"; var appinfo = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo); if(appinfo.id == firefox_id) { /...
Signing an extension - Archive of obsolete content
the following instructions also apply to a theme and other xpi files.
... sudo port install nss export your certificate if you have your certificate in firefox, export it by following the steps below.
Search Extension Tutorial (Draft) - Archive of obsolete content
the following file, for instance, would change the default keyword search engine, assuming that an engine with the name example engine is installed, as described below: // this is a localizable preference, so it must contain a url which // points at a properties file containing the preference name as a // property.
...the following example bootstrap.js file illustrates the method: const { classes: cc, interfaces: ci, utils: cu, results: cr } = components; // import the services module.
Localizing an extension - Archive of obsolete content
we do this by creating a string bundle, using the following code: <stringbundleset id="stringbundleset"> <stringbundle id="string-bundle" src="chrome://stockwatcher2/locale/stockwatcher2.properties"/> </stringbundleset> this establishes a new string bundle, referenced by the id "string-bundle", whose keys and values are to be loaded from the stockwatcher2.properties file we've already created.
...we add to refreshinformation() the following code: var stringsbundle = document.getelementbyid("string-bundle"); var changestring = stringsbundle.getstring('changestring') + " "; var openstring = stringsbundle.getstring('openstring') + " "; var lowstring = stringsbundle.getstring('lowstring') + " "; var highstring = stringsbundle.getstring('highstring') + " "; var volumestring = stringsbundle.getstring('volumestring') + " "; this cod...
Enabling quicklaunch for all users - Archive of obsolete content
to enable it, just load the following registry script into the user's windows registry: quicklaunch.reg.
... this can be performed automatically by including the following command into the windows logon script: regedit /s \\server\netlogon\reg\quicklaunch.reg ...
Bookmark Keywords - Archive of obsolete content
thus we could type any of the following into the address bar and get back useful results: <tt>google geitost</tt> <tt>google mozilla keyword bookmark</tt> <tt>google bookmark site:developer.netscape.com</tt> <tt>google netscape xml support -site:netscape.com</tt> a few examples in the course of writing this article, a number 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.
Structure of an installable bundle - Archive of obsolete content
basic structure of a bundle a bundle may include any of the following files: path from the root of the bundle description version information /install.rdf extension/theme install manifest /application.ini application launch manifest /bootstrap.js the bootstrap script for extensions not requiring a restart (those with <em:bootstrap>true</em:bootstrap> in their install.rdf).
...for example, if a plugin vendor wanted to make a plugin available for consumer computers running linux(of the form: /platform/linux*/), macintosh(of the form: /platform/darwin*/), and windows(of the form: /platform/win*/), it would provide the following files: /platform/linux_x86-gcc3/plugins/libmyplugin.so /platform/winnt_x86-msvc/plugins/myplugin.dll /platform/darwin_ppc-gcc3/plugins/libmyplugin.dylib because xpt files are not platform-specific, any associated xpt files would go in the generic components directory: /components/myplugin.xpt if an extension has non-binary platform-specific code (such as code which uses the windows registry...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
build create a new project in visual studio for a win32 gui library (dll) (in .net 2003: win32 template, then switch to dll in application settings in the following dialog, export symbols too?)(in visual studio 2008, it is visualc++|win32|win32 project, then check dll in the wizard).
... add the following preprocessor definitions to project properties|(all configurations)|c++|preprocessor|preprocessor definitions: win32;_windows;xp_win32;xp_win;_x86_;npsimple_exports disable precompiled headers using project properties|(all configurations)|c++|precompiled headers|create/use precompiled header.
Making a Mozilla installation modifiable - Archive of obsolete content
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.
...if you have perl on your system, you can do this with the following command: perl -pi.orig -e 's/(jar:)|(\/[^.\/]+\.jar!)//g' chrome.rdf installed-chrome.txt for example, to convert the url jar:resource:/chrome/comm.jar!/content/necko/, change it to resource:/chrome/content/necko/.
Creating a Microsummary - Archive of obsolete content
for example, if we put the generator file on the web at http://people.mozilla.com/~myk/micro...-generator.xml, and we wanted users to be able to install it from http://people.mozilla.com/~myk/micro...ial/index.html, we might add the following code to the index.html page: <button onclick="window.sidebar.addmicrosummarygenerator('http://people.mozilla.com/~myk/microsummaries/tutorial/sfx-generator.xml')">install the spread firefox home page microsummary!</button> clicking that button will generate a javascript error on browsers that don't support microsummaries, however, so to improve the experience for those users, we should check t...
...we might do so via the following code: <script> const warning = "sorry, you need a microsummary-enabled browser like firefox 2.0 to install and use microsummary generators."; function addgenerator(url) { if (typeof window.sidebar == "object" && typeof window.sidebar.addmicrosummarygenerator == "function") window.sidebar.addmicrosummarygenerator(url); else alert(warning); } </script> <button onclick="addgenerator('http://people.mozilla.com/~myk/microsummaries/tutorial/sfx-generator.xml')">install the spread firefox home page microsummary!</button> note that due to bug 341283, addmicrosummarygenerator() will not accept a relative url.
Drag and Drop - Archive of obsolete content
this should be set to one of the following constants, or several added together.
...the following properties and methods are available: candrop set this property to true if the element the mouse is currently over can accept the object currently being dragged to be dropped on it.
Repackaging Firefox - Archive of obsolete content
the following diagram represents an overview of the process and the pieces involved: you will need the following to get started: a macintosh computer (even for repackaging windows or linux only); it may be either powerpc or intel based.
...this xpi has the following contents chrome.manifest components/partnerbookmarks.js defaults/preferences/partner.js install.rdf locale/ar/partner.properties locale/cs/partner.properties locale/da/partner.properties locale/de/partner.properties locale/el/partner.properties locale/en-gb/partner.properties locale/partner.properties locale/es-ar/partner.properties locale/es-es/partner.properties locale/fi/partner.properties lo...
Using microformats - Archive of obsolete content
if provided, this is a javascript object that contains zero or more of the following flags: recurseexternalframes if true, child frames are included in the search.
...if provided, this is a javascript object that contains zero or more of the following flags: recurseexternalframes if true, child frames that reference external content are included in the search.
JavaScript Client API - Archive of obsolete content
have a look at one of the following files: services/sync/modules/engines/bookmarks.js services/sync/modules/engines/history.js setting up a js module the code for your custom sync engine should live in a js module.
... in this case, it is highly recommended to use the utils.makeguid() helper to generate new guids: let newguid = utils.makeguid(); your store object must implement the following methods: itemexists(id) createrecord(id, collection) changeitemid(oldid, newid) getallids() wipe() create(record) update(record) remove(record) you may also find it useful to override other methods of the base implementation, for example applyincomingbatch if the underlying storage for your data supports batch operations.
importUserCertificates - Archive of obsolete content
if the string is null and no certificate with the same dn exists in the user's certificate store, personal security manager uses the following pattern to derive the nickname: <tt><common name>'s <issuer name> id</tt>.
...if it fails, one of the following error strings will be returned: error string description "error:usercancel" the user canceled the import operation "error:invalidcertificate" one of the certificate packages was incorrectly formatted "error:internalerror" the software encountered some internal error, such as out of memory "error:invalidrequestid" the request id in the re...
Microsummary XML grammar reference - Archive of obsolete content
the following example identifies a generator as being able to summarize all pages on the www.example.com web site except pages named about.html: <pages> <include> ^http://www\.example\.com/ </include> <exclude>/about\.html</exclude> </pages> note: regular expressions intended to match the beginnings of page urls should start with the caret (^) to ensure they do not inadvertently match urls which ...
...firefox determines which interval to apply to a microsummary generated by a generator according to the following rules: firefox processes each <condition> child element in document order.
Microsummary topics - Archive of obsolete content
for example, the following code snippet installs the microsummary generator from the creating a microsummary tutorial: var generatortext = ' \ <?xml version="1.0" encoding="utf-8"?> \ <generator xmlns="http://www.mozilla.org/microsummaries/0.1" \ name="firefox download count" \ uri="urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16}"> \ <template> \ <transform xmlns="http://www.w3.org/1999/x...
...for example, you might include the following header in your response to prevent firefox from making another microsummary-related request for one hour: cache-control: max-age=3600 note: because of a technical limitation (bug 346820), firefox uses the same cache for both microsummary-related requests and user-initiated requests, so the cache headers you return apply to both.
New Security Model for Web Services - Archive of obsolete content
the root element the first element of the file should be the following: <wsa:webscriptaccess xmlns:wsa="http://www.mozilla.org/2002/soap/security"> delegation if the <delegate/> element is present then "web-scripts-access.xml" is required in the subdirectory for uris which are in a subdirectory.
... allowing web script access to permit scripts to access the resources of this server, use the following command: <wsa:allow type="<request-type>" from ="<uri-prefix>"/> the type of request, if specified, will be checked against the type of request being requested by the script, such as "soap", "soapv", or "load".
Porting NSPR to Unix Platforms - Archive of obsolete content
<tt>mozilla/nsprpub/pr/src/md/unix/netbsd.c</tt> you need to modify the following existing files: <tt>mozilla/nsprpub/pr/include/md/makefile</tt> <tt>mozilla/nsprpub/pr/include/md/_unixos.h</tt>: just fix the compiling errors, usually pointed out by the <tt>#error</tt> preprocessor directives we inserted.
... <tt>mozilla/nsprpub/pr/include/md/prosdep.h</tt> <tt>mozilla/nsprpub/pr/src/md/prosdep.c</tt> <tt>mozilla/nsprpub/pr/src/md/unix/makefile</tt> <tt>mozilla/nsprpub/pr/src/md/unix/objs.mk</tt> <tt>mozilla/nsprpub/pr/src/md/unix/unix.c</tt>: just fix the compiling errors, usually pointed out by the <tt>#error</tt> preprocessor directives we inserted for a pthreads port, you need to modify the following files: <tt>mozilla/nsprpub/pr/include/md/_pth.h</tt> files in mozilla/nsprpub/pr/src/pthreads, most likely <tt>ptthread.c</tt> and <tt>ptio.c</tt> testing your port we have some unit tests in <tt>mozilla/nsprpub/pr/tests</tt>.
Frequently Asked Questions - Archive of obsolete content
to be valid the root <svg> tag in svg files must have at least the following two "namespace bindings".
...this is (almost certainly) because the 'xmlns:xlink' attribute has been used in the file without including the following two namespace bindings on the root <svg> tag.
Table Cellmap - Border Collapse - Archive of obsolete content
as one can see from the following illustration this is enough to cover a whole table.
...the following owners are possible: etableowner = 0, ecolgroupowner = 1, eajacolgroupowner = 2, // col group to the left ecolowner = 3, eajacolowner = 4, // col to the left erowgroupowner = 5, eajarowgroupowner = 6, // row group above erowowner = 7, eajarowowner = 8, // row above ecellowner = 9, eajacellowner = 10 // cell to the top or to the left the ownership is determined by the rules for border conflict resolution as defined in css 2.1 corner for the corner we store the corner owne...
Running Tamarin performance tests - Archive of obsolete content
running the performance tests requires the following steps: set the avm environment variable to the path of the avmshell executable.
...just type the following commands after making sure you've set the environment variables correctly.
Tamarin Acceptance Testing - Archive of obsolete content
in order to ensure that changes to the tamarin code base are high quality before submitting, all developers are required to complete the following steps.
... successfully build release and debug versions of the shell with the debugger enabled [info] successfully run the following test suites: acceptance test suite [info] self tests [info] submit a sandbox build request to test against platforms that you may not have locally [info] available tamarin acceptance test suites actionscript acceptance tests: actionscript acceptance tests running tamarin acceptance tests abc assembler tests cmdline tests performance tests actionscript performance tests running tamarin performance tests built-in self tests see instructions in doc/selftest.html in the tamarin repository.
The new nsString class implementation (1999) - Archive of obsolete content
usage patterns how to use these classes to increase the portability, thread and process safety of gecko, i suggest the following rules regarding the use of each of our string class derivatives: <center> string class</center> <center> where to use</center> nsstrimpl use to pass strings between modules who have linked the nsstrimpl function library.
...it is recognized that (ascii) nscstring's are useful in the following contexts: whenever calling libraries that expect a char* variant whenever maximum memory efficiency is essential i would argue that only the first case is normatively legitimate.
URIs and URLs - Archive of obsolete content
together these segments form the url spec with the following syntax: scheme://username:password@host:port/directory/filebasename.fileextension;param?query#ref for performance reasons the complete spec is stored in escaped form in the nsstandardurl object with pointers (position and length) to each basic segment and for the more global segments like path and prehost for example.
... 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.
Using Breakpoints in Venkman - Archive of obsolete content
the following options are available: continue regardless of result causes venkman to continue normal execution after running the breakpoint script.
...the following meta comment types are available: the //@jsd_log comment will insert a breakpoint which is set to execute the script that follows without stopping.
Using XPInstall to Install Plugins - Archive of obsolete content
plugins can consist of the following types of files, all of which can be installed via an xpi package: shared libraries (i.e.
...this install script does all of the following: it installs both a dll and an xpt file to the browser's plugins directory.
dirCreate - Archive of obsolete content
method of file object syntax int dircreate( filespecobject dirtocreate ); parameters the dircreate method has the following parameters: dirtocreate a filespecobject representing the pathname of the directory to create.
...the following simple example demonstrates the use of the dircreate method.
modDateChanged - Archive of obsolete content
method of file object syntax boolean moddatechanged (filespecobject asourcefolder, number anolddate); parameters the moddatechanged method has the following parameters: asourcefolder a filespecobject representing the file to be queried.
... description most often, the date passed in as the second parameter in moddatechanged is the returned value from a moddate on a separate file, as in the following example, in which the dates of two files are compared.
getFolder - Archive of obsolete content
method of install object syntax filespecobject getfolder ( string foldername); filespecobject getfolder ( string foldername, string subdirectory); filespecobject getfolder ( object localdirspec, string subdirectory); parameters the getfolder method has the following parameters: foldername a string representing one of netscape's standard directories.
...the value of foldername must be one of the following (info is based on mozilla 1.7 stable branch, might also work in other versions): "chrome" "components" "current user" "defaults" "file:///" "os drive" "plugins" "preferences" "profile" "program" "temporary" "mac apple menu" "mac c...
loadResources - Archive of obsolete content
be aware that the parameter specifies the file within the xpi and not on the file system, as the following example demonstrates.
... the following lines retrieve the properties as a javascript object and make the values accessible with the familiar "dot property" syntax: reseg2obj = loadresources("bin/res_eg_2.properties"); dump( reseg2obj.title ) ...
enumKeys - Archive of obsolete content
method of winreg object syntax string enumkeys ( string key, int subkeyindex ); parameters the enumkeys method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
...the following example shows how to use enumkeys to find the plugins subdirectory below the various mozilla-based browser installations.
enumValueNames - Archive of obsolete content
method of winreg object syntax string enumvaluenames ( string key, int subkeyindex ); parameters the enumvaluenames method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
...the following brief example retrieves a key value using this method.
XUL Events - Archive of obsolete content
« xul reference home the following tables and sections describe the event handler that are valid for most xul elements.
... window events the following events are dispatched to top-level dom windows and can be listened to using window.addeventlistener.
Accessing Files - Archive of obsolete content
the following example will retrieve a reference to a file named sample.txt located in the profile directory.
...there are several other values which may be used as the first argument to nsiscriptableio.getfile(), listed in the following table.
Getting File Information - Archive of obsolete content
for instance, the following line will set the length of a file to 5000 bytes.
...the following four methods return true or false: nsifile.isreadable() - returns true if the file can be read from.
Writing to Files - Archive of obsolete content
the following methods are available, all of which take one argument, which is the value to write: writeboolean will write a boolean value to a stream.
...if you want to write a negative value, use the following calculation first to convert the value: function writenegative(val) { if (val > 0x7fff) val = ~(0x10000 - val - 1); stream.write16(val); } one last method that is useful for writing to binary streams is the writebytearray method, used to write an array of bytes.
IO - Archive of obsolete content
ArchiveMozillaXULFileGuideIO
the following example will retrieve a reference to a file located in the profile directory named sample.txt.
...for instance, in the following example, a subdirectory is retrieved.
Moving, Copying and Deleting Files - Archive of obsolete content
the following example moves a file 'myfile.txt' in the user's home directory into the temporary directory.
...for instance, the following example renames a file within the same directory: file.moveto(null, "hello.txt"); if the destination file already exists, nsifile.moveto() replaces the existing file.
List of commands - Archive of obsolete content
the following lists commands which might be usable by <command> or command dispatchers/controllers.
...eprevious cmd_charprevious cmd_charnext cmd_selectcharprevious cmd_selectcharnext cmd_beginline cmd_endline cmd_selectbeginline cmd_selectendline cmd_wordprevious cmd_wordnext cmd_selectwordprevious cmd_selectwordnext cmd_scrollpageup cmd_scrollpagedown cmd_scrolllineup cmd_scrolllinedown cmd_movepageup cmd_movepagedown cmd_selectpageup cmd_selectpagedown other commands the following list other commands (prefixed by cmd_ or browser:) which have not been categorized here yet (though they are in the alphabetical list below): http://lxr.mozilla.org/seamonkey/sou...baroverlay.xul http://lxr.mozilla.org/seamonkey/sou...t/navigator.js http://lxr.mozilla.org/seamonkey/sou...toroverlay.xul http://lxr.mozilla.org/seamonkey/sou...onaltoolbar.js http://lxr.mozilla.org/seamonkey/s...
Floating Panels - Archive of obsolete content
a floating panel can be created using the panel element with at least two additional attributes as in the following example: <panel id="tools-panel" noautohide="true" titlebar="normal"> <label control="name" value="name:"/> <textbox id="name"/> </panel> the noautohide attribute is used to indicate that the panel is not temporary.
...a label for the titlebar may be set using the label attribute, as in the following example: <panel id="info-panel" noautohide="true" titlebar="normal" label="image properties"> closing a floating panel unlike other panels, a floating panel does not close when clicking outside of it.
MenuModification - Archive of obsolete content
both the appenditem and insertitemat methods return the new menuitem, so you can further modify it, for instance to add an access key, as in the following example: var item = menu.appenditem("insert", "insert"); item.accesskey = "i"; appending submenus there is no built-in method to append submenus to a menu.
...the following shows how the addsubmenu function above might be rewritten to handle this case.
OpenClose - Archive of obsolete content
in the following example, the popup is anchored below an element, yet is offset by 10 pixels to the right and 2 pixels upwards.
...in the following example, the popup is opened at horizontal positon 100 and vertical position 200: popup.openpopupatscreen(100, 200, false); note that if the supplied coordinates would cause the popup to be partially or completely off screen, the popup will be moved such that it is fully visible, and may be resized if necessary.
Popup Guide - Archive of obsolete content
a brief overview of each type is listed here; more details for each type can be found by following the corresponding links.
... working with popups the following additional information is available about manipulating menus and popups.
Building Trees - Archive of obsolete content
for instance, consider the following css: treechildren::-moz-tree-cell(dave) { background-color: lightgreen; } this would set the background color of a cell to green for any cell with the “dave” property.
... object="?country"/> <triple subject="?country" predicate="http://purl.org/dc/elements/1.1/title" object="?countrytitle"/> </query> <action> <treechildren> <treeitem uri="?photo"> <treerow properties="?countrytitle"> <treecell src="?photo"/> </treerow> </treeitem> </treechildren> </action> </rule> you might use the following css to change the border around rows listing a particular country: treechildren::-moz-tree-row(netherlands) { border: green 1px solid; } the result of this example is a tree where one row has a green border around it.
Multiple Rules - Archive of obsolete content
a multiple rule template looks like the following: <hbox id="photoslist" datasources="template-guide-photos3.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> <template> <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> </query> <rule> <where subject="?titl...
...the following example matches names that contain either the letter 'a' or 'a'.
RDF Modifications - Archive of obsolete content
for instance, an assert call looks like the following: var source = rdf.getresource("http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg"); var predicate = rdf.getresource("http://purl.org/dc/elements/1.1/description"); var target = rdf.getliteral("one of the thirty or so egyptian obelisks"); datasource.assert(source, predicate, target, true); the assert call adds a new triple to the rdf datasource.
...consider the following binding: <binding subject="?start" predicate="http://www.xulplanet.com/rdf/categoryname" object="?name"/> this binding involves a triple pointing out from the starting variable that has been used in these examples.
Special Condition Tests - Archive of obsolete content
for instance, we might use the following: <vbox datasources="template-guide-streets.rdf" ref="http://www.xulplanet.com/rdf/myneighbourhood"> <template> <rule parent="vbox"> <groupbox uri="rdf:*"> <caption label="rdf:http://purl.org/dc/elements/1.1/title"/> </groupbox> </rule> <rule> <label uri="rdf:*" value="rdf:http://www.xulplanet.com/rdf/address"/> </rule> </template> </vbox> on th...
...for instance, we might add the following to the previous example: <button label="houses in my neighbourhood" type="menu" datasources="template-guide-streets.rdf" containment="http://www.xulplanet.com/rdf/address" ref="http://www.xulplanet.com/rdf/myneighbourhood"> the houses do have a value for the 'http://www.xulplanet.com/rdf/address' predicate, so they will also be considered to be containers as well, resulti...
Textbox (XPFE autocomplete) - Archive of obsolete content
a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e.
...the following values are possible, although custom components may be installed which add others.
Adding HTML Elements - Archive of obsolete content
it might be added to the find file window: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> then, you can use html tags as you would normally, keeping in mind the following: you must add a html: prefix to the beginning of each tag, assuming you declared the html namespace as above.
... text outside of html blocks example 3 : source view <html:div> would you like to save the following documents?
Adding Labels and Images - Archive of obsolete content
if the text needs to wrap, you can place the text content inside opening and closing tags as in the following example: example 2 : <label>this is some longer text that will wrap onto several lines.</label> as with html, line breaks and extra whitespace are collapsed into a single space.
...</description> you can set the text via script using the textcontent property, as in the following example: <description id="text" width="200"/> document.getelementbyid('text').textcontent = "some lengthy word wrapped text goes here."; internally, both the label element and the description elements are the same.
Additional Install Features - Archive of obsolete content
the following code will make a copy of the file "/bin/grep" and put it in the directory "/main".
...for example, you might put the following as the last section of your script: if (getlasterror() == success) { performinstall(); } else { cancelinstall(); } error codes that could be returned by getlasterror() are listed in the mozilla source file nsinstall.h.
Anonymous Content - Archive of obsolete content
this results in a display that is equivalent to the following: <binding id="zoombox"> <content> <xul:box flex="1"> <xul:button label="zoom in"/> <xul:box flex="1" style="border: 1px solid black"> <xul:image src="images/happy.jpg"/> <xul:image src="images/angry.jpg"/> </xul:box> <xul:button label="zoom out"/> </xul:box> </content> </binding> from the dom's perspective, the child elements are still in their...
...for example, the following xbl will cause text labels and buttons to appear in a different location than other elements: source <binding id="navbox"> <content> <xul:vbox> <xul:label value="labels and buttons"/> <children includes="label|button"/> </xul:vbox> <xul:vbox> <xul:label value="other elements"/> <children/> </xul:vbox> </content> </binding> the first children element on...
Commands - Archive of obsolete content
it is normal to put a group of commands inside a commandset element, together near the top of the xul file, as in the following: <commandset> <command id="cmd_open" oncommand="alert('open!');"/> <command id="cmd_help" oncommand="alert('help!');"/> </commandset> a command is invoked when the user activates the button or other element attached to the command.
...for example, the following example will disable pasting into a textbox.
Creating Dialogs - Archive of obsolete content
the following values may be used, seperated by commas: accept - an ok button cancel - a cancel button help - a help button disclosure - a disclosure button, which is used for showing more information you can set code to execute when the buttons are pressed using the ondialogaccept, ondialogcancel, ondialoghelp and ondialogdisclosure attributes.
...title="my dialog" description="example dialog"/> <groupbox flex="1"> <caption label="select favourite fruit"/> <radio id="orange" label="oranges because they are fruity"/> <radio id="violet" selected="true" label="strawberries because of their colour"/> <radio id="yellow" label="bananas because they are pre-packaged"/> </groupbox> </dialog> the buttons elements can be accessed with the following javascript // the accept button var acceptbutt = document.documentelement.getbutton("accept") more examples more examples in dialogs and prompts (code snippets).
Custom Tree Views - Archive of obsolete content
the following example shows this: <tree id="my-tree" flex="1"> <treecols> <treecol id="namecol" label="name" flex="1"/> <treecol id="datecol" label="date" flex="1"/> </treecols> <treechildren/> </tree> to assign data to be displayed in the tree, the view object needs to be created which is used to indicate the value of each cell, the total number of rows plus other optional information.
... function setview(){ document.getelementbyid('my-tree').view = treeview; } the following presents the example together.
Focus and Selection - Archive of obsolete content
the following example can be used to apply a function to handle a focus event.
...the following example demonstrates this: example 5 : source view <textbox id="addr"/> <button label="focus" oncommand="document.getelementbyid('addr').focus()"/> or, you can use the methods advancefocus and rewindfocus on the command dispatcher.
Install Scripts - Archive of obsolete content
the install script should take the following steps: initialize the installation by specifying what package and version is being installed.
...this key is structured as directory-like path of the following form: /author/package name replace the word author with your name and replace the package name with the name of the package that you are installing.
Introduction to XBL - Archive of obsolete content
the following example shows the basic skeleton of an xbl file: <?xml version="1.0"?> <bindings xmlns="http://www.mozilla.org/xbl"> <binding id="binding1"> <!-- content, property, method and event descriptions go here --> </binding> <binding id="binding2"> <!-- content, property, method and event descriptions go here --> </binding> </bindings> the bindings element is the root element of an xbl ...
...the following example demonstrates this.
List Controls - Archive of obsolete content
the following example demonstrates these additional features: example 2 : source view <listbox rows="3"> <listitem label="butter pecan" value="bpecan" /> <listitem label="chocolate chip" value="chocchip" /> <listitem label="raspberry ripple" value="raspripple" /> <listitem label="squash swirl" value="squash" /> </listbox> the example has been changed to display only 3 rows at a time.
... the following example is of a listbox with two columns and three rows: example 3 : source view <listbox> <listcols> <listcol/> <listcol/> </listcols> <listitem> <listcell label="george" /> <listcell label="house painter" /> </listitem> <listitem> <listcell label="mary ellen" /> <listcell label="candle maker" /> </listitem> <listitem> <listcell label="roger" /> <...
Localization - Archive of obsolete content
to do this, add a line of the following form somewhere near the top of the xul file: <!doctype window system "chrome://findfile/locale/findfile.dtd"> this line specifies that the url indicated is to be used as a dtd for the file.
... for japanese: <!entity findlabel "検索"> for example, the following text: <description value="&findlabel;"/> is translated as: english version: <description value="find"/> japanese version: <description value="検索"/> you would declare an entity for each label or string of text that you use in your interface.
Manipulating Lists - Archive of obsolete content
getting the selected item these two properties are commonly inspected during a select event, as in the following example: example 2 : source view <listbox id="thelist" onselect="alert(this.selecteditem.label);"> <listitem label="short"/> <listitem label="medium"/> <listitem label="tall"/> </listbox> the select event is fired for a listbox when an item in the list is selected.
... deleting selected items the following example shows a method of deleting the selected items properly: example 4 : source view <script> function deleteselection(){ var list = document.getelementbyid('thelist'); var count = list.selectedcount; while (count--){ var item = list.selecteditems[0]; list.removeitemat(list.getindexofitem(item)); } } </script> <button label="delete" oncommand="deleteselection();"/> <listbox...
Modifying a XUL Interface - Archive of obsolete content
for example, the following will add a button to a xul window: example 1 : source view <script> function addbutton(){ var abox = document.getelementbyid("abox"); var button = document.createelement("button"); button.setattribute("label","a new button"); abox.appendchild(button); } </script> <box id="abox" width="200"> <button label="add" oncommand="addbutton();"/> </box> this example has two parts ...
...you can also retrieve the current label or value using these properties, as in the following example: example 5 : source view <button label="hello" oncommand="alert(this.label);"/> toggling a checkbox checkboxes have a checked property which may be used to check or uncheck the checkbox.
Numeric Controls - Archive of obsolete content
for instance, the following numeric textbox has a range between 1 and 20.
...for instance, the following example steps in multiples of 10.
The Chrome URL - Archive of obsolete content
« previousnext » the following section will describe how to refer to xul documents and other chrome files.
...the following url will refer to the bookmarks window, listed for firefox: chrome://browser/content/bookmarks/bookmarksmanager.xul you can enter chrome urls anywhere normal urls can be used.
Tree Box Objects - Archive of obsolete content
this makes it easy to pass event coordinates directly to these functions, as in the following example of the getcellat() function.
... the following line is used so that the example above will work in all versions.
Updating Commands - Archive of obsolete content
a simple way of doing this is the following: var controller = document.commanddispatcher.getcontrollerforcommand("cmd_paste"); if (controller && controller.iscommandenabled("cmd_paste")){ controller.docommand(command); } the code above first retrieves the controller for the 'cmd_paste' command from the command dispatcher.
... the following example shows the command updaters used in the mozilla browser to update the edit menu commands.
XPCOM Examples - Archive of obsolete content
we can use this as in the following example: example 1 : source <toolbox> <menubar id="windowlist-menubar"> <menu label="window"> <menupopup id="window-menu" datasources="rdf:window-mediator" ref="nc:windowmediatorroot"> <template> <rule> <menuitem uri="rdf:*" label="rdf:http://home.netscape.com/nc-rdf#name"/> </rule> </template> </menupopup> </menu> </menubar> </toolbox> a window menu will be c...
...that means that in order to switch the window focus, we need to do the following: determine the element that the user clicked on.
XUL Template Primer - Bindings - Archive of obsolete content
we'll use a the following data model to illustrate how bindings work.
...resource="#doghouse"/> </rdf:description> </rdf:li> <rdf:li> <rdf:description nc:name="lumpy"/> </rdf:li> </rdf:seq> </nc:friends> </rdf:description> <rdf:description id="home" nc:street="437 hoffman"/> <rdf:description id="doghouse" nc:street="435 hoffman"/> </rdf:rdf> the rdf model that this file creates can be represented with the following graph.
XUL accessibility tool - Archive of obsolete content
the version currently on xulplanet is compatible with the following xul applications: firefox 1.5+ thunderbird 3.0a+ recent sunbird builds recent songbird builds.
... future work the following things have been suggested or are planned for a future version of the tool: new tests: (aaronlev) warning: hardcoded color and pixel sizings (aaronlev) error: duplicate accesskey in a dialog (already have this for menus) (aaronlev) error: form control without accesskey (aaronlev) warning: accesskey as lowercase letter with descender (underlined g,j,y,q,p are hard to read, not recommended) ...
XUL Coding Style Guidelines - Archive of obsolete content
xml, xul, html, and xhtml guidelines the following are considered good coding style for xml/xul documents.
...to prevent them from being localized, you may insert a line of comment following the xml declaration as follows.
browser - Archive of obsolete content
droppedlinkhandler type: function this function is called when links are dropped to the browser element, with the following arguments.
...in addition to the flags allowed for the reloadwithflags method, the following flags are also valid: load_flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect.
button - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } dir type: one of the values below the direction in which the child elements of the element are placed.
...the following values can be used as the dialog type: accept the ok button, which will accept the changes when pressed.
dialog - Archive of obsolete content
the following values can be used in the list: accept: the ok button, which will accept the changes when pressed.
...the following values can be used in the list: accept: the ok button, which will accept the changes when pressed.
label - Archive of obsolete content
ArchiveMozillaXULlabel
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
...ldnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may be used to style the element.
listitem - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } current type: boolean this attribute will be set to true if the listitem is the current item.
...nodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may be used to style the element.
menuitem - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } description type: string descriptive text to appear in addition to the dialog title.
...the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded.
menupopup - Archive of obsolete content
attributes ignorekeys, left, onpopuphidden, onpopuphiding, onpopupshowing, onpopupshown, position, top properties accessibletype, anchornode, popupboxobject, position, state, triggernode methods hidepopup, moveto, openpopup, openpopupatscreen, setconsumerollupevent, showpopup, sizeto examples the following example shows how a menupopup may be attached to a menulist.
... <menulist> <menupopup> <menuitem label="mozilla" value="http://mozilla.org"/> <menuitem label="slashdot" value="http://slashdot.org"/> <menuitem label="sourceforge" value="http://sf.net"/> <menuitem label="freshmeat" value="http://freshmeat.net"/> </menupopup> </menulist> the following example shows how a menupopup can be used as a context menu for an element.
panel - Archive of obsolete content
ArchiveMozillaXULpanel
attributes backdrag, close, consumeoutsideclicks, fade, flip, ignorekeys, label, left, level, noautofocus, noautohide, norestorefocus, onpopuphidden, onpopuphiding, onpopupshowing, onpopupshown, position, titlebar, top, type properties accessibletype, label, popupboxobject, popup, state methods hidepopup, moveto, openpopup, openpopupatscreen, sizeto examples the following example shows how a panel may be attached to a label.
...should be one of the following: autocomplete specify this for a panel that provides a tree for an autocomplete element.
preference - Archive of obsolete content
a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e.
... type type: one of the values below the preference type which should be one of the following values.
<statusbarpanel> - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } image type: uri the uri of the image to appear on the element.
...nodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may be used to style the element.
tab - Archive of obsolete content
ArchiveMozillaXULtab
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
...the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded.
tabbrowser - Archive of obsolete content
the properties of params are following: boolean inbackground boolean replace boolean allowthirdpartyfixup tab targettab number newindex object postdatas number usercontextid note: this is the xul method on <browser> / <tabbrowser>, not the global function in chrome://browser/content/browser.js.
...in addition to the flags allowed for the reloadwithflags method, the following flags are also valid: load_flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect.
toolbar - Archive of obsolete content
the value of this attribute should be a comma-separated list of item ids from the toolbarpalette or, additionally, any of the following strings: "separator", "spring", "spacer".
...for spacers, separators, and flexible spacers the following strings are used instead of ids: "spacer", "separator", "spring".
Application Update - Archive of obsolete content
getting started you will need the following utility scripts from http://lxr.mozilla.org/mozilla/sourc...ate-packaging/ (or local source of xulrunner) common.sh make_full_update.sh you will need mar / mar.exe to build a complete update patch.
... application settings you will need to configure the following settings in your application: branding the update process uses branding information, setup branding for your application as described here: xulrunner tips icons the updater process for linux systems requires updater.png to be in your <application folder>/icons/, see https://bugzilla.mozilla.org/show_bug.cgi?id=706846 preferences // whether or not app updates are enabled pref("app.update.ena...
Building XULRunner with Python - Archive of obsolete content
set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot having created amozilla project directory (e.g.c:\projects\mozilla or/c/projects/mozilla in msys) create the following .mozconfig file.
... using python in xul applications add the following to yourprefs.js during development pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showinconsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); html <script> tags specify that python is used withtype="application/x-python" attribute.
Deploying XULRunner - Archive of obsolete content
the installed files should be arranged in the following directory structure: installdir/ application.ini components/ ...
...copy xulrunner/ to this directory when deploying with xulrunner 2.0 and above do the following: move chrome.manifest to the root directory, and adjust resource paths inside chrome.manifest accordingly with xulrunner 9.0 or 10.0 you may need to copy "mozutils.dll" and/or "mozcrt19.dll" from the xulrunner directory to the root directory.
Getting started with XULRunner - Archive of obsolete content
one way to achieve this is to run the following script everytime you want to install a new version: firefox_version=`grep -po "\d{2}\.\d+" /usr/lib/firefox/platform.ini` arch=`uname -p` xurl=https://ftp.mozilla.org/pub/mozilla.org/xulrunner/releases/$firefox_version/runtimes/xulrunner-$firefox_version.en-us.linux-$arch.tar.bz2 cd /opt sudo sh -c "wget -o- $xurl | tar -xj" sudo ln -s /opt/xulrunner/xulrunner /usr/bin/xulrunner sudo ln -s /opt...
... hint: skip ahead and download the sample application, you can experiment with it while following this tutorial.
What XULRunner Provides - Archive of obsolete content
the following features are either already implemented or planned: gecko features xpcom networking gecko rendering engine dom editing and transaction support (no ui) cryptography xbl (xbl2 planned) xul svg xslt xml extras (xmlhttprequest, domparser, etc.) web services (soap) auto-update support (not yet complete) type ahead find toolbar history implementation (the places implementation in the 1.9 cycle) accessibility support ipc services for communication between gecko-based apps (not yet complete) storage/sqlite interfaces user interface features the following user interface is supplied by xulrunne...
... extension manager file picker (uses native os filepicker as appropriate) find toolbar helper app dialog/ui security ui (maintenance of ssl keychains, etc) embedding apis the following embedding apis are provided by xulrunner: cross-platform embedding (xre_initembedding) javaxpcom embedding gtkmozembed (linux only) activex control (windows only) (not yet complete) obsolete since gecko 7.0 nsview-based-widget (mac os x only) (not yet complete) the "maybe" list the following features have been discussed and may be included if developer time permits and code size is controlled: ldap su...
application/http-index-format specification - Archive of obsolete content
syntax every line in the file must conform to the following generic syntax: number: data where number is at least a three digit number (note that more digits are possible in the future) and data is separated from number by a colon and a space.
... file-type one of the following keywords to represent a special status for a file: file directory symbolic-link sym-file (a symbolic link to a file) sym-directory (a symbolic link to a directory) permissions unix type file permission syntax.
2006-10-27 - Archive of obsolete content
these were the following choices stated: search the filesystem for unneeded files delete or archive them, add a hard disk, move all or part of the concerned filesystem there move that tinderbox to a different machine with more empty disk space on october 23rd: nick responded to gavin and tony's posting.
...the following is his configuration script that he used to build firefox 2 on solaris.
Monitoring plugins - Archive of obsolete content
below are a number of javascript snippets that would be useful to developers trying to use this feature: registration to register for runtime notifications with the observer service you must create a class with an observe method which receives 3 parameters (subject, topic and data) as well as a register method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice (components.interfaces.nsiobserverservice); observerservice.addobserver(this, "experimental-notify-plugin-call", false); observing as discussed above, to specify what you want done when a notification arrives your class must have an observe method, receiving 3 parameters...
... clean up to unregister your class with the observer service - when you no longer want to be listening to runtime notifications - your class must include an unregister method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "experimental-notify-plugin-call"); skeleton observer class below is a skeleton class that you may use to listen to runtime notifications: function pluginobserver() { this.registered = ...
NPEvent - Archive of obsolete content
pedef struct _npevent { uint16 event; uint32 wparam; uint32 lparam; } npevent; mac os typedef eventrecord npevent; type eventrecord = record { what: integer; message: longint; when: longint; where: point; modifiers: integer; end; xwindows typedef xevent npevent; fields npevent on microsoft windows the data structure has the following fields: event one of the following event types: wm_paint wm_lbuttondown wm_lbuttonup wm_lbuttondblclk wm_rbuttondown wm_rbuttonup wm_rbuttondblclk wm_mbuttondown wm_mbuttonup wm_mbuttondblclk wm_mousemove wm_keyup wm_keydown wm_setcursor wm_setfocus wm_killfocus for information about these events, see the microsoft windows developer documentation.
... eventrecord npevent on mac os npevent is defined as an eventrecord data structure, which has the following fields: what integer representing an event type.
NPVariant - Archive of obsolete content
syntax typedef struct _npvariant { npvarianttype type; union { bool boolvalue; int32_t intvalue; double_t doublevalue; npstring stringvalue; npobject *objectvalue; } value; } npvariant; fields the data structure has the following fields: type a member of the npvarianttype enumeration specifying the data type contained in the npvariant.
...ttype_object functions npn_releasevariantvalue() npn_getstringidentifier() npn_getstringidentifiers() npn_getintidentifier() npn_identifierisstring() npn_utf8fromidentifier() npn_intfromidentifier() macros plugin developers are not expected to directly manipulate or access the members of the npvariant instance, instead, the function npn_releasevariantvalue(), and the following macros are provided: npvariant_is_void() evaluates to true if v is of type npvarianttype_void.
NP_Port - Archive of obsolete content
syntax typedef struct np_port { cgrafptr port; /* grafport */ int32 portx; /* position inside the topmost window */ int32 porty; } np_port; fields the data structure has the following fields: port standard mac os port into which the plug-in should draw.
...since the port is shared between the plug-in and other plug-ins and the browser, the plug-in should always do the following: draw only within the area designated by the npwindow.
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
plugin packages should only need to package a small set of files in the following structure in the xpi file: install.rdf plugins/ pluginlib.dll plugintypes.xpt the install.rdf file contains an install manifest that describes the plugin to the user.
...in the xpi you can use the following structure: platform/ linux_x86-gcc3/ plugins/ libplugin.so darwin_ppc-gcc3/ plugins/ libplugin.dylib more specific information can be found in the platform-specific subdirectories documentation.
Introduction to SSL - Archive of obsolete content
this exchange of messages is designed to facilitate the following actions: authenticate the server to the client.
...to ensure that red hat console can control an ssl-enabled server, the server must enable at least one of the following cipher suites for ssl 3.0: rc4 with 128-bit encryption and md5 message authentication rc4 with 40-bit encryption and md5 message authentication rc2 with 40-bit encryption and md5 message authentication no encryption, md5 message authentication only cipher suites with rsa key exchange table 1 lists the cipher suites supported by ssl that use the rsa key-exchange algorithm.
Tamarin Tracing Build Documentation - Archive of obsolete content
tamarin source versions the following instructions are for obtaining and building the tamarin tracing source code.
...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 libraries for the avmplus and garbage collector (mmgc), and create a standalone executable, avmshell, for executing files in the abc file format.
Building a Theme - Archive of obsolete content
next, the contents of the following directories to their respective folders into the folder.
... copy the contents of the following directories to their respective folders.
Theme changes in Firefox 3 - Archive of obsolete content
the rule that's needed to show and hide the go button and other location bar icons is: #urlbar[pageproxystate="invalid"] > #urlbar-icons > :not(#go-button) , #urlbar[pageproxystate="valid"] > #urlbar-icons > #go-button { visibility: collapse; } images to add add the following images: chrome://global/skin/icons/information-16.png used when presenting information notices.
... images to remove the following images were removed: chrome://mozapps/skin/extensions/question.png no longer used.
Theme changes in Firefox 4 - Archive of obsolete content
default values of the iconsize attribute on browser toolbars if the theme doesn't override the value of the iconsize attribute, the following defaults are used: toolbar element id default iconsize value menu bar #toolbar-menubar small navigation bar #nav-bar small or large depending on user preference.
...finally, you need to create a chrome.manifest file with the contents: skin browser classic/1.0 chrome/browser/ skin communicator classic/1.0 chrome/communicator/ skin global classic/1.0 chrome/global/ skin mozapps classic/1.0 chrome/mozapps/ this results in the following structure : /my_theme/chrome/browser/* /my_theme/chrome/communicator/* /my_theme/chrome/global/* /my_theme/chrome/mozapps/* /my_theme/chrome.manifest /my_theme/icon.png /my_theme/install.rdf /my_theme/preview.png note: for more information (and how to package into a jar) consult creating a skin for firefox which still mostly applies.
-ms-hyphenate-limit-chars - Archive of obsolete content
initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete syntax values auto corresponds to a value of 5 2 2, indicating a 5-character word limit, 2 characters required before a hyphenation break, and 2 characters required following a hyphenation break.
... <integer>{1,3} one to three integer values, corresponding to the word limit, the minimum number of characters required before a hyphenation break, and the minimum number of characters required following a hyphenation break, respectively.
-ms-scroll-snap-x - Archive of obsolete content
ap-type: none-ms-scroll-snap-points-x: snapinterval(0px, 100%)applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas each of the properties of the shorthand:-ms-scroll-snap-type: as specified-ms-scroll-snap-points-x: as specifiedanimation typediscrete syntax values the -ms-scroll-snap-x shorthand property is specified as one or both of the following values, in order and separated by spaces.
...the two selectors in the following example have the same effect.
-ms-scroll-snap-y - Archive of obsolete content
ap-type: none-ms-scroll-snap-points-y: snapinterval(0px, 100%)applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas each of the properties of the shorthand:-ms-scroll-snap-type: as specified-ms-scroll-snap-points-y: as specifiedanimation typediscrete syntax values the -ms-scroll-snap-y shorthand property is specified as one or both of the following values, in order and separated by spaces.
...the two selectors in the following example have the same effect.
-ms-scrollbar-arrow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to use -ms-scrollbar-arrow-color and -ms-scrollbar-face-color to display a scroll bar with a blue scroll box and arrows, and a scroll bar with a green scroll box and arrows.
... </div> </body> the following image shows the result: specifications not part of any specification.
::-ms-clear - Archive of obsolete content
such inputs include: <input type="color"> <input type="date"> <input type="datetime"> <input type="datetime-local"> <input type="email"> <input type="month"> <input type="number"> <input type="search"> <input type="tel"> <input type="time"> <input type="url"> <input type="week"> allowable properties only the following css properties can be used in a rule with ::-ms-clear in its selector.
...*/ /* the cross can be hidden by setting the display attribute as "none" */ } result the following screenshot shows what the feature will look like: specifications not part of any specification.
E4X for templating - Archive of obsolete content
n separate file templates (to be eval()d at a later time, taking into account security considerations, such as escaping with the above), e4x content using such functions can also be easily serialized inline (and then perhaps converted to the dom) as needed: var list = <>{_if(elems.length(), function () <> <markup/> <markup/> </>)}</>.toxmlstring(); iterating functions such as the following foreach (which can work with arrays, objects, or e4x objects) are quite convenient in iterating over complex structures such as e4x would not normally allow.
...licit additional params; otherwise define with more than one param (see below) ++it; } } else { for (k in arr) { if (it < min) { ++it; continue; } if (it > max) { break; } ret+=h(k, arr[k], it, lev); ++it; } } return ret; } the following real case example iterates over an array of the lines in an e4x child element to produce an xmllist of multiple vbox's representing each line: <vbox> {foreach(e(someel.somechild[0]).split('\n'), function (line) <description>{line}</description> )} </vbox> the following example shows iteration over an e4x object itself: {foreach(elems, function (k, elem, iter) <> <row>{k}: {elem}</row> ...
ArrayBuffer.transfer() - Archive of obsolete content
ray(buf1)[0] = 42; var buf2 = arraybuffer.transfer(buf1, 80); buf1.bytelength; // 0 but if you use the polyfill then the value is still 40 buf2.bytelength; // 80 new int32array(buf2)[0]; // 42 var buf3 = arraybuffer.transfer(buf2, 0); buf2.bytelength; // 0 but if you use the polyfill then the value is still 80 buf3.bytelength; // 0 polyfill you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of transfer() in browsers that do not natively support it.
... this is not the exact equivalent of this api because browsers that natively support it are be able to internally use the c++ function realloc() which extends the length of the memory and only copies it to a new location as-needed as opposed to the following pollyfill which always copies the whole thing to a new space of memory, but this function transfers data from one arraybuffer to another arraybuffer.
Array comprehensions - Archive of obsolete content
the following comprehension takes an array of numbers and creates a new array of the double of each of those numbers.
... var numbers = [1, 2, 3, 4]; var doubled = [for (i of numbers) i * 2]; console.log(doubled); // logs 2,4,6,8 this is equivalent to the following map() operation: var doubled = numbers.map(i => i * 2); comprehensions can also be used to select items that match a particular expression.
ActiveXObject - Archive of obsolete content
in the following example, you access properties and methods of the new object using the object variable excelsheet and other excel objects, including the application object and the activesheet.cells collection.
...excelsheet.application.quit(); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
Debug.debuggerEnabled - Archive of obsolete content
syntax var dbgenabled = debug.debuggerenabled; requirements supported in the following document modes: internet explorer 10 standards and internet explorer 11 standards.
... not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards.
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
example the following code provides an example of tracing an asynchronous call for a windows 8.x store app.
... not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards.
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
example the following code provides an example of tracing an asynchronous call for a windows 8.x store app.
... not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards.
Enumerator.atEnd - Archive of obsolete content
example in following code, the atend method is used to determine if the end of a list of drives has been reached: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; ...
...sready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
Enumerator.moveFirst - Archive of obsolete content
example in following example, the movefirst method is used to evaluate members of the drivescollection from the beginning of the list: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.pat...
...sready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
Enumerator.moveNext - Archive of obsolete content
example in following example, the movenext method is used to move to the next drive in the drives collection: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; ...
...sready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
Enumerator - Archive of obsolete content
example the following code shows the usage of the enumerator object: var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); document.write(fso.drives); var e = new enumerator(fso.drives); var drivestring = ""; e.movefirst(); while (e.atend() == false) { var drv = e.item(); drivestring += drv.path + " - "; if (drv.isready){ var freegb = drv.freespace /...
... requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
Error.description - Archive of obsolete content
example the following example illustrates the use of the description property.
... try { // cause an error: x = y } catch(e) { // prints "[object error]": document.write(e) document.write (" "); // prints 5009: document.write((e.number & 0xffff)) document.write (" "); // prints "'y' is undefined": document.write(e.description); document.write (" "); // prints "'y' is undefined": document.write(e.message) } requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
Error.number - Archive of obsolete content
example the following example causes an exception to be thrown and displays the error code that is derived from the error number.
... error code: 5009 facility code: 10 error message: 'y' is undefined requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
GetObject - Archive of obsolete content
you could use the following code to activate a layer within a drawing called schema.cad: var layerobject = getobject("c:\\cad\\schema.cad!layer3"); if you do not specify the object's class, automation determines which application to start and which object to activate, based on the file name you provide.
... requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, and internet explorer 8 standards.
ScriptEngineMinorVersion - Archive of obsolete content
example the following example illustrates the use of the scriptengineminorversion function.
... if (window.scriptengineminorversion) { console.log(window.scriptengineminorversion()); } //output: <current minor version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
VBArray.dimensions - Archive of obsolete content
the following example consists of three parts.
...a) { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return(s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray.getItem - Archive of obsolete content
example the following example consists of three parts.
...<script type="text/javascript"> <!-- function getitemtest(vbarray) { var i, j; var a = new vbarray(vbarray); for (i = 0; i <= 2; i++) { for (j =0; j <= 2; j++) { document.writeln(a.getitem(i, j)); } } } --> </script> </head> <body> <script type="text/javascript"> <!-- getitemtest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray.lbound - Archive of obsolete content
example the following example consists of three parts.
...){ var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray.toArray - Archive of obsolete content
example the following example consists of three parts.
...vbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray) { var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray.ubound - Archive of obsolete content
example the following example consists of three parts.
... { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray - Archive of obsolete content
example the following example consists of three parts.
... requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
New in JavaScript 1.7 - Archive of obsolete content
the following is a changelog for javascript 1.7.
... new features in javascript 1.7 the following features added with javascript 1.7 were not part of an ecma-262 standard at the time.
Object.prototype.watch() - Archive of obsolete content
examples using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval, newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); return newval; }); o.p = 2; o.p = 3; delete o.p; o.p = 4; o.unwatch('p'); o.p = 5; this script displays the following: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from undefined to 4 using watch() to validate an object's properties you can use watch to test any assignment to an object's properties.
...eerror('invalid name for ' + this); } if (id === 'age' && (newval < 0 || newval > 200)) { throw new rangeerror('invalid age for ' + this); } return newval; } } const will = new person('will', 29); console.log(will); // will, 29 try { will.name = ''; } catch (e) { console.log(e); } try { will.age = -4; } catch (e) { console.log(e); } this script displays the following: will, 29 rangeerror: invalid name for will, 29 rangeerror: invalid age for will, 29 specifications not part of any standard.
JSObject - Archive of obsolete content
method summary the netscape.javascript.jsobject class has the following methods: call calls a javascript method.
... the netscape.javascript.jsobject class has the following static method: getwindow gets a jsobject for the window containing the given applet.
JavaArray - Archive of obsolete content
in addition, the tostring method is inherited from the object object and returns the following value: [object javaarray] you must specify a class object, such as one returned by java.lang.object.forname, for the componenttype parameter of newinstance when you use this method to create an array.
... var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); example: instantiating a javaarray in javascript with the newinstance method in javascript 1.4, you can use a javaclass object as the argument for the newinstance method which creates the array, as shown in the following code: var dogs = java.lang.reflect.array.newinstance(java.lang.string, 5); in javascript 1.1, use a class object returned by java.lang.class.forname as the argument for the newinstance method, as shown in the following code: var datatype = java.lang.class.forname("java.lang.string"); var dogs = java.lang.reflect.array.newinstance(datatype, 5); ...
JavaClass - Archive of obsolete content
examples example: using javaclass in the following example, x is a javaclass object referring to java.awt.font.
... example in the following example, the javaclass object java.lang.string is passed as an argument to the newinstance method which creates an array: var cars = java.lang.reflect.array.newinstance(java.lang.string, 15); see also javaarray, javaobject, javapackage, packages ...
JavaObject - Archive of obsolete content
examples example: instantiating a java object in javascript the following code creates the javaobject thestring, which is an instance of the class java.lang.string: var thestring = new packages.java.lang.string("hello, world"); because the string class is in the java package, you can also use the java synonym and omit the packages keyword when you instantiate the class: var thestring = new java.lang.string("hello, world"); example: accessing methods of a java obj...
...the following example uses the startswith method to check whether thestring begins with "hello".
Requests For Enhancement - Archive of obsolete content
ArchiveWebXFormsRFE
if you have an idea that might improve mozilla's xforms implementation then you should choose one of the following rfe categories and put your request there.
...this section could be of particular interest to people using custom controls in xul documents for the following reasons: xul, in many cases, is much better suited for application development than xhtml.
XForms Input Element - Archive of obsolete content
representations the xforms input element can be represented by the following widgets for the spcified data types (or types derived from these data types): text field - the default widget when no type is specified or the data is of type xsd:string (xhtml/xul) checkbox - used for xsd:boolean instance data.
... calendar a form author may notice a xforms input element represented by a calendar widget in the mozilla xforms processor if the control meets the following criteria (xhtml/xul).
XForms Output Element - Archive of obsolete content
representations the xforms output element can be represented by the following widgets for the specified data types (or types derived from these data types): text - default representation for instance data of most types, especially static text (xhtml/xul).
... analogous widgets are <xhtml:span/> and <xul:description/> calendar a form author may notice a xforms output element represented by a calendar widget in the mozilla xforms processor if the control meets the following criteria (xhtml/xul).
The Business Benefits of Web Standards - Archive of obsolete content
feed content such as rss and atom simply will not work without being implemented by following the requisite standard.
... following standards-compliance in requirements documents is a very effective way to ensure measurable quality of the final product, the w3c being an impartial judge.
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
how to call plugin native methods the following html code will do the job:</p> this should be changed, we shouldn't advocate embed <embed type="application/plugin-mimetype"> <script language="javascript"> var embed = document.embeds[0]; embed.nativemethod(); </script> how to build and install having the built mozilla tree is probably not necessary, but building the plugin with a scriptable instance interface will require mozilla headers and t...
...ns_impl_isupports2(nsscriptablepeer, nsitestplugin, nsiclassinfo) // the following method will be callable from javascript ns_imethodimp nsscriptablepeer::nativemethod() { return ns_ok; } example 3.
Anatomy of a video game - Game development
the browser's main thread thus tries to look like the following: start a new frame (while the previous frame is handled by the display).
... a separate update and draw method could look like the following example.
Building up a basic demo with PlayCanvas editor - Game development
add the following line inside this function, to rotate the cube on every frame: this.entity.rotate(dt*10, dt*20, dt*30); in the line above this.entity refers to the object to which the script will be attached (the box); using the dt variable, which contains the delta time passed since the previous frame, we can rotate the box by a different amount around all three axes.
... next, add the following line to the initialize() function: this.timer = 0; to move the cone up and down we will use the setposition() method — add the code below to the update() function: this.timer += dt; this.entity.setposition(2, math.sin(this.timer*2), 0); the position of the cone will be animated on each frame by being passed the math.sin() value of the timer at each point in time — we have doubled the this...
Implementing game control mechanisms - Game development
in the following articles we will show how to implement various different control mechanisms for captain rogers to support different platforms — from touch on mobile, through keyboard/mouse/gamepad on desktop, to more unconventional ones like tv remote, shouting to or waving your hand in front of the laptop, or squeezing bananas.
... the articles javascript is the perfect choice for mobile gaming because of html5 being truly multiplatform; all of the following articles focus on the apis provided for interfacing with different control mechanisms: mobile touch controls — the first article will kick off with touch, as the mobile first approach is very popular.
Square tilemaps implementation: Static maps - Game development
in this case, we need to map the column and row to an array index: var index = row * map.cols + column; wrapping up, an example of a tilemap object could look like the following.
...this snippets assumes the following definitions: context: a 2d canvas context.
Create the Canvas and draw on it - Game development
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: 0; } canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="mycanvas" width="480" height="320"></canvas> <script> // javascript code goes here </script> </body> </html> we have a charset...
...add the following below your opening <script> tag.
Game over - Game development
first, replace where you initially called setinterval() setinterval(draw, 10); with: var interval = setinterval(draw, 10); then replace the second if statement with the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } letting the paddle hit the ball the last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back int...
...update the last bit of code you modified again, to the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { if(x > paddlex && x < paddlex + paddlewidth) { dy = -dy; } else { alert("game over"); document.location.reload(); clearinterval(interval); } } if the ball hits the bottom edge of the canvas we need to check whether it hits the paddle .
Mouse controls - Game development
add the following line in the same place as the other event listeners, just below the keyup event: document.addeventlistener("mousemove", mousemovehandler, false); anchoring the paddle movement to the mouse movement we can update the paddle position based on the pointer coordinates — the following handler function will do exactly that.
... add the following function to your code, below the previous line you added: function mousemovehandler(e) { var relativex = e.clientx - canvas.offsetleft; if(relativex > 0 && relativex < canvas.width) { paddlex = relativex - paddlewidth/2; } } in this function we first work out a relativex value, which is equal to the horizontal mouse position in the viewport (e.clientx) minus the distance between the left edge of the canvas and left edge of the viewport (canvas.offsetleft) — effectively this is equal to the distance between the canvas left edge and the mouse pointer.
Buttons - Game development
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.
...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 function that will be executed when the button is pressed a reference to this to specify the execution context the frames that will be used for the over, out and down events.
Physics - Game development
add the following line at the bottom of the create() function: game.physics.enable(ball, phaser.physics.arcade); next, if we want to move our ball on the screen, we can set velocity on its body.
... add the following line, again at the bottom of create(): ball.body.velocity.set(150, 150); removing our previous update instructions remember to remove our old method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine.
Visual-js game engine - Game development
3) please read the following terms and conditions before using this application: disclaimer of warranty 'visual js' is provided "as-is" and without warranty of any kind, express, implied or otherwise, including without limitation, any warranty of merchantability or fitness for a particular purpose.
...ted intro build.js ) webgl2 based on : copyright (c) 2014 tappali ekanathan keestu (keestu@gmail.com) gnu general public license obj loader : https://github.com/frenchtoast747/webgl-obj-loader textures download from http://textures.com more texture downloads http://www.textures4photoshop.com/ female body v3.blend this file has been released by andrescuccaro under the following license: creative commons attribution 3.0 about gui for windows (canvas2d part only) : windows gui application version 1.0 (using visual-js 0.9 lib) important : you will need net 4.5.2 minimum also redistribution pack for c++ how to start project ?
CORS-safelisted request header - MDN Web Docs Glossary: Definitions of Web-related terms
a cors-safelisted request header is one of the following http headers: accept, accept-language, content-language, content-type.
... you can safelist more headers using the access-control-allow-headers header and also list the above headers there to circumvent the following additional restrictions: additional restrictions cors-safelisted headers must also fulfill the following requirements in order to be a cors-safelisted request header: for accept-language and content-language: can only have values consisting of 0-9, a-z, a-z, space or *,-.;=.
Function - MDN Web Docs Glossary: Definitions of Web-related terms
only function expressions can be anonymous, function declarations must have a name: // when used as a function expression (function () {}); // or using the ecmascript 2015 arrow notation () => {}; the following terms are not used in the ecmascript language specification, they're jargon used to refer to different types of functions.
....wikipedia.org/wiki/immediately-invoked_function_expression) /* ​function foo() { console.log('hello foo'); }(); */ // function expressions, named or anonymous, can be called immediately (function foo() { console.log("hello foo"); }()); (function food() { console.log("hello food"); })(); (() => console.log('hello world'))(); if you'd like to know more about iifes, check out the following page on wikipedia : immediately invoked function expression learn more technical reference functions arrow functions ...
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
in the following example there is a grid with three column tracks and two row tracks.
...in the following example the item is positioned from column line 1 to column line 3, and from row line 1 to row line 3.
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
firefox does not support it natively, but the following function aims to allow its use with documents passed into it.
... code sample the following code aims to let <xi:include> and <xi:fallback> tags (the two elements in the language) with all of the attributes of <xi:include> be included in an xml document so as to be resolvable into a single xml document.
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
not all http responses can be cached, these are the following constraints for an http response to be cached: the method used in the request is itself cacheable, that is either a get or a head method.
...the following status code are cacheable: 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501.
Accessibility - Learn web development
the following video provides a nice introduction to it: looking to become a front-end web developer?
... wai-aria basics following on from the previous article, sometimes making complex ui controls that involve unsemantic html and dynamic javascript-updated content can be difficult.
A cool-looking box - Learn web development
styling the box we'd like you to style the provided <p>, giving it the following: a reasonable width for a large button, say around 200 pixels.
... example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
Backgrounds and borders - Learn web development
try the following.
...this is controlled using the background-attachment property, which can take the following values: scroll: it causes the element's background to scroll when the page is scrolled.
Cascade and inheritance - Learn web development
the following table shows a few isolated examples to get you in the mood.
... to summarize conflicting declarations will be applied in the following order, with later ones overriding earlier ones: declarations in user agent style sheets (e.g.
Debugging CSS - Learn web development
the following video provides some useful tips on debugging css using the firefox devtools: editing values in addition to turning properties on and off, you can edit their values.
...the following steps should help.
Fundamental CSS comprehension - Learn web development
the following sections describe what you need to do.
... example the following screenshot shows an example of what the finished design should look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
Organizing your CSS - Learn web development
need both the media and comment classes applied: <div class="media comment"> <img /> <div class="content"></div> </div> the list-item would have media and list-item applied: <ul> <li class="media list-item"> <img /> <div class="content"></div> </li> </ul> the work that nicole sullivan did in describing this approach and promoting it means that even people who are not strictly following an oocss approach today will generally be reusing css in this way — it has entered our understanding as a good way to approach things in general.
... $base-color: #c6538c; .alert { border: 1px solid $base-color; } once compiled to css, you would end up with the following css in the final stylesheet.
Type, class, and ID selectors - Learn web development
in the following example we have used the universal selector to remove the margins on all elements.
...you can see both of these uses in the following example: warning: using the same id multiple times in a document may appear to work for styling purposes, but don't do this.
CSS selectors - Learn web development
in the following example, the invalid class selector rule will be ignored, whereas the h1 would still be styled.
...the following for example selects paragraphs that are direct children of <article> elements using the child combinator (>): article > p { } next steps you can take a look at the reference table of selectors below for direct links to the various types of selectors in this learn section or on mdn in general, or continue on to start your journey by finding out about type, class, and id selectors.
CSS building blocks - Learn web development
guides this module contains the following articles, which cover the most essential parts of the css language.
...the following assessments will test your understanding of the css covered in the guides above.
What is CSS? - Learn web development
for more on browser/default styles, check out the following video: what is css for?
...for example "i want the main heading on my page to be shown as large red text." the following code shows a very simple css rule that would achieve the styling described above: h1 { color: red; font-size: 5em; } the rule opens with a selector .
Styling text - Learn web development
guides this module contains the following articles, which will teach you all of the essentials behind styling html text content.
... assessments the following assessments will test your understanding of the text styling techniques covered in the guides above.
Learn to style HTML using CSS - Learn web development
modules this topic contains the following modules, in a suggested order for working through them.
...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: ...
How do you host your website on Google App Engine? - Learn web development
for this tutorial, the following values are used: project name: gae sample site project id: gaesamplesite click the create button to create your project.
... run the following in the command line to select your project: gcloud config set project gaesamplesite then run the following command to go to your app's directory: cd sample-app you are now ready to deploy your application, i.e.
What are hyperlinks? - Learn web development
every time search engines crawl a webpage, they index the website by following the links available on the webpage.
... we know the following about how search engines determine a site's rank: a link's visible text influences which search queries will find a given url.
What is a URL? - Learn web development
let's see the most important parts using the following url: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#somewhereinthedocument http is the protocol.
... examples of relative urls to better understand the following examples, let's assume that the urls are called from within the document located at the following url: https://developer.mozilla.org/docs/learn sub-resources skills/infrastructure/understanding_urls because that url does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource.
How to structure a web form - Learn web development
apply the css to the html by adding the following line inside the html <head>: <link href="payment-form.css" rel="stylesheet"> next, create your form by adding the outer <form> element: <form> </form> inside the <form> tags, add a heading and paragraph to inform users how required fields are marked: <h1>payment form</h1> <p>required fields are followed by <strong><abbr title="required">*</abbr></strong>.</p> next we'll add a larg...
... enter the following below the previous section: <section> <h2>payment information</h2> <p> <label for="card"> <span>card type:</span> </label> <select id="card" name="usercard"> <option value="visa">visa</option> <option value="mc">mastercard</option> <option value="amex">american express</option> </select> </p> <p> <label for="number"> ...
Other form controls - Learn web development
the following screenshots show default, focused, and disabled <textarea> elements in firefox 71 and safari 13 on macos, and edge 18, yandex 14, firefox 71 and chrome 79 on windows 10.
... the following screenshot shows the datalist fallback as rendered in safari 6: if you use this fallback, ensure the data for both the <input> and the <select> are collected server-side.
Sending form data - Learn web development
consider the following form: <form action="http://www.foo.com" method="get"> <div> <label for="say">what greeting do you want to say?</label> <input name="say" id="say" value="hi"> </div> <div> <label for="to">who do you want to say it to?</label> <input name="to" id="to" value="mom"> </div> <div> <button>send my greetings</button> </div> </form> since the get method has been used, you...
...assuming you've used the post method, the following example just takes the data and displays it to the user.
The web and web standards - Learn web development
as a simple example, the following code would turn our html paragraph red: p { color: red; } in the house analogy, css is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice.
...the following simple javascript will store a reference to our paragraph in memory and change the text inside it: let pelem = document.queryselector('p'); pelem.textcontent = 'we changed the text!'; in the house analogy, javascript is like the cooker, tv, microwave, or hairdryer — the things that give your house useful functionality tooling once you've learned the "raw" technologies that can be used to build web pages (such as html, css, and javascript), you'll soon start to come across various tools that can be used to make your work easier or more efficient.
Debugging HTML - Learn web development
for example, the following shows an error reported when trying to compile a simple program written in the rust language.
... you will know when all your errors are fixed when you see the following banner in your output: summary so there we have it, an introduction to debugging html, which should give you some useful skills to count on when you start to debug css, javascript, and other types of code later on in your career.
Marking up a letter - Learn web development
in general, the letter should be marked up as an organization of headings and paragraphs, with the following exception.
... example the following screenshot shows an example of what the letter might look like after being marked up.
What’s in the head? Metadata in HTML - Learn web development
a favicon can be added to your page by: saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ico format will ensure it works as far back as internet explorer 6.) adding the following line into your html's <head> block to reference it: <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> here is an example of a favicon in a bookmarks panel: there are lots of other icon types to consider these days as well.
... 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.
Introduction to HTML - Learn web development
guides this module contains the following articles, which will take you through all the basic theory of html and provide ample opportunity for you to test out some skills.
... assessments the following assessments will test your understanding of the html basics covered in the guides above.
Images in HTML - Learn web development
our above code would give us the following result: note: elements like <img> and <video> are sometimes referred to as replaced elements.
...you are provided with a basic <img> tag; we'd like you to embed the image located at the following url: https://udn.realityripple.com/samples/ec/5a13bd14f6.jpg earlier we said to never hotlink to images on other servers, but this is just for learning purposes, so we'll let you off this one time.
Mozilla splash page - Learn web development
the following subsections detail what you need to do: preparing images using your favourite image editor, create 400px wide and 120px wide versions of: firefox_logo-only_rgb.png firefox-addons.jpg mozilla-dinosaur-head.png call them something sensible, e.g.
... example the following screenshots show what the splash page should look like after being correctly marked up, on a wide and narrow screen display.
Video and audio content - Learn web development
take a look at the following updated example (try it live here, also): <video controls> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html5 video.
...here is a <a href="viper.mp3">link to the audio</a> instead.</p> </audio> this produces something like the following in a browser: note: you can run the audio demo live on github (also see the audio player source code.) this takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio.
Multimedia and Embedding - Learn web development
guides this module contains the following articles which will take you through all the fundamentals of embedding multimedia on webpages.
... assessments the following assessments will test your understanding of the html basics covered in the guides above: mozilla splash page in this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about mozilla!
Assessment: Structuring planet data - Learn web development
an html data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below.
... the finished table should look like this: you can also see the example live here (no looking at the source code — don't cheat!) steps to complete the following steps describe what you need to do to complete the table example.
Making asynchronous programming easier with async and await - Learn web development
try typing the following lines into your browser's js console: function hello() { return "hello" }; hello(); the function returns "hello" — nothing special, right?
...try the following: async function hello() { return "hello" }; hello(); ah.
Image gallery - Learn web development
to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do.
... the following lines provide a basis for achieving the changes stipulated in points 2 and 3 above.
Introduction to web APIs - Learn web development
if you look at our simple web audio example (see it live also), you'll first see the following html: <audio src="outfoxing.mp3"></audio> <button class="paused">play</button> <br> <input type="range" min="0" max="1" step="0.01" value="1" class="volume"> we, first of all, include an <audio> element with which we embed an mp3 into the page.
... the following code provides a simple example of how this would be used: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new xmlhttprequest(); request.open('get', requesturl); request.responsetype = 'json'; request.send(); request.onload = function() { const superheroes = request.response; populateheader(superheroes); showheroes(superheroes); }...
Test your skills: Math - Learn web development
so, try updating the live code below to recreate the finished example, following these steps: create four variables that contain numbers.
... try updating the live code below to recreate the finished example, following these steps: write a calculation that multiplies result and result2 together and assigns the result back to result.
JavaScript First Steps - Learn web development
you are advised to work through the following modules before starting on javascript: getting started with the web (which includes a really basic javascript introduction).
... assessments the following assessment will test your understanding of the javascript basics covered in the guides above.
Solve common problems in your JavaScript code - Learn web development
the following links point to solutions to common problems you may encounter when writing javascript.
...for example: function myfunction() { alert('this is my function.'); }; this code won't do anything unless you call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e.
JavaScript — Dynamic client-side scripting - Learn web development
start by working through the following modules: getting started with the web introduction to html introduction to css having previous experience with other programming languages might also help.
... after getting familiar with the basics of javascript, you should be in a position to learn about more advanced topics, for example: javascript in depth, as taught in our javascript guide web apis modules this topic contains the following modules, in a suggested order for working through them.
Aprender y obtener ayuda - Learn web development
the following have different scopes, but are all realistic and achievable: i want to become a professional web developer in two years' time.
... the following are not quite as reasonable: i want to go from a complete beginner to becoming a senior web developer in three months.
Web performance - Learn web development
guides this topic contains the following guides.
... the following is a suggested order for working through them; you should definitely start with the first one.
Server-side web frameworks - Learn web development
the following sections illustrate some points using code fragments taken from real web frameworks.
...en"> <body> {% if youngest_teams %} <ul> {% for team in youngest_teams %} <li>{{ team.team_name }}</li> {% endfor %} </ul> {% else %} <p>no teams are available.</p> {% endif %} </body> </html> how to select a web framework numerous web frameworks exist for almost every programming language you might want to use (we list a few of the more popular frameworks in the following section).
Introduction to client-side frameworks - Learn web development
there are many frameworks out there, but currently the "big four" are considered to be the following.
... by contrast, the following block of code illustrates the way you might use vue to describe our list of tasks: <ul> <li v-for="task in tasks" v-bind:key="task.id"> <span>{{task.name}}</span> <button type="button">delete</button> </li> </ul> that's it.
Framework main features - Learn web development
the following shows a simple jsx example: const subject = "world"; const header = ( <header> <h1>hello, {subject}!</h1> </header> ); this expression represents an html <header> element with a <h1> element inside.
...to render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component): <authorcredit src="./assets/zelda.png" alt="portrait of zelda schiff" byline="zelda schiff is editor-in-chief of the library times." /> this will ultimately render the following <figure> element in the browser, with its structure as defined in the authorcredit component, and its content as defined in the props included on the authorcredit component call: <figure> <img src="assets/zelda.png" alt="portrait of zelda schiff" > <figcaption> zelda schiff is editor-in-chief of the library times.
Adding a new todo form: Vue events, methods, and models - Learn web development
go back to app.vue and add the following import statement just below the previous one, inside your <script> element: import todoform from './components/todoform'; you also need to register the new component in your app component — update the components property of the component object so that it looks like this: components: { todoitem, todoform } finally for this section, render your todoform component inside you...
... replace the console.log() in the onsubmit() method with the following: this.$emit("todo-added"); next, go back to app.vue and add a methods property to your component object containing an addtodo() method, as shown below.
Styling Vue components with CSS - Learn web development
add the following contents to the reset.css file: /*reset.css*/ /* resets */ *, *::before, *::after { box-sizing: border-box; } *:focus { outline: 3px dashed #228bec; } html { font: 62.5% / 1.15 sans-serif; } h1, h2 { margin-bottom: 0; } ul { list-style: none; padding: 0; } button { border: none; margin: 0; padding: 0; width: auto; overflow: visible; background: transparent; color: inher...
... to use the scoped modifier, create a <style> element inside todoitem.vue, at the bottom of the file, and give it a scoped attribute: <style scoped> </style> next, copy the following css into the newly created <style> element: .custom-checkbox > .checkbox-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 400; font-size: 16px; font-size: 1rem; line-height: 1.25; color: #0b0c0c; display: block; margin-bottom: 5px; } .custom-checkbox > .checkbox { font-family: arial, sans-serif; ...
Client-side tooling overview - Learn web development
from a high-level perspective, you can put client-side tools into the following three broad categories of problems to solve: safety net — tools that are useful during your code development.
... you’ll probably need a combination of the following things: experienced teachers, mentors, fellow students, or colleagues that have some experience, have solved such problems before, and can give advice.
Embedding API for Accessibility
be aware that in debug builds, this can cause a great number of assertions (bug 71598) to use prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_true /* or pr_false */); prefs->setintpref("int.pref.name", newvalue); prefs->setcharpref("string.pref.name", newcharstarvalue); to manually add a pref to your settings, add a line like the following to your prefs.js: user_pref("accessibility.br...
...owsewithcaret", true); accessibility prefs reference the following is a description of what accessibility prefs give us (or will give us), for accessibility: functionality implementation works as of images setintpref("network.image.imagebehavior", behavior); /* behavior: 0=accept, 1=accept images from originating server only, 2=no images */ moz 0.8 cookies setintpref("network.cookie.cookiebehavior", behavior); /* behavior: 0=accept, 1=accept cookies from originating server only, 2=no cookies */ setboolpref("network.cookie.warnaboutcookies", boolwarn); ...
Mozilla’s UAAG evaluation report
(p1) p the following line can be added to a user's prefs.js file to control blinking: user_pref("browser.blink_allowed", false); bug 89144 has been filed to expose this pref in the ui.
...(p1) vg provides a focus outline box highlights follow graphical rendering conventions for windows does not highlight selected images we do not have the ability to show a border around the text selection we have the following focus appearance prefs that are not exposed in the ui, but can be manually inserted in the user's prefs.js file: setboolpref("browser.display.use_focus_colors", usefocuscolors); /* true or false */ setcharpref("browser.display.focus_background_color", colorstring); /* for example #ffeedd or the name of a color */ setcharpref("browser.display.focus_text_color", colorstring); setcha...
Adding a new event
each event class should implement following methods manually.
...if all information of the event is stored by its internal event, c++ event handlers can access them with following code: ns_imethodimp aneventlistener::handleevent(nsidomevent* aevent) { internalfooevent* internalevent = aevent->getinternalnsevent()->asfooevent(); if (ns_warn_if(!internalevent)) { return ns_error_unexpected; } dosomethingwith(internalevent->mbar); aevent->preventdefault(); return ns_ok; } implement dom event class generate dom event implementation if it's possible if ...
What to do and what not to do in Bugzilla
when verifying a bug, you should remember the following: verifying duplicates is the easiest task, so start with that.
...when performing bug reassignments, keep the following things in mind: always remember to check the reassign to default owner and qa contact radio button under the comment textbox.
Creating MozSearch plugins
the following xml is the bundled firefox 2 search plugin for searching using yahoo!: <searchplugin xmlns="http://www.mozilla.org/2006/browser/search/"> <shortname>yahoo</shortname> <description>yahoo search</description> <inputencoding>utf-8</inputencoding> <image width="16" height="16">data:image/x-icon;base64,r0lgodlheaaqajecap8aaaaaap///waaach5baeaaaialaaaaaaqabaaaaipli+py+0nogquybdened2khkffwuamezmpzsfmai...
...firefox will use the above search engine description to construct the following search url: http://search.yahoo.com/search?p=mozilla&ei=utf-8&fr=moz2 if the user clicks the magnifying glass icon in the search bar, or chooses the web search option in the tools menu when the search bar isn't visible, the browser will take them to http://search.yahoo.com/, the value of the <searchform> element.
Creating reftest-based unit tests
step 3 create a file named foo.html with the following: <html><head><title>reftest0001</title> <body><strong>hello!</strong></body> </html> step 4 create a file named bar.html with the following: <html><head><title>reftest0001</title> <body><b>hello!</b></body> </html> step 5 create a file named reftest.list with the following: == foo.html bar.html you are now ready to run the test (but first you must go back to the root of firefo...
... your second and third reftest for these tests create the following files: spaces1.html: <html><head><title>spaces1</title></head> <body> x x </body></html> spaces2.html: <html><head><title>spaces2</title></head> <body> x&nbsp;x </body></html> spaces3.html: <html><head><title>spaces3</title></head> <body> x&nbsp;&nbsp;x </body></html> spaces4.html: <html><head><title>spaces4</title></head> <body> x x </body></html> reftests.txt: == spaces1.html spa...
Debugging JavaScript
go to about:config and set the following two prefs: devtools.chrome.enabled: true devtools.debugger.remote-enabled: true after you restart the browser, you can access the browser debugger through tools > web developer > browser toolbox.
... under microsoft windows you additionally need to start firefox via the following command to have a native console : firefox.exe -console using normal javascript object inspection, you can write a function that dumps a whole object, similar to this ddumpobject().
Building Firefox with Debug Symbols
use the following mozconfig settings to do a build with symbols: building firefox with symbols there is a single configure option to enable building with symbols on all platforms.
... breakpad symbol files after the build is complete, run the following command to generate an archive of breakpad symbol files: mach buildsymbols the tinderbox uses an additional uploadsymbols target to upload symbols to a socorro server.
Old Thunderbird build
so firstly complete the instructions for your os and then continue following these build instructions.
... build configuration to build thunderbird, you need to add a file named mozconfig to the root directory of the comm-central checkout that contains the following line: ac_add_options --enable-application=mail you can create a file with this line by doing this: cd comm-central echo 'ac_add_options --enable-application=mail' > mozconfig if you omit this line, the build system will build firefox instead.
Simple SeaMonkey build
install all necessary build deps sudo aptitude install zip mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libxt-dev libiw-dev libidl-dev mesa-common-dev autoconf2.13 yasm libgtk2.0-dev libdbus-1-dev libdbus-glib-1-dev python-dev libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libpulse-dev ubuntu linux # for ubuntu 12.04 lts (precise pangolin), replace the following line with: sudo apt-get build-dep thunderbird sudo apt-get build-dep seamonkey sudo apt-get install zip unzip mercurial g++ make autoconf2.13 yasm libgtk2.0-dev libglib2.0-dev libdbus-1-dev libdbus-glib-1-dev libasound2-dev libcurl4-openssl-dev libnotify-dev libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libiw-dev libxt-dev mesa-common-dev libpulse-dev fedora linux centos ...
... rhel: sudo yum groupinstall 'development tools' 'development libraries' 'gnome software development' sudo yum install mercurial autoconf213 glibc-static libstdc++-static yasm wireless-tools-devel mesa-libgl-devel alsa-lib-devel libxt-devel gstreamer-devel gstreamer-plugins-base-devel pulseaudio-libs-devel # 'development tools' is defunct in fedora 19 and above use the following sudo yum groupinstall 'c development tools and libraries' sudo yum group mark install "x software development" mac: install xcode tools.
Contributing to the Mozilla code base
if you're having any trouble following this documentation, or hit a barrier you can't get around, please contact mike hoye at mhoye@mozilla.com.
... when you commit your code, please use the following format for your commit message: `bug number - what your patch does; r?reviewer` for example, a commit message may look like `bug 1234567 - remove reflow by caching element size.
Frame script environment
the frame script's global is a contentframemessagemanager, giving it the following environment: content the dom window of the content loaded in the browser.
... events besides the regular dom events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload fires when the frame script environment is shut down, i.e.
Frame script environment
the frame script's global is a contentframemessagemanager, giving it the following environment: content the dom window of the content loaded in the browser may be null (see below) docshell the nsidocshell associated with the browser.
... events besides the regular dom events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload bubbles no fires when the frame script environment is shut down, i.e.
Tracking Protection
if tracking cookies were present, you would be able to view the list by clicking on "blocking tracking cookies" in the above image to view the following popup: you can click "manage content blocking" to change the blocking settings: how does firefox choose what to block?
... for example, you should not use google analytics in the following way: <a href="http://www.example.com" onclick="tracklink('http://www.example.com', event);"> visit example.com </a> <script> function tracklink(url,event) { event.preventdefault(); ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitcallback': function() { document.location = url; } }); } </script> instead, you should account for the ca...
Overview of Mozilla embedding APIs
public classes the following utility classes are available from the xpcom dll.
...public return codes ns_succeeded ns_error_failure ns_error_not_implemented public functions the following functions are available from the xpcom dll.
Embedding the editor
meeting these objectives will also solve the following existing composer problems: composer should handle frameset documents composer should handle documents with <iframe>s.
...fixing this would require js changes of the following kind: standardize the way that clients get at the editorshell (or its replacement, post-embedding work) from the window.
Gecko SDK
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.
... contents of the sdk the sdk contains the following: 1.9.2 idl files for frozen interfaces (under idl/) header files for frozen interfaces, xpcom functions, and nspr functions (under include/) import libraries or shared libraries (under lib/) static utility libraries (under lib/) various tools (under bin/) for more information about safely linking xpcom components using the xpcom "glue" library, see xpcom glue.
Script security
security policy gecko implements the following security policy: objects that are same-origin are able to access each other freely.
... (a is the start of the arrow, and b is the end.) computing a wrapper the following diagram shows the factors that determine the kind of wrapper that compartment a would get when trying to access an object in compartment b.
How to add a build-time test
note that the following variables are supplied by the rules.mk file: cppsrcs, simple_programs, run_test_program.
... for example, to add an xpcshell test to a module, do the following: copy tools/test-harness/xpcshell-simple/example to yourmoduledir/tests_type, wheretests_type is something that describes your tests.
How to get a stacktrace with WinDbg
(to get a stacktrace for thunderbird or some other product, substitute the product name where ever you see firefox in this instructions.) requirements to get such a stacktrace you need to install the following software: debugging tools for windows microsoft distributes the debugging tools for windows for free, those include windbg which you will need here.
... a: if you see 'int 3' after either of those exceptions, you will need to execute the following commands in windbg.
IPDL Best Practices
consider the following protocol: async protocol pasyncquerier { child: pasyncquery(); } async protocol pasyncquery { child: kickoffquery(nsstring query); parent: returnresult(nsstring result); __delete__(); } in this situation, there is a guaranteed sequence of messages that will be sent.
... following actor construction, the parent will send a kickoffquery message and presumably ignore the actor until it receives returnresult, at which point it will be deleted.
Implementing QueryInterface
it addrefs the resulting interface, not this, thus following the com-correct way (particularly important in aggregation) it uses nscomtypeinfo<t>::getiid() instead of ktiid thus saving a global declaration and global space it uses c 's static_cast, via ns_static_cast, which detects errors when you can't really get to the desired interface.
...the differences are highlighted in the following code.
JavaScript-DOM Prototypes in Mozilla
because of this, the following holds true (assuming img1 and img2 are two different image objects in the same document): img1.__proto__ === img2.__proto__ if img1 would come from one document and img2 from another document, then the above would not be true.
... | htmlelement.prototype | |.__proto__ | element.prototype | |.__proto__ | node.prototype | |.__proto__ | object.prototype | |.__proto__ | null if you have an instance of a htmldivelement in javascript, the following will hold true: div.__proto__ === htmldivelement.prototype which means that the following should also be true: div.__proto__ === div.constructor.prototype non standard no browser is required to provide modifiable __proto__, nor a global node, nor provide any way to get at host objects nor their associated prototypes.
CustomizableUI.jsm
the following event handlers are supported: onwidgetadded(awidgetid, aarea, aposition) fired when a widget is added to an area.
...the following properties are recognized: property description type the type of area.
Interfacing with the Add-on Repository
starting a request to start a search of the repository, you can use either of the following methods: searchaddons() queries the add-on repository for add-ons matching given search criteria.
... when the user clicks a toolbar button to initiate the query, the following code gets run to start the request: addonrepository.retrieverecommendedaddons(10, this); this asks the repository to fetch up to 10 add-ons, using the object this as the target for callbacks.
JavaScript OS.Constants
using os.constants from the main thread to initialize os.constants for use in the main thread, add the following snippet to your code: components.classes["@mozilla.org/net/osfileconstantsservice;1"].
...useful mostly for using js-ctypes to interact with the following platforms: macos x; android; linux; other variants of unix.
Examples
consider the following cases: function f() { return promise.reject(new error("boom!")); // if nobody catches the error, how will it be reported?
...} we adopt the following strategy: if a promise is rejected at the time of its garbage-collection and if the promise is at the end of a promise chain (i.e.
WebRequest.jsm
usage to import webrequest, use code like: let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); the webrequest object has the following properties, each of which corresponds to a specific stage in executing a web request: onbeforerequest onbeforesendheaders onsendheaders onheadersreceived onresponsestarted oncompleted each of these objects defines two functions: addlistener(callback, filter, opt_extrainfospec) removelistener(callback) adding listeners use addlistener to add a listener to a particular event.
... the following types are supported: "main_frame" "sub_frame" "stylesheet" "script" "image" "object" "xmlhttprequest" http headers https headers are represented as objects with two properties, name and value: name type description name string header name, for example "content-type" value string ...
XPCOMUtils.jsm
example for (var section in xpcomutils.iterstringenumerator(iniparser.getsections())) console.log(section); post-registration callback the post-registration callback called by generatemodule() should have the following signature: postregister( nsicomponentmanager compmgr, nsifile filespec, componentsarray ); parameters compmgr an nsicomponentmanager instance to use for managing the component.
... pre-unregistration callback the pre-unregistration callback passed to generatemodule() should have the following signature: preunregister( nsicomponentmanager compmgr, nsifile filespec, componentsarray ); parameters compmgr the nsicomponentmanager instance to use for managing the component.
Release phase
add the following lines to your ~/.ssh/config file, replacing user@host.domain with your mozilla ldap account name: host hg.mozilla.org user user@host.domain if you have already cloned the remote repository using the http protocol using this command: $ hg clone http://hg.mozilla.org/releases/l10n-central/x-testing then you will need to edit the .hg/hgrc file (inside the x-testing local clone) to tell mercurial...
...next, try issuing the following command: $ ssh hg.mozilla.org if ssh is working fine, you should see the following message: no interactive shells allowed here!
Localization technical reviews
this guide provides details on what a localization technical review is, what criteria are used for the technical reviews, and the process for requesting one and following its progress.
...most locales should have the following: #filter substitution pref("general.useragent.locale", "@ab_cd@") how it all works a large part of the review process takes place before you even submit your request for a technical review.
Localization formats
that file will have the following structure: ;getting started débuter avec firefox the english content is designated by the semi-colon and the localizer provides the translation underneath.
...with this arrangement, content for localization is presented in the following manner: msgid "coming soon" msgstr "bientôt disponible" where the value in the "" of the msgid is the english content, and the value in the "" of the msgstr is the translation.
Setting up the infrastructure
review the english content following the web content localizability guidelines.
... review your code following the web applications localizability guidelines.
MathML Demo: <mtable> - tables and matrices
contrast it with the following which has align="bottom" ---...
... and making floating elements do a multiplication such as the following one which is anchored at a baseline is made simple by using align="baseline1" on both tables [ a b c d ] [ a b c d ] to multiply a matrix a by a vector x, each row of the matrix has to be multiplied to the vector.
Using the viewport meta tag to control layout on mobile browsers
viewport basics a typical mobile-optimized site contains something like the following: <meta name="viewport" content="width=device-width, initial-scale=1"> the width property controls the size of the viewport.
...for example, if your layout needs at least 500 pixels of width then you can use the following markup.
Intel Power Gadget
understanding the power gadget output the following screenshot (from the mac version) demonstrates the available measurements.
... the three panes display the following information: power: shows power estimates for the package and the cores ("ia").
Refcount tracing and balancing
you may use an object's serial number with the following variable to further restrict the reference count tracing: xpcom_mem_log_objects set this variable to a comma-separated list of object serial number or ranges of serial number, e.g., 1,37-42,73,165 (serial numbers start from 1, not 0).
... the scripts output looks like the following.
turbostat
invocation turbostat must be invoked as the super-user: sudo turbostat if you get an error saying "turbostat: no /dev/cpu/0/msr", you need to run the following command: sudo modprobe msr the output is as follows: core cpu avg_mhz %busy bzy_mhz tsc_mhz smi cpu%c1 cpu%c3 cpu%c6 cpu%c7 coretmp pkgtmp pkg%pc2 pkg%pc3 pkg%pc6 pkg%pc7 pkgwatt corwatt gfxwatt - - 799 21.63 3694 3398 0 12.02 3.16 1.71 61.48 49 49 0.00 0.00 0.00 0.00 22.68 15.13 1.13 0 0 ...
... if you run with the -s option you get a smaller range of measurements that fit on a single line, like the following: avg_mhz %busy bzy_mhz tsc_mhz smi cpu%c1 cpu%c3 cpu%c6 cpu%c7 coretmp pkgtmp pkg%pc2 pkg%pc3 pkg%pc6 pkg%pc7 pkgwatt corwatt gfxwatt 3614 97.83 3694 3399 0 2.17 0.00 0.00 0.00 77 77 0.00 0.00 0.00 0.00 67.50 57.77 0.46 ...
Patches and pushes
com/gossip?output=fxjson&amp;command={searchterms}" />*** <url type="text/html" method="get" template="http://search.yahoo.com/search"> <param name="p" value="{searchterms}"/> <param name="ei" value="utf-8"/> <mozparam name="fr" condition="pref" pref="yahoo-fr" /> </url> <searchform>http://search.yahoo.com/</searchform> </searchplugin> create xml files for each search plugin preference following the above example.
... create a patch of the searchplugins directory by entering the following command in your command-line tool, where mypatch.diff is where you give your patch a name: $ hg add mozilla/browser/searchplugins/ $ hg diff mozilla/browser/searchplugins/ > mypatch.diff attach your patch file to the bug by clicking the "add an attachment" link.
Profile Manager
additionally, you can manually add firefox versions by clicking the "manage firefox versions..." button: each firefox version in the list has the following properties: path, version, and default.
... other operations context-clicking any profile in the profile list will cause a popup menu to appear with the following commands: copy - makes a copy of the profile using a name and location of your choice.
Localization Use Cases
ing, as: <brandshortname "boot2gecko" _gender:"neutral"> now we can translate crash-banner-os2 into polish without sounding like a robot: <crashbanneros2[brandshortname::_gender] { masculine: "{{ brandshortname }} uległ awarii", feminine: "{{ brandshortname }} uległa awarii", neutral: "{{ brandshortname }} uległo awarii" }> this will give us, depending on the current branding, the following messages: firefox os uległ awarii boot2gecko uległo awarii isolation let's look at how the settings app formats sizes.
... unit: _('byteunit-' + sizeinfo.unit) }); } the function is used like so: // application storage updateappfreespace: function storage_updateappfreespace() { var self = this; this.getfreespace(this.appstorage, function(freespace) { devicestoragehelper.showformatedsize(self.appstoragedesc, 'availablesize', freespace); }); }, problem definition for all values of freespace, the following string is enough to construct a grammatically-correct sentence in english: availablesize = {{$size}} {{$unit}} available however, other languages might need to pluralize this string with different forms of the available adjective.
Leak And Bloat Tests
aim to provide a continuous check within mailnews and its sub-components for the following items: total memory leaks.
... manually running tests setting up build set up build thunderbird or seamonkey with your standard mozconfig file, but with the following options set: ac_add_options --enable-debug ac_add_options --enable-trace-malloc running the tests in your <objdir> run the following command: make mailbloat this will run the tests and produce some result files.
I/O Functions
differences include the following: the blocking socket functions in nspr take a timeout parameter.
...for example, the following lines of code are equivalent: rv = pr_pushiolayer(stack, pr_top_io_layer, my_layer); rv = pr_pushiolayer(stack, pr_getlayersidentity(stack), my_layer); pr_getuniqueidentity pr_getnameforidentity pr_getlayersidentity pr_getidentitieslayer pr_getdefaultiomethods pr_createiolayerstub pr_pushiolayer pr_popiolayer ...
Named Shared Memory
pr_attachsharedmemory should be called following pr_opensharedmemory to map the memory segment to an address in the application's address space.
...following a call to pr_closesharedmemory, the prsharedmemory object is invalid and cannot be reused.
PR_Accept
syntax #include <prio.h> prfiledesc* pr_accept( prfiledesc *fd, prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the rendezvous socket on which the caller is willing to accept new connections.
... returns the function returns one of the following values: upon successful acceptance of a connection, a pointer to a new prfiledesc structure representing the newly accepted connection.
PR_Available
syntax #include <prio.h> print32 pr_available(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file or socket.
... returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading.
PR_Available64
syntax #include <prio.h> print64 pr_available64(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file or socket.
... returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading.
PR_Bind
syntax #include <prio.h> prstatus pr_bind( prfiledesc *fd, const prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
... returns the function returns one of the following values: upon successful binding of an address to a socket, pr_success.
PR_CEnterMonitor
syntax #include <prcmon.h> prmonitor* pr_centermonitor(void *address); parameter the function has the following parameter: address a reference to the data that is to be protected by the monitor.
... returns the function returns one of the following values: if successful, the function returns a pointer to the prmonitor associated with the value specified in the address parameter.
PR_CExitMonitor
syntax #include <prcmon.h> prstatus pr_cexitmonitor(void *address); parameters the function has the following parameters: address the address of the protected object--the same address previously passed to pr_centermonitor.
... returns the function returns one of the following values: if successful, pr_success.
PR_CWait
syntax #include <prcmon.h> prstatus pr_cwait( void *address, printervaltime timeout); parameters the function has the following parameters: address the address of the protected object--the same address previously passed to pr_centermonitor.
... returns the function returns one of the following values: pr_success indicates either that the monitored object has been notified or that the interval specified in the timeout parameter has been exceeded.
PR_Close
syntax #include <prio.h> prstatus pr_close(prfiledesc *fd); parameters the function has the following parameters: fd a pointer to a prfiledesc object.
... returns one of the following values: if file descriptor is closed successfully, pr_success.
PR_CloseFileMap
syntax #include <prio.h> prstatus pr_closefilemap(prfilemap *fmap); parameter the function has the following parameter: fmap the file mapping to be closed.
... returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success.
PR_Connect
syntax #include <prio.h> prstatus pr_connect( prfiledesc *fd, const prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
... returns the function returns one of the following values: upon successful completion of connection setup, pr_success.
PR_CreateFileMap
syntax #include <prio.h> prfilemap* pr_createfilemap( prfiledesc *fd, print64 size, prfilemapprotect prot); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the file that is to be mapped to memory.
...this parameter consists of one of the following options: pr_prot_readonly.
PR_CreateThread
syntax #include <prthread.h> prthread* pr_createthread( prthreadtype type, void (*start)(void *arg), void *arg, prthreadpriority priority, prthreadscope scope, prthreadstate state, pruint32 stacksize); parameters pr_createthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread).
... returns the function returns one of the following values: if successful, a pointer to the new thread.
PR_Delete
syntax #include <prio.h> prstatus pr_delete(const char *name); parameters the function has the following parameter: name the pathname of the file to be deleted.
... returns one of the following values: if file is deleted successfully, pr_success.
PR_DestroyPollableEvent
syntax nspr_api(prstatus) pr_destroypollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
... returns the function returns one of the following values: if successful, pr_success.
PR_EnumerateHostEnt
syntax #include <prnetdb.h> printn pr_enumeratehostent( printn enumindex, const prhostent *hostent, pruint16 port, prnetaddr *address); parameters the function has the following parameters: enumindex the index of the enumeration.
... returns the function returns one of the following values: if successful, the function returns the value you should specify in the enumindex parameter for the next call of the enumerator.
PR_ExitMonitor
syntax #include <prmon.h> prstatus pr_exitmonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor.
... returns the function returns one of the following values: if successful, pr_success.
PR GetAddrInfoByName
syntax #include <prnetdb.h> praddrinfo *pr getaddrinfobyname( const char *hostname, pruint16 af, printn flags); parameters the function has the following parameters: hostname the character string defining the host name of interest.
...include pr_ai_nocanonname to suppress the determination of the canonical name corresponding to hostname returns the function returns one of the following values: if successful, a pointer to the opaque praddrinfo structure containing the results of the host lookup.
PR_GetDescType
syntax #include <prio.h> prdesctype pr_getdesctype(prfiledesc *file); parameter the function has the following parameter: file a pointer to a prfiledesc object whose descriptor type is to be returned.
... description the prdesctype enumeration is defined as follows: typedef enum prdesctype { pr_desc_file = 1, pr_desc_socket_tcp = 2, pr_desc_socket_udp = 3, pr_desc_layered = 4 } prdesctype; the enumeration has the following enumerators: pr_desc_file the prfiledesc object represents a normal file.
PR_GetFileInfo
syntax #include <prio.h> prstatus pr_getfileinfo( const char *fn, prfileinfo *info); parameters the function has the following parameters: fn the pathname of the file to get information about.
... returns one of the following values: if the file information is successfully obtained, pr_success.
PR_GetFileInfo64
syntax #include <prio.h> prstatus pr_getfileinfo64( const char *fn, prfileinfo64 *info); parameters the function has the following parameters: fn the pathname of the file to get information about.
... returns one of the following values: if the file information is successfully obtained, pr_success.
PR_GetHostByAddr
syntax #include <prnetdb.h> prstatus pr_gethostbyaddr( const prnetaddr *hostaddr, char *buf, printn bufsize, prhostent *hostentry); parameters the function has the following parameters: hostaddr a pointer to the ip address of host in question.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetHostByName
syntax #include <prnetdb.h> prstatus pr_gethostbyname( const char *hostname, char *buf, printn bufsize, prhostent *hostentry); parameters the function has the following parameters: hostname the character string defining the host name of interest.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetIdentitiesLayer
syntax #include <prio.h> prfiledesc* pr_getidentitieslayer( prfiledesc* stack, prdescidentity id); parameters the function has the following parameters: stack a pointer to a prfiledesc object that is a layer in a stack of layers.
... returns the function returns one of the following values: if successful, a pointer to a file descriptor of the layer with the specified identity in the given stack of layers.
PR_GetNameForIdentity
syntax #include <prio.h> const char* pr_getnameforidentity(prdescidentity ident); parameter the function has the following parameter: ident a layer's identity.
... returns the function returns one of the following values: if successful, the function returns a pointer to the string associated with the specified layer.
PR_GetOpenFileInfo
syntax #include <prio.h> prstatus pr_getopenfileinfo( prfiledesc *fd, prfileinfo *info); parameters the function has the following parameters: fd a pointer to a prfiledesc object for an open file.
... returns the function returns one of the following values: if file information is successfully obtained, pr_success.
PR_GetOpenFileInfo64
syntax #include <prio.h> prstatus pr_getopenfileinfo64( prfiledesc *fd, prfileinfo *info); parameters the function has the following parameters: fd a pointer to a prfiledesc object for an open file.
... returns the function returns one of the following values: if file information is successfully obtained, pr_success.
PR_GetProtoByName
syntax #include <prnetdb.h> prstatus pr_getprotobyname( const char* protocolname, char* buffer, print32 bufsize, prprotoent* result); parameters the function has the following parameters: protocolname a pointer to the character string of the protocol's name.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetProtoByNumber
syntax #include <prnetdb.h> prstatus pr_getprotobynumber( print32 protocolnumber, char* buffer, print32 bufsize, prprotoent* result); parameters the function has the following parameters: protocolnumber the number assigned to the protocol.
... returns the function returns one of the following values: if successful, pr_success.
PR_GetUniqueIdentity
syntax #include <prio.h> prdescidentity pr_getuniqueidentity(const char *layer_name); parameter the function has the following parameter: layer_name the string associated with the creation of a layer's identity.
... returns the function returns one of the following values: if successful, the prdescidentity for the layer associated with the string specified in the layer named layer_name.
PR ImportTCPSocket
syntax #include "private/pprio.h" prfiledesc* pr_importtcpsocket(prosfd osfd); parameters the function has the following parameters: osfd the native file descriptor for the tcp socket to import.
... returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly imported native tcp socket.
PR_JoinThread
syntax #include <prthread.h> prstatus pr_jointhread(prthread *thread); parameter pr_jointhread has the following parameter: thread a valid identifier for the thread that is to be joined.
... returns the function returns one of the following values: if successful, pr_success if unsuccessful--for example, if no joinable thread can be found that corresponds to the specified target thread, or if the target thread is unjoinable--pr_failure.
PR_Listen
syntax #include <prio.h> prstatus pr_listen( prfiledesc *fd, printn backlog); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket that will be used to listen for new connections.
... returns the function returns one of the following values: upon successful completion of listen request, pr_success.
PR_MkDir
syntax #include <prio.h> prstatus pr_mkdir( const char *name, printn mode); parameters the function has the following parameters: name the name of the directory to be created.
... possible values include the following: 00400.
PR_NEXT_LINK
description pr_next_link returns a pointer to the element following the specified element.
...the following element is not removed from the list.
PR_NetAddrToString
syntax #include <prnetdb.h> prstatus pr_netaddrtostring( const prnetaddr *addr, char *string, pruint32 size); parameters the function has the following parameters: addr a pointer to the network address to be converted.
... returns the function returns one of the following values: if successful, pr_success.
PR_NewThreadPrivateIndex
syntax #include <prthread.h> prstatus pr_newthreadprivateindex( pruintn *newindex, prthreadprivatedtor destructor); parameters pr_newthreadprivateindex has the following parameters: newindex on output, an index that is valid for all threads in the process.
... returns the function returns one of the following values: if successful, pr_success.
PR_Notify
syntax #include <prmon.h> prstatus pr_notify(prmonitor *mon); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor.
... returns the function returns one of the following values: if successful, pr_success.
PR_NotifyAll
syntax #include <prmon.h> prstatus pr_notifyall(prmonitor *mon); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor.
... returns the function returns one of the following values: if successful, pr_success.
PR_OpenTCPSocket
syntax #include <prio.h> prfiledesc* pr_opentcpsocket(printn af); parameters the function has the following parameters: af the address family of the new tcp socket.
... returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened tcp socket.
PR OpenUDPSocket
syntax #include <prio.h> prfiledesc* pr_openudpsocket(printn af); parameters the function has the following parameters: af the address family of the new udp socket.
... returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
PR_PopIOLayer
syntax #include <prio.h> prfiledesc *pr_popiolayer( prfiledesc *stack, prdescidentity id); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack from which the specified layer is to be removed.
... returns the function returns one of the following values: if the layer is successfully removed from the stack, a pointer to the removed layer.
PR_PushIOLayer
syntax #include <prio.h> prstatus pr_pushiolayer( prfiledesc *stack, prdescidentity id, prfiledesc *layer); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack.
... returns the function returns one of the following values: if the layer is successfully pushed onto the stack, pr_success.
PR_Read
syntax #include <prio.h> print32 pr_read(prfiledesc *fd, void *buf, print32 amount); parameters the function has the following parameters: fd a pointer to a prfiledesc object for the file or socket.
... returns one of the following values: a positive number indicates the number of bytes actually read in.
PR_Recv
syntax #include <prio.h> print32 pr_recv( prfiledesc *fd, void *buf, print32 amount, printn flags, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
... returns the function returns one of the following values: a positive number indicates the number of bytes actually received.
PR_RecvFrom
syntax #include <prio.h> print32 pr_recvfrom( prfiledesc *fd, void *buf, print32 amount, printn flags, prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
... returns the function returns one of the following values: a positive number indicates the number of bytes actually received.
PR_Rename
syntax #include <prio.h> prstatus pr_rename( const char *from, const char *to); parameters the function has the following parameters: from the old name of the file to be renamed.
... returns one of the following values: if file is successfully renamed, pr_success.
PR_Send
syntax #include <prio.h> print32 pr_send( prfiledesc *fd, const void *buf, print32 amount, printn flags, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
... returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent.
PR_SendTo
syntax #include <prio.h> print32 pr_sendto( prfiledesc *fd, const void *buf, print32 amount, printn flags, const prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
... returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent.
PR_SetPollableEvent
syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
... returns the function returns one of the following values: if successful, pr_success.
PR_SetThreadPrivate
syntax #include <prthread.h> prstatus pr_setthreadprivate(pruintn index, void *priv); parameters pr_setthreadprivate has the following parameters: index an index into the per-thread private data table.
... returns the function returns one of the following values: if successful, pr_success.
PR_StringToNetAddr
syntax #include <prnetdb.h> prstatus pr_stringtonetaddr( const char *string, prnetaddr *addr); parameters the function has the following parameters: string the string to be converted.
... returns the function returns one of the following values: if successful, pr_success.
PR_Sync
syntax #include <prio.h> prstatus pr_sync(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file.
... returns the function returns one of the following values: on successful completion, pr_success.
PR_TransmitFile
syntax #include <prio.h> print32 pr_transmitfile( prfiledesc *networksocket, prfiledesc *sourcefile, const void *headers, print32 hlen, prtransmitfileflags flags, printervaltime timeout); parameters the function has the following parameters: networksocket a pointer to a prfiledesc object representing the connected socket to send data over.
... flags one of the following flags: pr_transmitfile_keep_open indicates that the socket will be kept open after the data is sent.
PR_Unmap
syntax #include <prio.h> prstatus pr_memunmap( void *addr, pruint32 len); parameters the function has the following parameters: addr the starting address of the memory region to be unmapped.
... returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success.
PR_Wait
syntax #include <prmon.h> prstatus pr_wait( prmonitor *mon, printervaltime ticks); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor.
... returns the function returns one of the following values: pr_success means the thread is being resumed from the pr_wait call either because it was explicitly notified or because the time specified by the parameter ticks has expired.
PR_WaitCondVar
syntax #include <prcvar.h> prstatus pr_waitcondvar( prcondvar *cvar, printervaltime timeout); parameters pr_waitcondvar has the following parameters: cvar the condition variable on which to wait.
... returns the function returns one of the following values: if successful, pr_success.
PR_WaitForPollableEvent
syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
... returns the function returns one of the following values: if successful, pr_success.
PR_Write
syntax #include <prio.h> print32 pr_write( prfiledesc *fd, const void *buf, print32 amount); parameters the function has the following parameters: fd a pointer to the prfiledesc object for a file or socket.
... returns one of the following values: a positive number indicates the number of bytes successfully written.
4.3.1 Release Notes
release date: 2009-12-02 introduction network security services for java (jss) 4.3.1 is a minor release with the following new features: support for ssl3 & tls renegotiation vulnerablity support to explicitly set the key usage for the generated private key jss 4.3.1 is tri-licensed under mpl 1.1/gpl 2.0/lgpl 2.1.
...this default setting can also be changed within the application by using the following jss methods: sslserversocket.enablerenegotiation(int mode) sslsocket.enablerenegotiation(int mode) sslsocket.enablerenegotiationdefault(int mode) the mode of renegotiation that the peer must use can be set to the following: sslsocket.ssl_renegotiate_never - never renegotiate at all.
4.3 Release Notes
release date: 01 april 2009 introduction network security services for java (jss) 4.3 is a minor release with the following new features: sqlite-based shareable certificate and key databases libpkix: an rfc 3280 compliant certificate path validation library pkcs11 needslogin method support hmacsha256, hmacsha384, and hmacsha512 support for all nss 3.12 initialization options jss 4.3 is tri-licensed under mpl 1.1/gpl 2.0/lgpl 2.1.
...se_alert ssl_error_bad_cert_hash_value_alert new tls cipher suites (see http://mxr.mozilla.org/security/sour...sslsocket.java): tls_rsa_with_camellia_128_cbc_sha tls_dhe_dss_with_camellia_128_cbc_sha tls_dhe_rsa_with_camellia_128_cbc_sha tls_rsa_with_camellia_256_cbc_sha tls_dhe_dss_with_camellia_256_cbc_sha tls_dhe_rsa_with_camellia_256_cbc_sha note: the following tls cipher suites are declared but are not yet implemented: tls_dh_dss_with_camellia_128_cbc_sha tls_dh_rsa_with_camellia_128_cbc_sha tls_dh_anon_with_camellia_128_cbc_sha tls_dh_dss_with_camellia_256_cbc_sha tls_dh_rsa_with_camellia_256_cbc_sha tls_dh_anon_with_camellia_256_cbc_sha tls_ecdh_anon_with_null_sha tls_ecdh_anon_with_rc4_128_sha tls_ecdh_anon_with...
NSS Key Log Format
secrets follow the format <label> <space> <clientrandom> <space> <secret> where: <label> describes the following secret.
... the following labels are defined, followed by a description of the secret: rsa: 48 bytes for the premaster secret, encoded as 96 hexadecimal characters (removed in nss 3.34) client_random: 48 bytes for the master secret, encoded as 96 hexadecimal characters (for ssl 3.0, tls 1.0, 1.1 and 1.2) client_early_traffic_secret: the hex-encoded early traffic secret for the client side (for tls 1.3) client_handshake_traffic_secret: the hex-encoded handshake traffic secret for the client side (for tls 1.3) server_handshake_traffic_secret: the hex-encoded handshake traffic secret for the server side (for tls 1.3) client_traffic_secret_0: the first...
NSS_3.11.10_release_notes.html
bugs fixed the following bugs have been fixed in nss 3.11.10.
...new and revised documents available since the release of nss 3.9 include the following: build instructions for nss 3.11.4 and above compatibility nss 3.11.10 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS_3.12.1_release_notes.html
levels of standards conformance strictness for cert_nametoasciiinvertible (see certt.h) cert_n2a_readable (maximum human readability) cert_n2a_strict (strict rfc compliance) cert_n2a_invertible (maximum invertibility) bugs fixed the following bugs have been fixed in nss 3.12.1.
...new and revised documents available since the release of nss 3.11 include the following: build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS_3.12.2_release_notes.html
new in nss 3.12.2 new functions in the nss shared library: sec_pkcs12addcertorchainandkey (see p12.h) new pkcs11 errors (see secerr.h) sec_error_pkcs11_general_error sec_error_pkcs11_function_failed sec_error_pkcs11_device_error bugs fixed the following bugs have been fixed in nss 3.12.2.
...new and revised documents available since the release of nss 3.11 include the following: build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.2 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.12.4 release notes
bugs fixed the following bugs have been fixed in nss 3.12.4.
...new and revised documents available since the release of nss 3.12 include the following: build instructions for nss 3.12.4 compatibility nss 3.12.4 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.12.9 release notes
new in nss 3.12.9 removed functions new ssl options new error codes bugs fixed the following bugs have been fixed in nss 3.12.9.
...new and revised documents available since the release of nss 3.11 include the following:</for> build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.9 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.15.2 release notes
distribution information nss 3.15.2 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_2_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.2.
...specifically, the following cipher suites are now supported: tls_ecdhe_ecdsa_with_aes_128_gcm_sha256 tls_ecdhe_rsa_with_aes_128_gcm_sha256 tls_dhe_rsa_with_aes_128_gcm_sha256 tls_rsa_with_aes_128_gcm_sha256 new functions pk11_cipherfinal has been introduced, which is a simple alias for pk11_digestfinal.
NSS 3.17.3 release notes
the following ca certificates were removed cn = gte cybertrust global root sha1 fingerprint: 97:81:79:50:d8:1c:96:70:cc:34:d8:09:cf:79:44:31:36:7e:f4:74 cn = thawte server ca sha1 fingerprint: 23:e5:94:94:51:95:f2:41:48:03:b4:d5:64:d2:a3:a3:f5:d8:8b:8c cn = thawte premium server ca sha1 fingerprint: 62:7f:8d:78:27:65:63:99:d2:7d:7f:90:44:c9:fe:b3:f3:3...
...e:fa:9a cn = america online root certification authority 1 sha-1 fingerprint: 39:21:c1:15:c1:5d:0e:ca:5c:cb:5b:c4:f0:7d:21:d8:05:0b:56:6a cn = america online root certification authority 2 sha-1 fingerprint: 85:b5:ff:67:9b:0c:79:96:1f:c8:6e:44:22:00:46:13:db:17:92:84 the following ca certificates had the websites and code signing trust bits turned off ou = class 3 public primary certification authority - g2 sha1 fingerprint: 85:37:1c:a6:e5:50:14:3d:ce:28:03:47:1b:de:3a:09:e8:f8:77:0f cn = equifax secure ebusiness ca-1 sha1 fingerprint: da:40:18:8b:91:89:a3:ed:ee:ae:da:97:fe:2f:9d:f5:b7:d1:8a:41 the following ca certificates were added cn = comodo rsa certification authority ...
NSS 3.18 release notes
the following ca certificates had the websites and code signing trust bits turned off ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a cn = equifax secure global ebusiness ca-1 sha1 fingerprint: 7e:78:4a:10:1c:82:65:cc:2d:e1:f1:6d:47:b4:40:ca:d9:0a:19:45 cn = tc trustcenter class 3 ca ii ...
... sha1 fingerprint: 80:25:ef:f4:6e:70:c8:d4:72:24:65:84:fe:40:3b:8a:8d:6a:db:f5 the following ca certificates were added cn = staat der nederlanden root ca - g3 sha1 fingerprint: d8:eb:6b:41:51:92:59:e0:f3:e7:85:00:c0:3d:b6:88:97:c9:ee:fc cn = staat der nederlanden ev root ca sha1 fingerprint: 76:e2:7e:c1:4f:db:82:c1:c0:a6:75:b5:05:be:3d:29:b4:ed:db:bb cn = identrust commercial root ca 1 sha1 fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25 cn = identrust public sector root ca 1 sha1 fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd cn = s-trust universal root ca sha1 fingerprint: 1b:3d:11:14:ea:7a:0f:95:58:54:41:95:bf:6b:25:82:...
NSS 3.19.2.1 release notes
nss 3.19.2.1 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.2.1.
... the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss.
NSS 3.19.3 release notes
notable changes in nss 3.19.3 the following ca certificates were removed cn = buypass class 3 ca 1 sha1 fingerprint: 61:57:3a:11:df:0e:d8:7e:d5:92:65:22:ea:d0:56:d7:44:b3:23:71 cn = tÜrktrust elektronik sertifika hizmet sağlayıcısı sha1 fingerprint: 79:98:a3:08:e1:4d:65:85:e6:c2:1e:15:3a:71:9f:ba:5a:d3:4a:d9 cn = sg trust services racine sha1 fingerprint: 0c:62:8f:5c:55:70:b...
...1:c9:57:fa:fd:38:3f:b0:3d:7b:7d:d7:b9:c6 cn = tc trustcenter universal ca i sha-1 fingerprint: 6b:2f:34:ad:89:58:be:62:fd:b0:6b:5c:ce:bb:9d:d9:4f:4e:39:f3 cn = tc trustcenter class 2 ca ii sha-1 fingerprint: ae:50:83:ed:7c:f4:5c:bc:8f:61:c6:21:fe:68:5d:79:42:21:15:6e the following ca certificate had the websites trust bit turned off cn = comsign secured ca sha1 fingerprint: f9:cd:0e:2c:da:76:24:c1:8f:bd:f0:f0:ab:b6:45:b8:f7:fe:d5:7a the following ca certificates were added cn = tÜrktrust elektronik sertifika hizmet sağlayıcısı h5 sha1 fingerprint: c4:18:f6:4d:46:d1:df:00:3d:27:30:13:72:43:a9:12:11:c6:75:fb cn = tÜrktrust elektronik sertifika hizmet sağlayıcısı h6 ...
NSS 3.19.4 release notes
nss 3.19.4 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_4_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.4.
... the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss.
NSS 3.20.1 release notes
nss 3.20.1 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.20.1.
... the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss.
NSS 3.21 release notes
reinfo_cipher_suite - used with sslpreliminarychannelinfo to indicate that a tls cipher suite has been selected ssl_preinfo_all - used with sslpreliminarychannelinfo to indicate that all preliminary information has been set notable changes in nss 3.21 nss now builds with elliptic curve ciphers enabled by default (bug 1205688) nss now builds with warnings as errors (bug 1182667) the following ca certificates were removed cn = verisign class 4 public primary certification authority - g3 sha1 fingerprint: c8:ec:8c:87:92:69:cb:4b:ab:39:e9:8d:7e:57:67:f3:14:95:73:9d cn = utn-userfirst-network applications sha1 fingerprint: 5d:98:9c:db:15:96:11:36:51:65:64:1b:56:0f:db:ea:2a:c2:3e:f1 cn = tc trustcenter universal ca iii sha1 finger...
...(c) kasım 2005 sha-1 fingerprint: b4:35:d4:e1:11:9d:1c:66:90:a7:49:eb:b3:94:bd:63:7b:a7:82:b7 the following ca certificate had the websites trust bit turned off ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a the following ca certificates were added cn = certification authority of wosign g2 sha1 fingerprint: fb:ed:dc:90:65:b7:27:20:37:bc:55:0c:9c:56:de:bb:f2:78:94:e1 cn =...
NSS 3.23 release notes
the following ca certificates were removed cn = staat der nederlanden root ca sha-256 fingerprint: d4:1d:82:9e:8c:16:59:82:2a:f9:3f:ce:62:bf:fc:de:26:4f:c8:4e:8b:95:0c:5f:f2:75:d0:52:35:46:95:a3 cn = netlock minositett kozjegyzoi (class qa) tanusitvanykiado sha-256 fingerprint: e6:06:dd:ee:e2:ee:7f:5c:de:f5:d9:05:8f:f8:b7:d0:a9:f0:42:87:7f:6a:17:1e:d8:ff:69:60:e4:cc:5e:a5 ...
...cc:4f:a3:29:c2:cc:f0:e2:fa:1b:14:03:05 friendly name: verisign class 3 public pca – g2 sha-256 fingerprint: 83:ce:3c:12:29:68:8a:59:3d:48:5f:81:97:3c:0f:91:95:43:1e:da:37:cc:5e:36:43:0e:79:c7:a8:88:63:8b cn = ca disig sha-256 fingerprint: 92:bf:51:19:ab:ec:ca:d0:b1:33:2d:c4:e1:d0:5f:ba:75:b5:67:90:44:ee:0c:a2:6e:93:1f:74:4f:2f:33:cf the following ca certificates were added cn = szafir root ca2 sha-256 fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe cn = certum trusted network ca 2 sha-256 fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 the following ca certificate ha...
NSS 3.25 release notes
nss 3.25 source distributions are available on ftp.mozilla.org for secure https download at the following location.
... the following ca certificate was removed cn = sonera class1 ca sha-256 fingerprint: cd:80:82:84:cf:74:6f:f2:fd:6e:b5:8a:a1:d5:9c:4a:d4:b3:ca:56:fd:c6:27:4a:89:26:a7:83:5f:32:31:3d the following ca certificates were added cn = hellenic academic and research institutions rootca 2015 sha-256 fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:...
NSS 3.28.1 release notes
notable changes in nss 3.28.1 the following ca certificates were removed cn = buypass class 2 ca 1 sha-256 fingerprint: 0f:4e:9c:dd:26:4b:02:55:50:d1:70:80:63:40:21:4f:e9:44:34:c9:b0:2f:69:7e:c7:10:fc:5f:ea:fb:5e:38 cn = root ca generalitat valenciana sha-256 fingerprint: 8c:4e:df:d0:43:48:f3:22:96:9e:7e:29:a4:cd:4d:ca:00:46:55:06:1c:16:e1:b0:76:42:2e:f3:42:ad:63:0e ou = rsa security 2048 ...
...v3 sha-256 fingerprint: af:8b:67:62:a1:e5:28:22:81:61:a9:5d:5c:55:9e:e2:66:27:8f:75:d7:9e:83:01:89:a5:03:50:6a:bd:6b:4c the following ca certificates were added ou = ac raiz fnmt-rcm sha-256 fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa cn = amazon root ca 1 sha-256 fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e cn = amazon root ca 2 sha-256 fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4 cn = amazon root ca 3 sha-256 fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:...
NSS 3.28.5 release notes
notable changes in nss 3.28.5 the following ca certificates were removed: o = japanese government, ou = applicationca sha-256 fingerprint: 2d:47:43:7d:e1:79:51:21:5a:12:f3:c5:8e:51:c7:29:a5:80:26:ef:1f:cc:0a:5f:b3:d9:dc:01:2f:60:0d:19 cn = wellssecure public root certificate authority sha-256 fingerprint: a7:12:72:ae:aa:a3:cf:e8:72:7f:7f:b3:9f:0f:b3:d1:e5:42:6e:90:60:b0:6e:e6:f1:3e:9a:3c:58:33:cd:43 ...
... cn=tÜrktrust elektronik sertifika hizmet sağlayıcısı h6 sha-256 fingerprint: 8d:e7:86:55:e1:be:7f:78:47:80:0b:93:f6:94:d2:1d:36:8c:c0:6e:03:3e:7f:ab:04:bb:5e:b9:9d:a6:b7:00 cn=microsec e-szigno root sha-256 fingerprint: 32:7a:3d:76:1a:ba:de:a0:34:eb:99:84:06:27:5c:b1:a4:77:6e:fd:ae:2f:df:6d:01:68:ea:1c:4f:55:67:d0 the following ca certificates were added: cn = d-trust root ca 3 2013 sha-256 fingerprint: a1:a8:6d:04:12:1e:b8:7f:02:7c:66:f5:33:03:c2:8e:57:39:f9:43:fc:84:b3:8a:d6:af:00:90:35:dd:94:57 trust flags: email cn = tubitak kamu sm ssl kok sertifikasi - surum 1 sha-256 fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 trust fl...
NSS 3.30.2 release notes
notable changes in nss 3.30.2 the following ca certificates were removed: o = japanese government, ou = applicationca sha-256 fingerprint: 2d:47:43:7d:e1:79:51:21:5a:12:f3:c5:8e:51:c7:29:a5:80:26:ef:1f:cc:0a:5f:b3:d9:dc:01:2f:60:0d:19 cn = wellssecure public root certificate authority sha-256 fingerprint: a7:12:72:ae:aa:a3:cf:e8:72:7f:7f:b3:9f:0f:b3:d1:e5:42:6e:90:60:b0:6e:e6:f1:3e:9a:3c:58:33:cd:43 ...
... cn=tÜrktrust elektronik sertifika hizmet sağlayıcısı h6 sha-256 fingerprint: 8d:e7:86:55:e1:be:7f:78:47:80:0b:93:f6:94:d2:1d:36:8c:c0:6e:03:3e:7f:ab:04:bb:5e:b9:9d:a6:b7:00 cn=microsec e-szigno root sha-256 fingerprint: 32:7a:3d:76:1a:ba:de:a0:34:eb:99:84:06:27:5c:b1:a4:77:6e:fd:ae:2f:df:6d:01:68:ea:1c:4f:55:67:d0 the following ca certificates were added: cn = d-trust root ca 3 2013 sha-256 fingerprint: a1:a8:6d:04:12:1e:b8:7f:02:7c:66:f5:33:03:c2:8e:57:39:f9:43:fc:84:b3:8a:d6:af:00:90:35:dd:94:57 trust flags: email cn = tubitak kamu sm ssl kok sertifikasi - surum 1 sha-256 fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 trust fl...
NSS 3.32 release notes
the websites (tls/ssl) trust bit was turned off for the following root certificates.
... cn = addtrust class 1 ca root sha-256 fingerprint: 8c:72:09:27:9a:c0:4e:27:5e:16:d0:7f:d3:b7:75:e8:01:54:b5:96:80:46:e3:1f:52:dd:25:76:63:24:e9:a7 cn = swisscom root ca 2 sha-256 fingerprint: f0:9b:12:2c:71:14:f4:a0:9b:d4:ea:4f:4a:99:d5:58:b4:6e:4c:25:cd:81:14:0d:29:c0:56:13:91:4c:38:41 the following ca certificates were removed: cn = addtrust public ca root sha-256 fingerprint: 07:91:ca:07:49:b2:07:82:aa:d3:c7:d7:bd:0c:df:c9:48:58:35:84:3e:b2:d7:99:60:09:ce:43:ab:6c:69:27 cn = addtrust qualified ca root sha-256 fingerprint: 80:95:21:08:05:db:4b:bc:35:5e:44:28:d8:fd:6e:c2:cd:e3:ab:5f:b9:7a:99:42:98:8e:b8:f4:dc:d0:60:16 cn = china internet network information center ev certificates root ...
NSS 3.34 release notes
nss 3.34 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_34_rtm/src/ notable changes in nss 3.34 the following ca certificates were added: cn = gdca trustauth r5 root sha-256 fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93 trust flags: websites cn = ssl.com root certification authority rsa sha-256 fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:...
...n = trustcor rootcert ca-2 sha-256 fingerprint: 07:53:e9:40:37:8c:1b:d5:e3:83:6e:39:5d:ae:a5:cb:83:9e:50:46:f1:bd:0e:ae:19:51:cf:10:fe:c7:c9:65 trust flags: websites, email cn = trustcor eca-1 sha-256 fingerprint: 5a:88:5d:b1:9c:01:d9:12:c5:75:93:88:93:8c:af:bb:df:03:1a:b2:d4:8e:91:ee:15:58:9b:42:97:1d:03:9c trust flags: websites, email the following ca certificates were removed: cn = certum ca, o=unizeto sp.
NSS 3.35 release notes
the following ca certificates were removed: ou = security communication ev rootca1 sha-256 fingerprint: a2:2d:ba:68:1e:97:37:6e:2d:39:7d:72:8a:ae:3a:9b:62:96:b9:fd:ba:60:bc:2e:11:f6:47:f2:c6:75:fb:37 cn = ca disig root r1 sha-256 fingerprint: f9:6f:23:f4:c3:e7:9c:07:7a:46:98:8d:5a:f5:90:06:76:a0:f0:39:cb:64:5d:d1:75:49:b2:16:c8:24:40:ce cn = dst aces ca x6 ...
... the websites (tls/ssl) trust bit was turned off for the following ca certificates: cn = chambers of commerce root sha-256 fingerprint: 0c:25:8a:12:a5:67:4a:ef:25:f2:8b:a7:dc:fa:ec:ee:a3:48:e5:41:e6:f5:cc:4e:e6:3b:71:b3:61:60:6a:c3 cn = global chambersign root sha-256 fingerprint: ef:3c:b4:17:fc:8e:bf:6f:97:87:6c:9e:4e:ce:39:de:1e:a5:fe:64:91:41:d1:02:8b:7d:11:c0:b2:29:8c:ed significant changes to tls 1.3 were...
NSS 3.39 release notes
the following ca certificates were added: ou = globalsign root ca - r6 sha-256 fingerprint: 2cabeafe37d06ca22aba7391c0033d25982952c453647349763a3ab5ad6ccf69 cn = oiste wisekey global root gc ca sha-256 fingerprint: 8560f91c3624daba9570b5fea0dbe36ff11a8323be9486854fb3f34a5571198d the following ca certificate was removed: cn = comsign sha-256 f...
...ingerprint: ae4457b40d9eda96677b0d3c92d57b5177abd7ac1037958356d1e094518be5f2 the following ca certificates had the websites trust bit disabled: cn = certplus root ca g1 sha-256 fingerprint: 152a402bfcdf2cd548054d2275b39c7fca3ec0978078b0f0ea76e561a6c7433e cn = certplus root ca g2 sha-256 fingerprint: 6cc05041e6445e74696c4cfbc9f80f543b7eabbb44b4ce6f787c6a9971c42f17 cn = opentrust root ca g1 sha-256 fingerprint: 56c77128d98c18d91b4cfdffbc25ee9103d4758ea2abad826a90f3457d460eb4 cn = opentrust root ca g2 sha-256 fingerprint: 27995829fe6a7515c1bfe848f9c4761db16c225929257bf40d0894f29ea8baf2 cn = opentrust root ca g3 sha-256 fingerprint: b7c36231706e81078c367cb896198f1e3208dd926949dd8f5709a...
NSS 3.41 release notes
bug 1493215 - enabled the following ciphersuites by default: tls_ecdhe_ecdsa_with_aes_256_gcm_sha384 tls_ecdhe_rsa_with_aes_256_gcm_sha384 tls_dhe_rsa_with_aes_256_gcm_sha384 tls_rsa_with_aes_256_gcm_sha384 new functions none notable changes in nss 3.41 the following ca certificates were added: cn = certigna root ca sha-256 fingerprint: d48d3d23eedb50a459e55197601c27774b9d7b18c94d5a059511a10250b93...
...a71babce5 cn = gts root r4 sha-256 fingerprint: 71cca5391f9e794b04802530b363e121da8a3043bb26662fea4dca7fc951a4bd cn = uca global g2 root sha-256 fingerprint: 9bea11c976fe014764c1be56a6f914b5a560317abd9988393382e5161aa0493c cn = uca extended validation root sha-256 fingerprint: d43af9b35473755c9684fc06d7d8cb70ee5c28e773fb294eb41ee71722924d24 the following ca certificates were removed: cn = ac raíz certicámara s.a.
NSS 3.43 release notes
note that while the mechanism is present, post-handshake authentication is currently not tls 1.3 compliant due to bug 1532312 notable changes in nss 3.43 the following ca certificates were added: cn = emsign root ca - g1 sha-256 fingerprint: 40f6af0346a99aa1cd1d555a4e9cce62c7f9634603ee406615833dc8c8d00367 cn = emsign ecc root ca - g3 sha-256 fingerprint: 86a1ecba089c4a8d3bbe2734c612ba341d813e043cf9e8a862cd5c57a36bbe6b cn = emsign root ca - c1 sha-256 fingerprint: 125609aa301da0a249b97a8239cb6a34216f44dcac9f3954b14292f2...
...e8c8608f cn = emsign ecc root ca - c3 sha-256 fingerprint: bc4d809b15189d78db3e1d8cf4f9726a795da1643ca5f1358e1ddb0edc0d7eb3 cn = hongkong post root ca 3 sha-256 fingerprint: 5a2fc03f0c83b090bbfa40604b0988446c7636183df9846e17101a447fb8efd6 the following ca certificates were removed: none bugs fixed in nss 3.43 bug 1528669 and bug 1529308 - improve gyp build system handling bug 1529950 and bug 1521174 - improve nss s/mime tests for thunderbird bug 1530134 - if docker isn't installed, try running a local clang-format as a fallback bug 1531267 - enable fips mode automatically if the system fips mode flag is set bug 1528262 - add a -j option to the strsclnt command to specify sigschemes bug 1513909 - add manual for nss-policy-check bug 1531074 - ...
NSS 3.54 release notes
certificate authority changes the following ca certificates were added: bug 1645186 - certsign root ca g2 sha-256 fingerprint: 657cfe2fa73faa38462571f332a2363a46fce7020951710702cdfbb6eeda3305 bug 1645174 - e-szigno root ca 2017 sha-256 fingerprint: beb00b30839b9bc32c32e4447905950641f26421b15ed089198b518ae2ea1b99 bug 1641716 - microsoft ecc root certificate authority 2017 sha-256 ...
...fingerprint: 358df39d764af9e1b766e9c972df352ee15cfac227af6ad1d70e8e4a6edcba02 bug 1641716 - microsoft rsa root certificate authority 2017 sha-256 fingerprint: c741f70f4b2a8d88bf2e71c14122ef53ef10eba0cfa5e64cfa20f418853073e0 the following ca certificates were removed: bug 1645199 - addtrust class 1 ca root sha-256 fingerprint: 8c7209279ac04e275e16d07fd3b775e80154b5968046e31f52dd25766324e9a7 bug 1645199 - addtrust external ca root sha-256 fingerprint: 687fa451382278fff0c8b11f8d43d576671c6eb2bceab413fb83d965d06d2ff2 bug 1641718 - luxtrust global root 2 sha-256 fingerprint: 54455f7129c20b1447c418f997168f24c58fc5023bf5da5be2eb6e1dd8902ed5 bug 1639987 - staat der nederlanden root ca - ...
NSS Developer Tutorial
curly braces: both of the following styles are allowed: if (condition) { action1(); } else { action2(); } or: if (condition) { action1(); } else { action2(); } the former style is more common.
... multiple-line comments should be formatted as follows: /* * line1 * line2 */ or /* ** line 1 ** line 2 */ the following styles are also common, because they conserve vertical space: /* line1 * line2 */ or /* line1 ** line2 */ or /* line1 * line2 */ naming public functions are named foo_dooneaction.
NSS sources building testing
create a new directory on your computer that you will use as your local work area, and run the following commands.
...the subdirectories dbm, security/dbm, security/coreconf, security/nss were part of the nss sources.) the nss directory contains the following important subdirectories: nss/coreconf contains knowledge for cross platform building.
nss tech note1
the following is not an attempt to explain asn.1 tags or their purposes.
...the following macros are provided for tag numbers within the universal class : sec_asn1_boolean, sec_asn1_integer, sec_asn1_bit_string, sec_asn1_octet_string, sec_asn1_null, sec_asn1_object_id, sec_asn1_object_descriptor,† sec_asn1_real, sec_asn1_enumerated, sec_asn1_embedded_pdv, sec_asn1_utf8_string, sec_asn1_sequence, sec_asn1_set, sec_asn1_numeric_string, sec_asn1_printable_string, sec_asn1_t61_stri...
nss tech note4
e *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 components pass &(cert->issuer) or &(cert->subject) to the following functions char *cert_getcommonname(certname *name); char *cert_getcertemailaddress(certname *name); char *cert_getcountryname(certname *name); char *cert_getlocalityname(certname *name); char *cert_getstatename(certname *name); char *cert_getorgname(certname *name); char *cert_getorgunitname(certname *name); char *cert_getdomaincomponentname(cer...
... background on cert extensions an extension has the following attributes object id (oid) : a unique oid represents an algorithm, a mechanism, a piece of information, etc.
nss tech note6
the following applies to nss 3.8 through 3.10 : on 32-bit solaris sparc (i.e., not x86, and not 64-bit sparc) and 32-bit hp-ux pa-risc (i.e., not itanium, and not 64-bit pa-risc), there are two more .chk files: libfreebl_pure32_3.chk and libfreebl_hybrid_3.chk.
... the following applies to nss 3.11 : the low-level freebl cryptographic code has been separated from softoken on all platforms.
nss tech note7
data types nss uses the following data types to represent keys: seckeypublickey: a public key, defined in "keythi.h".
...here is the asn.1 type definition: rsapublickey ::= sequence { modulus integer, -- n publicexponent integer -- e } the following sample code (error handling omitted for brevity) encodes a rsapublickey from a modulus and a public exponent and imports the public key into nss.
Overview of NSS
nss provides a complete open-source implementation of the crypto libraries used by aol, red hat, google, and other companies in a variety of products, including the following: mozilla products, including firefox, thunderbird, seamonkey, and firefox os.
... interoperability and open standards you can use nss to support a range of security standards in your application, including the following: ssl v3.
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
certificates and keys are often looked up by the following methods: by looking up all private keys.
...symmetric operations supported by nss include the following: ckm_aes_xxx, ckm_des3_xxx, ckm_des_xxx, ckm_rc2_xxx, and ckm_rc4_xxx.
PKCS11 Implement
random-number generation and simple digesting the nss requires that the following functions operate without authenticating to the token: c_seedrandom, c_generaterandom, and c_digest (for sha, md5, and md2).
... read/write and read-only requirements the nss assumes that the following operations always require a read/write session: creating a token object, such as with c_createobject (token) or c_destroyobject (token) changing a password initializing a token creating session objects must work with a read-only session.
FC_InitToken
syntax ck_rv fc_inittoken( ck_slot_id slotid, ck_char_ptr ppin, ck_ulong ulpinlen, ck_char_ptr plabel ); parameters fc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description fc_inittoken() initializes a brand new token or re-initializes a token that was initialized before.
... return value fc_inittoken() returns the following return codes.
FC_Initialize
the pinitargs argument must point to a ck_c_initialize_args structure whose members should have the following values: createmutex should be null.
...return value fc_initialize returns the following return codes.
NSC_InitToken
syntax ck_rv nsc_inittoken( ck_slot_id slotid, ck_char_ptr ppin, ck_ulong ulpinlen, ck_char_ptr plabel ); parameters nsc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description nsc_inittoken() initializes a brand new token or re-initializes a token that was initialized before.
... return value nsc_inittoken() returns the following return codes.
NSS_Initialize
the flags parameter is a bitwise or of the following flags: nss_init_readonly - open the databases read only.
...the following limitation applies when this is set : secmod_waitforanytokenevent will not use c_waitforslotevent, in order to prevent the need for c_finalize.
NSS tools : certutil
nss recognizes the following prefixes: · sql: requests the newer database · dbm: requests the legacy database if no prefix is specified the default type is retrieved from nss_default_db_type.
... the contexts are the following: · c (as an ssl client) · v (as an ssl server) · l (as an ssl ca) · a (as any ca) · y (verify ca) · s (as an email signer) · r (as an email recipient) · o (as an ocsp status responder) · j (as an object signer) -v valid-months set the number of mo...
gtstd.html
the following sections decribe how to the certificate database tool to perform these tasks: setting up the ca db and certificate setting up the server db and certificate setting up the client db and certificate verifying the server and client certificates warning: the instructions below illustrate the use of nss command line tools to operate a simple root certificate authority for test purposes onl...
...in addition, you must use the following compiler flags: solaris flags: -c -o -kpic -dsvr4 -dsysv -d__svr4 -d__svr4__ -dsolaris -d_reentrant -dsolaris2_5 -d_svid_gettod -dxp_unix -udebug -dndebug windows nt flags: -c -o2 -md -w3 -nologo -d_x86_ -gt -dwinnt -dxp_pc -udebug -u_debug -dndebug -dwin32 -d_windows ...
sslintro.html
functions used in the initialization part of an application can include the following: pr_init.
... functions that can be used by both clients and servers during communication include the following: pr_send or pr_write pr_read or pr_recv pr_geterror pr_getpeername pr_sleep pr_malloc pr_free pr_poll pr_now pr_intervaltomilliseconds pr_millisecondstointerval pr_shutdown pr_close ssl_invalidatesession after establishing a connection, an application first calls pr_send, pr_recv, pr_read, pr_write, or ssl_forcehandshake to initiate the handshake.
NSS_3.12.3_release_notes.html
bugs fixed the following bugs have been fixed in nss 3.12.3.
...new and revised documents available since the release of nss 3.11 include the following: build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.3 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS Tools pk12util
certkeylen] [common-options] or pk12util -l p12file [-h tokenname] [-r] [common-options] where [common-options] = [-d dir] [-p dbprefix] [-k slotpasswordfile | -k slotpassword] [-w p12filepasswordfile | -w p12filepassword] syntax to run the pkcs #12 tool, type ther command pk12util option [arguments] where option and arguments are combinations of the options and arguments listed in the following section.
... error codes pk12util can return the following values: 0 - no error 1 - user cancelled 2 - usage error 6 - nls init error 8 - certificate db open error 9 - key db open error 10 - file initialization error 11 - unicode conversion error 12 - temporary file creation error 13 - pkcs11 get slot error 14 - pkcs12 decoder start error 15 - error read from import file 16 - pkcs12 decode error 17 - pkcs12 decoder verify error 18 - pkcs12 decoder valida...
NSS tools : signtool
extended examples the following example will do this and that listing available signing certificates you use the -l option to list the nicknames for all available certificates and check which ones are signing certificates.
...in the following example, the user input is in boldface: signtool -g mytestcert using certificate directory: /u/someuser/.netscape enter certificate information.
Necko Architecture
necko provides the following libraries: necko - core networking functionality.
... dependencies necko requires the following libraries for linking: nspr xpcom original document information author(s): jud valeski last updated date: november 8, 1999 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details.
Rhino shell
the following properties of the option object are processed: args - provides an array of additional command arguments env - explicit environment object.
... $ java org.mozilla.javascript.tools.shell.main -e "print('hi')" hi $ java org.mozilla.javascript.tools.shell.main js> print('hi') hi js> 6*7 42 js> function f() { return a; } js> var a = 34; js> f() 34 js> quit() $ cat echo.js for (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.main echo.js foo bar foo bar $ spawn and sync the following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test.
SpiderMonkey Internals
if (eval(sumofdivisors[divisor]) == divisor) { print("" + divisor + " = " + sumofdivisors[divisor]); } } delete sumofdivisors; print("that's all."); } the line number to pc and back mappings can be tested using the js program with the following script: load("perfect.js"); print(perfect); dis(perfect); print(); for (var ln = 0; ln <= 40; ln++) { var pc = line2pc(perfect, ln); var ln2 = pc2line(perfect, pc); print("\tline " + ln + " => pc " + pc + " => line " + ln2); } the result of the for loop over lines 0 to 40 inclusive is: line 0 => pc 0 => line 16 line 1 => pc 0 => line 16 line 2 => pc 0 => line 16 line 3 => pc 0 => ...
...all of the following happen here: creating objects by class and prototype, and finalizing objects; defining, looking up, getting, setting, and deleting properties; creating and destroying properties and binding names to them.
JSClass.flags
its value is the logical or of zero or more of the following constants: flag meaning jsclass_has_private this class uses private data.
... an object obj that emulates undefined behaves like any other object, except in the following ways: typeof obj === "undefined" obj converts to false when obj is converted to a boolean when used in boolean contexts (if conditions, loop continuation/termination conditions [for/while/do { } while], the condition in a ternary ?: expression, and so on) (obj == undefined) is true, and (obj != undefined) is false (obj == null) is true, and (obj != null) is false ...
JS_PushArguments
format const char * null-terminated string holding a list of format types to convert the following arguments to.
...format can contain one or more instances of the following characters, as appropriate: character argument type b jsbool c uint16 (16-bit, unsigned integer) i int32 (32-bit, ecma-compliant signed integer) u uint32 (32-bit, ecma-compliant, unsigned integer) j int32 (32-bit, signed integer) d jsdouble i jsdouble (converted to an integer value) s char ...
JS_SET_TRACING_DETAILS
description set debugging information about a reference to a traceable thing to prepare for the following call to js_calltracer.
...the storage for name or callback's arguments needs to live only until the following call to js_calltracer returns.
SpiderMonkey 1.8.8
migrating to spidermonkey 1.8.8 the following features in earlier versions of spidermonkey have been dropped.
...6_t, int16_t, uint32_t, int32_t, uint64_t, int64_t mozilla/stdint.h uintn, intn unsigned (also known as unsigned int), int n/a jsdouble double n/a jsuintn, jsintn unsigned (also known as unsigned int), int n/a jspackedbool n/a n/a jsrefcount n/a n/a the fixed-size integer types are defined in one of the following ways: if the environment variable moz_custom_stdint_h is set, that file will be included to provide definitions for these types.
SpiderMonkey 17
migrating to spidermonkey 17 the following features in earlier versions of spidermonkey have been dropped.
...6_t, int16_t, uint32_t, int32_t, uint64_t, int64_t mozilla/stdint.h uintn, intn unsigned (also known as unsigned int), int n/a jsdouble double n/a jsuintn, jsintn unsigned (also known as unsigned int), int n/a jspackedbool n/a n/a jsrefcount n/a n/a the fixed-size integer types are defined in one of the following ways: if the environment variable moz_custom_stdint_h is set, that file will be included to provide definitions for these types.
SpiderMonkey 24
the following features in earlier versions of spidermonkey have been dropped.
... typedef changes the fixed-size integer types introduced in spidermonkey 17 are defined in one of the following ways (xxx update for msvc<10 deprecation): if the environment variable moz_custom_stdint_h is set, that file will be included to provide definitions for these types.
TPS Bookmark Lists
all bookmark paths must begin with one of the following: "menu": the normal bookmarks menu "toolbar": the bookmarks toolbar "tags": the tags folder "unfiled": the unfiled bookmarks folder "places": the places root folder ("menu", "toolbar", and "unfiled" are all children of this) sub-folders are preceded with forward slashes, so "menu/folder1" denotes that "folder1" is a sub-folder of "menu".
...h of the folder that this separator should be moved to position: the title of the existing bookmark item, in the current folder, where this separator should be moved to (i.e., this separator would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below this separator) example: { separator: true } bookmark lists and phase actions following are the functions you can use in phase actions related to bookmarks: bookmarks.add - the bookmark items in the list are added to the end of their parent folder in the specified order.
TPS Formdata Lists
a formdata asset list is an array of objects, each with the following properties: fieldname: required.
... for example: var formdata1 = [ { fieldname: "testing", value: "success", date: -1 }, { fieldname: "testing", value: "failure", date: -2 }, { fieldname: "username", value: "joe" } ]; formdata lists and phase actions you can use the following functions in phase actions for formdata lists: formdata.add formdata.delete formdata.verify formdata.verifynot for an example, see the tps formdata unittest: http://hg.mozilla.org/services/tps/f...st_formdata.js notes note 1, tps supports the delete action for formdata, but sync currently does not correctly sync deleted form data, see bug 564296.
TPS Password Lists
assword_list = [ { hostname: "http://www.example.com", submiturl: "http://login.example.com", username: "joe", password: "secret123", usernamefield: "uname", passwordfield: "pword", changes: { password: "zippity-do-dah" } }, { hostname: "http://www.example.com", realm: "login", username: "joe", password: "secretlogin" } ]; each object has the following properties: hostname: the hostname for the password.
... password lists and phase actions following are the functions that can be used in phase actions related to passwords: passwords.add passwords.delete passwords.modify passwords.verify passwords.verifynot ...
TPS Tab Lists
a tabs asset list is an array of objects with the following keys: uri: the uri of the tab, required.
... uri: "http://hg.mozilla.org/automation/crossweave/raw-file/2d9aca9585b6/pages/page1.html", title: "crossweave test page 1", profile: "profile1" }, { uri: "data:text/html,<html><head><title>hello</title></head><body>hello</body></html>", title: "hello", profile: "profile1" } ]; tab lists and phase actions tabs cannot be modified or deleted, only added or verified with the following functions: tabs.add - opens the specified tabs in the browser window.
Handling Mozilla Security Bugs
general policies mozilla.org has adopted the following general policies for handling bug reports related to security vulnerabilities: security bug reports can be treated as special and handled differently than "normal" bugs.
...each and every member of the mozilla security bug group will automatically have access to all mozilla bugs marked "security-sensitive." the members of the mozilla security bug group will be drawn primarily from the following groups: security developers (i.e., those whose bugs are often singled out as security-relevant or who have security-relevant bugs assigned to them), and security qa people who are the qa contacts for those bugs.
XUL Accessibility
name the following rules to generate accessible name are applied: check aria-labelledby attribute, name is generated from elements pointed by aria-labelledby attribute <description id="descr1">label1</description> <description id="descr2">label2</description> <textbox aria-labelledby="descr1 descr2" /> if the element implements nsidomxullabeledcontrolelement or nsidomxulselectcontrolitemelement interface then i...
... if the element is anonymous child of the element that is the direct child of toolbaritem element or the element is direct child of toolbaritem element then title attribute of toolbaritem element is used (currently it's used in firefox ui only) if the element has aria role and the role allows to aggregate name from subtree of element then generate name from subtree of the element description the following rules to generate accessible description are applied: check aria-describedby attribute, description is generated from elements pointed by aria-describedby attribute <description id="descr1">label1</description> <description id="descr2">label2</description> <textbox aria-describedby="descr1 descr2" /> if neighbour of the element has description element pointing to this element by the control...
Using the Places history service
when the user starts browsing (for example, by typing in a link or following a bookmark), a new session id is created.
...this means that one "session" is comprised of going to a new page, and following a bunch of links or redirects.
Using the Places keywords API
it has the following properties: keyword: string representing the keyword url: either a url or spec represeting the url to associate to postdata: optional post data string.
... fetching an entry by keyword the fetch() method acceps a keyword string (or an object having a keywords property) and might resolve to a keyword entry with the following properties: keyword: string representing the keyword url: the url represeted by the keyword postdata: optional post data string.
extIApplication
method overview boolean quit() boolean restart() void getextensions(extiextensionscallback acallback) attributes the following interfaces are available to all applications: attribute type description id readonly attribute astring the id of the application.
...supports: "load", "ready", "quit", "unload" the following interfaces are only available to firefox: attribute type description bookmarks readonly attribute fuelibookmarkroots the root bookmarks object for the application.
Generating GUIDs
com/xpcom format when #define-ing iids and cids in mozilla c++ code, you generally use the following format: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx #define ns_...id \ { 0xxxxxxxxx, 0xxxxx, 0xxxxx, \ { 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx } } you can generate code in this format using one of the following tools.
... bash you can put the following into your .bashrc file: uuidgen-c++() { local uuid=$(uuidgen) echo "// $uuid" echo "#define ns__iid \\" echo "{ 0x${uuid:0:8}, 0x${uuid:9:4}, 0x${uuid:14:4}, \\" echo -n " { 0x${uuid:19:2}, 0x${uuid:21:2}, 0x${uuid:24:2}, " echo -n "0x${uuid:26:2}, 0x${uuid:28:2}, 0x${uuid:30:2}, " echo "0x${uuid:32:2}, 0x${uuid:34:2} } }" } perl #!/usr/bin/perl $uuid = `uuidgen`; chomp $uuid; print $uuid, "\n"; @parts = ($uuid =~ /^(.{8})-(.{4})-(.{4})-(..)(..)-(..)(..)(..)(..)(..)(..)$/); print "{ 0x$parts[0], 0x$parts[1], 0x$parts[2], \\", "\n", " { "; for (3 ..
Generic factory
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 this class, simply write the following: nsifactory* newcomponentfactory(nsirepository* repository) { nsigenericfactory* factory = null; nscid kgenericfactorycid = ns_genericfactory_cid; nsresult res = repository->createinstance(kgenericfactorycid, null, nsigenericfactory::iid(), &factory); if (res == ns_ok) { factory->setconstructor(&mycomponent::create); } return factory; } this example assumes that...
...it seems to me that we can cut down on code size (all those queryinterface, addref, release implementations) if we just use the following class for all of the simple factories: // idea: why not create a generic factory facility so we can avoid // duplication of so much nsifactory code?
Avoiding leaks in JavaScript XPCOM components
the most common strategies for managing heap allocation are the following: malloc and free (or new and delete) the simplest strategy for heap allocation is that the programmer makes one function call to request memory from the heap and another one to return it.
... 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.
Preface
organization of the tutorial the following list provides an overview of the steps that we will take to build an xpcom component called weblock, which provides site blocking functionality to gecko-based browsers.
... following along with the examples there are a couple of different ways to get xpcom onto your machine so you can begin to create components.
Components.isSuccessCode
components.issuccesscode() is functionally equivalent to the following javascript: function issuccesscode(returncode) { return (returncode & 0x80000000) === 0; } since failure error codes are turned into exceptions when encountered in javascript, this function usually is not necessary.
... examples checking whether copying a stream's data succeeded the following example demonstrates copying data from a buffered nsiinputstream to an nsioutputstream, checking for whether the copy succeeded using components.issuccesscode().
Components.utils.Sandbox
this parameter is an object with the following optional properties: freshzone if true creates a new gc region separate from both the calling context's and the sandbox prototype's region.
... the following objects are supported: -promise (removed in firefox 37) css indexeddb (web worker only) xmlhttprequest textencoder textdecoder url urlsearchparams atob btoa blob file crypto rtcidentityprovider fetch (added in firefo...
HOWTO
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.
...sult: "0x80040111 (ns_error_not_available)" location: "js frame :: file.js :: <top_level> :: line 12" data: no] solution 1 var loader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); loader.loadsubscript("chrome://myall/content/file.jsm"); see: http://mxr.mozilla.org/comm-central/...figutils.js#54 solution 2 append the following at the top of your js file which you want to run in xpcshell { // <https://developer.mozilla.org/en/xpconnect/xpcshell/howto> // <https://bugzilla.mozilla.org/show_bug.cgi?id=546628> let cc = components.classes; let ci = components.interfaces; // register resource://app/ uri let ios = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice); let reshandler = ios.get...
XPCShell Reference
for instance, assume that you have a file called test.js with the following contents: for (prop in arguments) { print(prop + "=" + arguments[prop]); } entering the following at the command line should produce the following output: $ xpcshell test.js this is a test 0=this 1=is 2=a 3=test xpcshell extensions once you execute xpcshell without a script you'll be at the js> command line.
... the following are some useful functions that can be invoked from the command line: clear(object) clear() removes all properties from an object.
IAccessibleText
three" object would be 4, matching the embed character</li> the caretoffset for "two" would be 2, matching the "o" the caret position/offset is that of the character logically following it, for example to the right of it in a left to right language.
...the caret position/offset is that of the character logically following it, for example to the right of it in a left to right language.
imgIEncoder
apng: ----- the following options can be used with startimageencode(): transparency=[yes|no|none] -- default: "yes" overrides default from input format.
... the following options can be used for each frame, with addimageframe(): transparency=[yes|no|none] -- default: "yes" overrides default from input format.
nsIAppStartup
obsolete since gecko 1.9.1 constants the following flags may be passed as the amode parameter to the quit() method.
... return value a javascript object with the following fields.
nsIDOMMozNetworkStatsManager
it contains the following fields: starttime a date object representing the start time.
...it contains the following fields: appmanifesturl a string used to filter network stats by app.
getFile
the following sections cover these.
... c constant string value notes ns_unix_local_dir "locl" ns_unix_lib_dir "libd" ns_unix_home_dir ns_os_home_dir the following locations are provided only on os/2 builds of gecko.
Using nsILoginManager
getting nsiloginmanager to get a component implementing nsiloginmanager, use the following: var passwordmanager = components.classes["@mozilla.org/login-manager;1"].getservice( components.interfaces.nsiloginmanager ); most login manager functions take an nsilogininfo object as a parameter.
... an nsilogininfo object contains the following attributes: hostname, form submit url, http realm, username, username field, password, and password field.
Building an Account Manager Extension
therefore we add the following code to the previous.
... prefpanel-devmo-account=devmo demo panel step4: the new panel and javascript the javascript for an account manager panel needs to implement at least the following functions.
nsINavBookmarkObserver
when a new item is created, all the items following it in the same folder will have their index shifted down, but no additional notifications will be sent.
...when an item is removed, all the items following it in the same folder will have their index shifted down, but no additional notifications will be sent.
nsINavHistoryService
it declares that the given uri is being opened as a result of following a bookmark.
... if this uri is loaded soon after this message has been received, that transition will be marked as following a bookmark.
nsIPromptService
lean acheckstate); boolean promptpassword(in nsidomwindow aparent, in wstring adialogtitle, in wstring atext, inout wstring apassword, in wstring acheckmsg, inout boolean acheckstate); boolean select(in nsidomwindow aparent, in wstring adialogtitle, in wstring atext, in pruint32 acount, [array, size_is(acount)] in wstring aselectlist, out long aoutselection); constants the following flags are combined to form the abuttonflags parameter passed to confirmex.
...the following example creates a dialog with an ok button and a custom button description.
nsIProxyInfo
some special values for this attribute include (but are not limited to) the following: "http" - http proxy (or ssl connect for https) "socks" - socks v5 proxy "socks4" - socks v4 proxy "direct" - no proxy "unknown" - unknown proxy (see nsiprotocolproxyservice.resolve()) a future version of this interface may define additional types.
... constants the following "proxy flags" may be bit-wise combined to construct the flags attribute defined on this interface.
nsIScriptableIO
this should be one of the following types: nsifile: an object returned by getfile() or getfilewithpath(), or any object implementing the nsifile interface.
...this should be one of the following types: nsifile: an object returned by getfile() or getfilewithpath(), or any object implementing the nsifile interface.
nsITransport
flags have the following meaning: open_blocking if specified, then the resulting stream will have blocking stream semantics.
...flags have the following meaning: open_blocking if specified, then the resulting stream will have blocking stream semantics.
nsIWindowMediator
getting most recent window the following code is useful when you need any of the windows of given type, or to check if a window of a particular type (for example your extension's options dialog) is already open.
... win.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem).treeowner .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsixulwindow) enumerating windows the following code can be used if you need to do something for each open window of a particular type.
nsIWindowWatcher
for example the following code will block the system because it will open windows continuously: function mywindowobserver() { this.observe=function(asubject, atopic, adata) { alert("window event: " + atopic) //and this is where the bugs origins because opening this alert will cause a window-open //event and the call of this method again (forever) } } var ww = components.classes["@mozilla.org/embedcomp/win...
...aobserver should implement an observe method, which will be called with the following parameters: asubject - the window being opened or closed, sent as an nsisupports which can be nsisupports.queryinterface() (queryinterfaced) to an nsidomwindow.
Reference Manual
you can construct an nscomptr from, or assign into it any of the following the value 0 another nscomptr of the same type a raw xpcom interface pointer of the same type a raw xpcom interface pointer of the same type, annotated with the dont_queryinterface directive a raw xpcom interface pointer of the same type, annotated with the dont_addref directive or a synonym any interface pointer (either nscomptr or a raw xpcom interface pointer) of any type, annotate...
...by following the optimization tips in this section, you will write code that generates fewer bytes of object than you might with raw pointers.
Using the clipboard
the clipboard model in mozilla requires you to perform the following steps to copy data: create an xpcom wrapper for the data which you want to put on the clipboard.
... the following boilerplate utility functions will be used in all later code examples.
Weak reference
in the following example, an nsobservable must keep some kind of a reference to each observer, in order to report events.
... the following assumes that any nsiobserver that is passed in also implements nsisupportsweakreference.
XPCOM ABI
abi naming each abi is named with a string [target_xpcom_abi] of the following format: {cpu_arch}-{target_compiler_abi} {cpu_arch} [platforms] represents the cpu architecture and may be either: x86 - i386 and higher series (including x86-64 cpus in 32-bit mode) ppc - powerpc series alpha - alpha series x86_64 - amd64/emt64 series in 64-bit mode (32-bit mode is still considered x86) sparc - sparc series ia64 - itanium series {target_compiler_abi}[platforms] repr...
...to retrieve the abi of your firefox or thunderbird, open the error console (accessible through tools | error console) and evaluate the following javascript code: components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime) .xpcomabi if either the cpu architecture or the c++ compiler are unknown, the application wouldn't have an xpcom abi string and attempts to get it will result in error ns_error_not_available.
Xptcall Porting Guide
the invoke functionality requires the implementation of the following on each platform (from xptcall/public/xptcall.h): xptc_public_api(nsresult) ns_invokebyindex(nsisupports* that, pruint32 methodindex, pruint32 paramcount, nsxptcvariant* params); calling code is expected to supply an array of nsxptcvariant structs.
...#include "xptcstubsdecl.inc" // the following methods must be provided by inheritor of this class.
XPIDL
the following is the correspondence table: table 1: standard idl types idl c++ in parameter c++ out parameter js type notes boolean bool bool* boolean char char char* string only chars in range \u0000-\u00ff permitted double double double* number float float float* number long int32_t ...
... in addition to this list, nearly every idl file includes nsrootidl.idl in some fashion, which also defines the following types: table 2: types provided by nsrootidl.idl idl typedef c++ in parameter c++ out parameter js type notes prtime (xpidl unsigned long long typedef, 64 bits) number prtime is in microseconds, while js date assumes time in milliseconds nsresult (xpidl unsigned long typedef, 32 bits) number nsrefcnt (xpidl unsigned long t...
The Valgrind Test Job
add the following lines to your mozconfig file.
... ac_add_options --enable-valgrind ac_add_options --disable-jemalloc running to run the valgrind test job locally, run the following command.
Address book sync client design
the general architecture for the sync component is the following: mozilla ui ab sync logic mork ab database sync protocol encoding sync protocol decoding http "post" api mozilla networking clie...
... // // the client keeps a sync mapping table which holds the following: // // serverrecordid - unique id for a record provided by the // uab server.
The libmime module
there is one header file and one source file for each class (for example, the mimeinlinetext class is defined in "mimetext.h" and "mimetext.c".) each header file follows the following boiler-plate form: typedefs these come first to avoid circular dependencies.
... }; then, in the corresponding .c file, the following structure is used: class definition first we pull in the appropriate include file (which includes all necessary include files for the parent classes) and then we define the class object using the mimedefclass macro: #include "foobar.h" #define mime_superclass parentlclass mimedefclass(foobar, foobarclass, foobarclass, &mime_superclass); the definition of mime_superclass is just ...
Building a Thunderbird extension 3: install manifest
open the file called install.rdf that you created at the top of your extension's directory hierarchy and paste the following text into the file: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>myfirstext@jen.zed</em:id> <em:name>my first extension</em:name> <em:version>1.0</em:version> <em:creator>jenzed</em:creator> <em:targetapplication> <description> <em:id>{3550f703-e5...
...82-4d05-9a08-453d09bdfdc6}</em:id> <em:minversion>1.5</em:minversion> <em:maxversion>5.0.*</em:maxversion> </description> </em:targetapplication> </description> </rdf> the following items (shown in bold) should be customized for your application: <em:id>myfirstext@jen.zed</em:id>: this is the id of the extension.
Working with windows in chrome code
the following two subsections describe how to cross chrome-content boundaries in either way, i.e.
...this can be done using the following statement: var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(compon...
Zombie compartments
any compartments with the following forms are created by firefox for its own internal use, and can usually be ignored when looking for zombie compartments.
... for example, if i open www.techcrunch.com the following compartments are created.
Add to iPhoto
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': ctypes.int32_t}, {'length': ctypes.int32_t}]); this defines corefoundation.cfrange to represent this data type, comprised of two 32-bit integer fields called location and length.
...we do that next by following these steps: create a cfstring referring to file:///applications/iphoto.app, which is iphoto's default path, using cfstringcreatewithcharacters().
Standard OS Libraries
to call objective-c based api from ctypes, use the following functions in libobjc.dylib: objc_getclass to get class sel_registername to register selector name objc_msgsend and some variants to send message to class and instance objective-c code can be translated into c code by the following rule: // objective-c code nsevent loc = [nsevent mouselocation]; // pseudo c code nsevent loc = (nspoint)objc_msgsend(objc_getclass("nsevent"), ...
...this article links to a fully funcitonal demo that can be copied and pasted into scratchpad, as a quick reference here is the link to that demo: following the android toasts tutorial from a jni prespective.
PKCS #11 Netscape Trust Objects - Network Security Services
conceptually a trust object contains the following: certificate reference purpose + level of trust (multiple) purpose + level of trust a trust object ultimately denotes a level of trust in a certificate.
... trust objects are of the class cko_netscape_trust and have the following attributes.
Drawing and Event Handling - Plugins
processes that apply to only one of these plug-in types are described in the following sections.
... see the following items for more information on controlling the drawing of the plug-in instance: specifying that a plug-in is windowless invalidating the drawing area forcing a paint message making a plug-in opaque making a plug-in transparent creating pop-up menus and dialog boxes event handling for windowless plug-ins specifying that a plug-in is windowless to specify that a plug-in is windowless, us...
URLs - Plugins
posting data to an http server the following code posts two name-value pairs to a cgi script through http.
...the following code sends a mail message with the default headers from the client machine.
Color vision simulation - Firefox Developer Tools
in the simulate menu, you can choose one option at a time from the following list: none — choose this to return to normal display protanomaly (low red) deuteranomaly (low green) tritanomaly (low blue) protanopia (no red) deuteranopia (no green) tritanopia (no blue) contrast loss these simulations are not completely medically accurate.
... the following table shows a colorful image of a cat's face, and what it looks like in the various simulations.
Accessibility Inspector - Firefox Developer Tools
starting in firefox 79, it is automatically enabled when you do one of the following: choose accessibility in the tools > web developer menu.
... in the following example, you can see that the image has been highlighted and its role, graphic, name, "road, asphalt, sky, clouds, fall", and the color contrast ratio, 3.46, appears in the information bar above it.
Inspecting web app manifests - Firefox Developer Tools
when you open the application panel’s manifest view on a page that doesn't have an app manifest successfully deployed, you'll get the following output shown: deploying a manifest to get a manifest deployed successfully, you need to include a <link> element in the <head> of your document that points to your .webmanifest file: <link rel="manifest" href="/manifest.webmanifest"> the .webmanifest extension is recommended in the spec, and should be served with an application/manifest+json mime type, although browsers generally tend to support manifests with other appropriate extensions like .json (mime type: application/json).
... inspecting your manifest if your manifest is deployed successfully, you should end up with a display like the following on the manifest view: from here, you can inspect all the information in the manifest in an easy-to-digest way, making sure that it is all correct.
Debugging service workers - Firefox Developer Tools
when you open the application panel’s service workers view on a page that doesn't have a service worker registered, 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!
... the server worker’s status, which can be one of the following: stopped: the service worker is installed, but not currently running.
Browser Console - Firefox Developer Tools
the following image shows the browser console focused on the same page as above after clicking on the show content messages checkbox.
...on windows, the following code will add a new item to the browser's main menu: var parent = window.document.getelementbyid("appmenuprimarypane"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makethetea.setattribute("label", "a nice cup of tea?"); parent.appendchild(makethetea); on macos, this similar code will a...
Break on DOM mutation - Firefox Developer Tools
click on the icon following the node name to go back to the page inspector with the node selected.
...in the following example, the selected node (the unordered list) is modified by adding a new child node.
Debugger.Environment - Firefox Developer Tools
accessor properties of the debugger.environment prototype object a debugger.environment instance inherits the following accessor properties from its prototype: inspectable true if this environment is a debuggee environment, and can therefore be inspected.
... type the type of this environment object, one of the following values: “declarative”, indicating that the environment is a declarative environment record.
Debugger.Object - Firefox Developer Tools
accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent’s prototype (as a new debugger.object instance), or null if it has no prototype.
...this string takes one of the following values: "pending", if the promise is pending.
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
(this menu will not be present unless you have changed the preference as explained above.) selecting the 'browser' context in the scratchpad enter the following code in the scratchpad: // this simply defines the 'debugger' constructor in this // scratchpad; it doesn't actually start debugging anything.
...(if you get an error complaining that components.utils is not defined, be sure you've selected browser from the scratchpad's environment menu, as described in step 2.) save the following html text to a file, and visit the file in your browser.
Tutorial: Set a breakpoint - Firefox Developer Tools
save the following text to an html file: <div onclick="report('the best div');">click me!</div> <div onclick="report('another great div');">or me!</div> <script> function report(what) { console.log('clicked: ' + what); } </script> visit the html file in your browser, and open the browser content toolbox by opening the firefox menu, choosing “web developer”, and then “browser content toolbox”.
... click on the scratchpad panel and enter the following code: components.utils.import("resource://gre/modules/jsdebugger.jsm"); components.utils.import("resource://gre/modules/console.jsm"); // this simply defines 'debugger' in this scratchpad; // it doesn't actually start debugging anything.
Debugger.Object - Firefox Developer Tools
accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent's prototype (as a new debugger.object instance), or null if it has no prototype.
...ifhandler is null, the referent is no longer watched.handler may have the following methods, called under the given circumstances: add(frame,name,descriptor) a property namedname has been added to the referent.descriptor is a property descriptor of the sort accepted by debugger.object.prototype.defineproperty, giving the newly added property's attributes.
Page inspector 3-pane mode - Firefox Developer Tools
when activated, this allows you to see the following simultaneously: the html pane on the left hand side, as usual.
... enabling the 3-pane inspector pre-firefox 62 in earlier versions of firefox (since firefox 59/60), you can enable 3 pane mode in release/beta by going to about:config and flipping the following prefs to true: devtools.inspector.split-rule-enabled — this switches 3-pane mode on and off.
Edit fonts - Firefox Developer Tools
empty elements will not have any fonts used and will display the message "no fonts were found for the current element." fonts will be included in this section for one of the following reasons: they are listed in the element's font-family css declaration value.
... here are a couple of examples of fonts with different axes defined: in the following example, you can see that the font "cheee variable" includes settings for yeast and gravity.
UI Tour - Firefox Developer Tools
the following image shows the 2-pane layout: in 2-pane mode, the inspector includes the html pane, and the css pane, which can contain one of six tools: rules view layout view computed view changes view compatibility view (firefox developer edition 77 and later) fonts view animations view the following image shows the 3-pane mode (available from firefox 62 onwards) which moves the css rules view ...
...the following image shows 3-pane mode: as you can see, the css pane has moved into the center of the inspector.
Responsive Design Mode - Firefox Developer Tools
on the right end of the screen, three buttons allow you to: camera button - take a screenshot settings button - opens the rdm settings menu close button - closes rdm mode and returns to regular browsing the settings menu includes the following commands: left-align viewport - when checked moves the rdm viewport to the left side of the browser window show user agent - when checked displays the user agent string the final two options define when the page is reloaded: reload when touch simulation is toggled: when this option is enabled, the page is reloaded whenever you toggle touch support.
...select a device, and responsive design mode sets the following properties to match the selected device: screen size device pixel ratio (the ratio of device physical pixels to device-independent pixels) touch event simulation additionally, firefox sets the user-agent http request header to identify itself as the default browser on the selected device.
Cookies - Firefox Developer Tools
the cookies table has the following columns: name — the name of the cookie.
... context menu the context menu for each cookie includes the following commands: add item - add a new cookie.
IndexedDB - Firefox Developer Tools
databases have the following details: database name — the name of the database.
...any object store has the following details: object store name — the name of the object store.
Storage Inspector - Firefox Developer Tools
currently it can be used to inspect the following storage types: cache storage — any dom caches created using the cache api.
... working with the storage inspector the following articles cover different aspects of using the network monitor: cookies local storage / session storage cache storage indexeddb extension storage ...
Toolbox - Firefox Developer Tools
the array may include the following tools: web console javascript debugger page inspector style editor profiler network monitor note that not all the hosted tools are always listed here: only the tools actually available in this context are shown (for example, not all tools support remote debugging yet, so if the debugging target is not the firefox instance that launched the window, not all the hosted tools will be shown)...
... the following tools are not included in the toolbar by default, but you can add them in the settings: highlight painted area 3d view (note that this is not available in firefox 40) scratchpad grab a color from the page take a screenshot of the entire page: take a screenshot of the complete web page and saves it in your downloads directory toggle rulers for the page measure a portion of the page: measure a part of the website by selecting areas within the page toolbox controls finally there...
Web Console Helpers - Firefox Developer Tools
you can supply any of the following: a selector string to be passed to document.queryselector to locate the iframe element the iframe element itself the content window inside the iframe see working with iframes.
...if you don't supply a filename, the image file will be named with the following format: screen shot yyy-mm-dd at hh.mm.ss.png the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard.
Rich output - Firefox Developer Tools
in particular, it: provides extra information for certain types enables detailed examination of the object's properties provides richer information for dom elements, and enables you to select them in the inspector type-specific rich output the web console provides rich output for many object types, including the following: object array date promise regexp window document element event examining object properties when an object is logged to the console it has a right-pointing triangle next to it, indicating that it can be expanded.
...for example, by expanding the array in the above list, i get the following: console.log(todolist) (4) […] ​ 0: object { status: "done", description: "morning pages", datecreated: 1552404478137 } ​ 1: object { status: "in progress", description: "refactor styles", datecreated: 1552404493169 } ​ 2: object { status: "to do", description: "create feedback form", datecreated: 1552404512630 } ​ 3: object { status: "to do", description: "normalize table", datecreate...
The JavaScript input interpreter - Firefox Developer Tools
you can supply any of the following: a selector string that will be passed to document.queryselector to locate the iframe element the iframe element itself the content window inside the iframe see working with iframes.
...if you don't supply a filename, the image file will be named: screen shot yyy-mm-dd at hh.mm.ss.png the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard.
AbstractRange - Web APIs
if we wish to instead copy the text "an interesting thing..." from the <section>'s heading (an <h2> element) through the end of the letters "ve" in the <em> within the paragraph below it, the following code would work: let r = document.createrange(); let startnode = document.queryselector("section h2").childnodes[0]; r.setstart(startnode, 11); let endnode = document.queryselector("#entry1 p em").childnodes[0]; r.setend(endnode, 2); let fragment = r.clonecontents(); here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the dom hiera...
...the code to do that looks like the following: let paranode = document.queryselector("p"); let paratextnode = paranode.childnodes[1]; let range = document.createrange(); range.setstart(paratextnode, 6); range.setend(paratextnode, paratextnode.length-1); let fragment = range.clonecontents(); document.body.appendchild(fragment); first we get references to the paragraph node itelf as well as to the second child node within the paragraph.
AnalyserNode - Web APIs
number of inputs 1 number of outputs 1 (but may be left unconnected) channel count mode "max" channel count 2 channel interpretation "speakers" inheritance this interface inherits from the following parent interfaces: <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" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1"...
... basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
Animation.finish() - Web APIs
WebAPIAnimationfinish
examples the following example shows how to use the finish() method and catch an invalidstate error.
... interfaceelement.addeventlistener("mousedown", function() { try { player.finish(); } catch(e if e instanceof invalidstate) { console.log("finish() called on paused or finished animation."); } catch(e); logmyerrors(e); //pass exception object to error handler } }); the following example finishes all the animations on a single element, regardless of their direction of playback.
AnimationEffect.getComputedTiming() - Web APIs
although many of the attributes of the returned object are common to the effecttiming contained in the object returned by the animationeffect.gettiming() method, the values returned by this object differ in the following ways: duration returns the calculated value of the iteration duration.
... return value a computedeffecttiming dictionary object, which contains the following properties: endtime the end time of the animation in milliseconds from the animation's start (if the keyframeeffect is associated with an animation).
Attr - Web APIs
WebAPIAttr
deprecated properties and methods the following properties have been deprecated.
... the following methods have been deprecated: appendchild() obsolete since gecko 14 modify the value of attr.value instead.
AudioBuffer - Web APIs
the buffer contains data in the following format: non-interleaved ieee754 32-bit linear pcm with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0.
... example the following simple example shows how to create an audiobuffer and fill it with random white noise.
AudioContext.getOutputTimestamp() - Web APIs
returns an audiotimestamp object, which has the following properties.
... performancetime: a point in the time coordinate system of a performance interface; the time after the document containing the audio context was first rendered examples in the following code we start to play an audio file after a play button is clicked, and start off a requestanimationframe loop running, which constantly outputs the contexttime and performancetime.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
syntax var authnrdata = authenticatorassertionresponse.authenticatordata; value an arraybuffer that has a arraybuffer.bytelength of at least 37 bytes, containing the following fields: rpidhash (32 bytes) - a sha256 hash of the relying party id that was seen by the browser.
...this is a sequence of bytes with the following format: aaguid (16 bytes) - authenticator attestation globally unique identifier, a unique number that identifies the model of the authenticator (not the specific instance of the authenticator) so that a relying party can understand the characteristics of the authenticator by looking up its metadata statement.
BaseAudioContext.createGain() - Web APIs
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
...tegain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
BaseAudioContext.createScriptProcessor() - Web APIs
if specified, the buffersize must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384.
... example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode.
CSS.registerProperty() - Web APIs
syntax css.registerproperty(propertydefinition); parameters a propertydefinition dictionary object, which can contain the following members: name a domstring indicating the name of the property being defined.
... examples the following will register a custom property, --my-color, using registerproperty(), as a color, give it a default value, and have it not inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); in this example, the custom property --my-color has been registered using the syntax <color> .
Using the CSS properties and values API - Web APIs
css.registerproperty the following will register a css custom properties, --my-prop, using css.registerproperty, as a color, give it a default value, and have it not inherit its value: window.css.registerproperty({ name: '--my-prop', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); @property the same registration can take place in css.
... the following will register a css custom properties, --my-prop, using @property, as a color, give it a default value, and have it not inherit its value: @property --my-prop { syntax: '<color>'; inherits: false; initial-value: #c0ffee; } using registered custom properties one of the advantages of registering a property is that the browser now knows how it should handle your custom property through things like transitions!
Advanced animations - Web APIs
the following code will set us up.
...to do so, we add the following checks to the draw method: if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } first demo let's see how it looks in action so far.
Hit regions and accessibility - Web APIs
the following guidelines can help to make it more accessible.
...the api has the following three methods (which are still experimental in current web browsers; check the browser compatibility tables).
Transformations - Web APIs
the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled.
... ctx.save(); ctx.scale(10, 3); ctx.fillrect(1, 10, 10, 10); ctx.restore(); // mirror horizontally ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.filltext('mdn', -135, 120); } <canvas id="canvas" width="150" height="150"></canvas> draw(); screenshotlive sample transforms finally, the following transformation methods allow modifications directly to the transformation matrix.
Using images - Web APIs
getting images to draw the canvas api is able to use any of the following data types as an image source: htmlimageelement these are images created using the image() constructor, as well as any <img> element.
... example: a simple line graph in the following example, we will use an external image as the backdrop for a small line graph.
ClipboardItem - Web APIs
constructor clipboarditem.clipboarditem() creates a new clipboarditem object, with the mime type as the key and blob as the value properties this interface provides the following properties.
... methods this interface defines the following methods.
CloseEvent - Web APIs
the following values are permitted status codes.
... the following definitions are sourced from the iana website [ref].
console - Web APIs
WebAPIConsole
console.group() creates a new inline group, indenting all following output by another level.
... console.groupcollapsed() creates a new inline group, indenting all following output by another level.
Constraint validation API - Web APIs
examples take the following form: <form> <label for="name">enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[a-za-z]+"> <button>submit</button> </form> the basic html form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern.
... if you wanted to instead display custom error messages, you could use javascript like the following: const nameinput = document.queryselector('input'); const form = document.queryselector('form'); nameinput.addeventlistener('input', () => { nameinput.setcustomvalidity(''); nameinput.checkvalidity(); }); nameinput.addeventlistener('invalid', () => { if(nameinput.value === '') { nameinput.setcustomvalidity('enter your username!'); } else { nameinput.setcustomvalidity('usernames can only contain upper and lowercase letters.
ContentIndex.add() - Web APIs
WebAPIContentIndexadd
syntax contentindex.add(contentdescription).then(...); parameters contentdescription the item registered is an object containing the following data: id: a unique string identifier.
... homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image.
ContentIndex.getAll() - Web APIs
contentdescription each item returned is an object containing the following data: id: a unique string identifier.
... homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image.
Content Index API - Web APIs
service worker additions the following additions to the serviceworker have been specified in the content index api spec to provide an entry point for using content indexing.
... examples all the following examples assume a service worker has been registered.
CustomElementRegistry.define() - Web APIs
examples autonomous custom element the following code is taken from our popup-info-box-web-component example (see it live also).
... customized built-in element the following code is taken from our word-count-web-component example (see it live also).
DisplayMediaStreamConstraints.video - Web APIs
the value may be a single one of the following strings, or an array of them to allow the browser flexibility in deciding what to do about the cursor.
...this may be a single one of the following strings, or a list of them to allow multiple source surfaces: application the stream contains all of the windows of the application chosen by the user rendered into the one video track.
Document.createElement() - Web APIs
ent("div"); // and give it some content const newcontent = document.createtextnode("hi there and greetings!"); // add the text node to the newly created div newdiv.appendchild(newcontent); // add the newly created element and its content into the dom const currentdiv = document.getelementbyid("div1"); document.body.insertbefore(newdiv, currentdiv); } web component example the following example snippet is taken from our expanding-list-web-component example (see it live also).
... } } // define the new element customelements.define('expanding-list', expandinglist, { extends: "ul" }); if we wanted to create an instance of this element programmatically, we'd use a call along the following lines: let expandinglist = document.createelement('ul', { is : 'expanding-list' }) the new element will be given an is attribute whose value is the custom element's tag name.
Document.createTouch() - Web APIs
note: previous versions of this method included the following additional parameters but those parameters are not included in either of the standards listed below.
... in following code snippet, two touch objects are created for the target element.
Document.getElementsByTagNameNS() - Web APIs
example in the following example getelementsbytagnamens starts from a particular parent element, and searches topdown recursively through the dom from that parent element, looking for child elements matching the tag name parameter.
... to use the following example, just copy/paste it into a new file saved with the .xhtml extension.
Document.open() - Web APIs
WebAPIDocumentopen
examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again.
... this call, for example opens github.com in a new window, with its opener set to null: document.open('https://www.github.com','', 'noopener=true') two-argument document.open() browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g.
Document - Web APIs
WebAPIDocument
properties included from documentorshadowroot the document interface includes the following properties defined on the documentorshadowroot mixin.
... methods included from documentorshadowroot the document interface includes the following methods defined on the documentorshadowroot mixin.
How to create a DOM tree - Web APIs
dynamically creating a dom tree consider the following xml document: <?xml version="1.0"?> <people> <person first-name="eric" middle-initial="h" last-name="jung"> <address street="321 south st" city="denver" state="co" country="usa"/> <address street="123 main st" city="arlington" state="ma" country="usa"/> </person> <person first-name="jed" last-name="brown"> <address street="321 north st" city="atlanta" state="ga" country="usa"/> <address street="123 west st" city="seattle" state="wa" country="usa"/> <address street="321 south avenue" city="den...
... you can automate the creation of a dom tree using a jxon reverse algorithm in association with the following json representation: { "people": { "person": [{ "address": [{ "@street": "321 south st", "@city": "denver", "@state": "co", "@country": "usa" }, { "@street": "123 main st", "@city": "arlington", "@state": "ma", "@country": "usa" }], "@first-name": "eric", "@middle-initial": "h", "@last-name"...
Using the W3C DOM Level 1 Core - Web APIs
for example, the following document <html> <head> <title>my document</title> </head> <body> <h1>header</h1> <p>paragraph</p> </body> </html> has a dom tree that looks like this: (note that, although the above tree is similar to the above document's dom tree, it's not identical, as the actual dom tree preserves whitespace.) when a web browser parses an html document, it builds a dom tree and then uses it to dis...
...the following script would do the job: html content <body> <input type="button" value="change this document." onclick="change()"> <h2>header</h2> <p>paragraph</p> </body> javascript content function change() { // document.getelementsbytagname("h2") returns a nodelist of the <h2> // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h2").item(0);...
Element.attachShadow() - Web APIs
the following is a list of elements you can attach a shadow root to: any autonomous custom element with a valid name <article> <aside> <blockquote> <body> <div> <footer> <h1> <h2> <h3> <h4> <h5> <h6> <header> <main> <nav> <p> <section> <span> syntax var shadowroot = element.attachshadow(shadowrootinit); parameters shadowrootinit a shadowrootinit dictionary, which can contain the following fields: mode a string specifying the enca...
... examples the following example is taken from our word-count-web-component demo (see it live also).
Element.getAnimations() - Web APIs
syntax const animations = element.getanimations(options); parameters options optional an options object containing the following property: subtree a boolean value which, if true, causes animations that target descendants of element to be returned as well.
... examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document.
Element.insertAdjacentText() - Web APIs
syntax element.insertadjacenttext(position, element); parameters position a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself.
... polyfill you can polyfill the insertadjacenttext() method in internet explorer 5.5 (maybe earlier) and higher with the following code: if (!element.prototype.insertadjacenttext) element.prototype.insertadjacenttext = function(type, txt){ this.insertadjacenthtml( type, (txt+'') // convert to string .replace(/&/g, '&amp;') // embed ampersand symbols .replace(/</g, '&lt;') // embed less-than symbols ) } specification specification status comment domthe de...
Element: mouseout event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmouseout examples the following examples show the use of the mouseout event.
... mouseout and mouseleave the following example illustrates the difference between mouseout and mouseleave events.
Element.scrollHeight - Web APIs
padding-bottom left top right bottom margin-top margin-bottom border-top border-bottom problems and solutions determine if an element has been totally scrolled the following equivalence returns true if an element is at the end of its scroll, false if it isn't.
..."thank you." : "please, scroll and read the following text."; } onload = function () { var otoberead = document.getelementbyid("rules"); checkreading.noticebox = document.createelement("span"); document.registration.accept.checked = false; checkreading.noticebox.id = "notice"; otoberead.parentnode.insertbefore(checkreading.noticebox, otoberead); otoberead.parentnode.insertbefore(document.createelement("br"), otoberead); otoberead.onsc...
Event.cancelable - Web APIs
WebAPIEventcancelable
example for example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is called — any following wheel events cannot be canceled.
... console.warn(`the following event couldn't be canceled:`); console.dir(event); } } document.addeventlistener('wheel', preventscrollwheel); notes whether an event can be canceled or not is something that's determined when that event is initialized.
FileEntrySync - Web APIs
returns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist.
... returns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist.
FileError - Web APIs
WebAPIFileError
so the following are a few tips that could help you avoid some pitfalls.
... security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application.
FileException - Web APIs
when errors occur, forward them to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" already exists.
... security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application.
FileReaderSync.readAsArrayBuffer() - Web APIs
exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g.
... securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file).
FileReaderSync.readAsBinaryString() - Web APIs
exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g.
... securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file).
FileReaderSync.readAsDataURL() - Web APIs
exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g.
... securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file).
FileReaderSync.readAsText() - Web APIs
exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g.
... securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file).
FileSystemEntry - Web APIs
// opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, function(fs) { fs.root.getfile('log.txt', {}, function(fileentry) { fileentry.remove(function() { console.log('file removed.'); }, onerror); }, onerror); }, onerror); properties this interface provides the following properties.
... methods this interface defines the following methods.
GainNode.gain - Web APIs
WebAPIGainNodegain
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
...tegain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
GainNode - Web APIs
WebAPIGainNode
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
...tegain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
msAudioCategory - Web APIs
examples include the following local media playback scenarios: local playlist streaming radio streaming playlist music videos streaming audio/radio, youtube, netflix, etc.
... yes communications for streaming communication audio such as the following: voip real time chat or other type of phone calls should not be used in non-real-time or non-communication scenarios, such as audio and/or video playback, as playback startup latency is affected.
HTMLBodyElement - Web APIs
recommendation the following properties are now obsolete: alink, bgcolor, background, link, text, and vlink.
... the following properties have been added: onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload.
HTMLFieldSetElement - Web APIs
recommendation the following properties have been added: disabled, elements, name, type, valdiationmessage, validity, and willvalidate.
... the following methods have been added: checkvalidity(), setcustomvalidity().
HTMLFormElement.elements - Web APIs
the form controls in the returned collection are in the same order in which they appear in the form by following a preorder, depth-first traversal of the tree.
... the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms.
HTMLImageElement.align - Web APIs
syntax htmlimageelement.align = alignmode; alignmode = htmlimageelement.align; value a domstring specifying one of the following strings which set the alignment mode for the image.
...instead, they cause the image to "float" to the left or right margin, allowing the following text to flow around the image.
HTMLImageElement.srcset - Web APIs
all of the following are valid image candidate strings: "images/team-photo.jpg 1x, images/team-photo-retina.jpg 2x, images/team-photo-full 2048w" this string provides versions of an image to be used at the standard pixel density (1x) as well as double that pixel density (2x).
... .box { width: 200px; border: 2px solid rgba(150, 150, 150, 255); padding: 0.5em; word-break: break-all; } .box img { width: 200px; } javascript the following code is run within a handler for the window's load event.
HTMLScriptElement - Web APIs
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).
... recommendation the following properties are now obsolete: htmlfor,.
HTMLTextAreaElement - Web APIs
the following attributes have been added: autofocus, placeholder, dirname, wrap, maxlength, required, textlength, labels, selectionstart, selectionend, selectiondirection, validity, validationmessage, and willvalidate.
... the following methods have been added: checkvalidity(), setcustomvalidity(), and setselectionrange().
Dragging and Dropping Multiple Items - Web APIs
the following example retrieves a set of files being dragged and adds them to an array.
... multiple drop example the following example provides a box where the lists of items and formats dropped on it are displayed.
History.replaceState() - Web APIs
examples suppose https://www.mozilla.org/foo.html executes the following javascript: const stateobj = { foo: 'bar' }; history.pushstate(stateobj, '', 'bar.html'); the explanation of these two lines above can be found in the example of pushstate() method section of the working with the history api article.
... then suppose https://www.mozilla.org/bar.html executes the following javascript: history.replacestate(stateobj, '', 'bar2.html'); this will cause the url bar to display https://www.mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.
History API - Web APIs
another use for the go() method is to refresh the current page by either passing 0, or by invoking it without an argument: // the following statements // both have the effect of // refreshing the page window.history.go(0) window.history.go() you can determine the number of pages in the history stack by looking at the value of the length property: let numberofentries = window.history.length interfaces history allows manipulation of the browser session history (that is, the pages visited in the tab or frame that the current pa...
... examples the following example assigns a listener to the onpopstate property.
IDBCursor.continue() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive.
... dataerror the key parameter may have any of the following conditions: the key is not a valid key.
IDBCursor.continuePrimaryKey() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive.
... dataerror the key parameter may have any of the following conditions: the key is not a valid key.
IDBCursorSync - Web APIs
setting this attribute can raise an idbdatabaseexception with the following codes: data_err if the underlying object store uses in-line keys and the property at the key path does not match the key in this cursor's position.
... remove() deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (databaseexception); exceptions this method can raise an idbdatabaseexception with the following code: not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode.
IDBDatabase.createObjectStore() - Web APIs
it includes the following properties: attribute description keypath the key path to be used by the new object store.
... exceptions this method may raise a domexception with a domerror of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction callback.
IDBFactory - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
... for a full working example, see our to-do notifications app (view example live.) // in the following line, you should include the prefixes of implementations you want to test.
IDBIndex.count() - Web APIs
WebAPIIDBIndexcount
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.get() - Web APIs
WebAPIIDBIndexget
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.getKey() - Web APIs
WebAPIIDBIndexgetKey
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.openCursor() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.openKeyCursor() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
exceptions this method may raise a domexception of the following type: exception description dataerror the following conditions raise an exception: the lower or upper parameters were not passed a valid key.
... example the following example illustrates how you'd use a bound key range.
IDBKeyRange.includes() - Web APIs
exceptions this method may raise a domexception of the following type: attribute description dataerror the supplied key was not a valid key.
...for browsers that do not support it, the following polyfill can be used.
IDBKeyRange.lowerBound() - Web APIs
exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key.
... example the following example illustrates how you'd use a lower bound key range.
IDBKeyRange.only() - Web APIs
WebAPIIDBKeyRangeonly
exceptions this method may raise a domexception of the following types: exception description dataerror the value parameter passed was not a valid key.
... example the following example illustrates how you'd use an only key range.
IDBKeyRange.upperBound() - Web APIs
exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key.
... example the following example illustrates how you'd use an upper bound key range.
IDBObjectStore.clear() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode.
... example in the following code snippet, we open a read/write transaction on our database and clear all the current data out of the object store using clear().
IDBObjectStore.delete() - Web APIs
exceptions this method may raise a domexception of the following types: exception description transactioninactiveerror this object store's transaction is inactive.
... example in the following code snippet, we open a read/write transaction on our database and delete one specific record out of our object store using delete() — a sample record with the key "walk dog".
IDBObjectStore.deleteIndex() - Web APIs
return value undefined exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction mode callback.
... example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
IDBObjectStore.get() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive.
... example in the following code snippet, we open a read/write transaction on our database and get one specific record from object store using get() — a sample record with the key "walk dog".
IDBObjectStore.index() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror the source object store has been deleted, or the transaction for the object store has finished.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBRequest.error - Web APIs
WebAPIIDBRequesterror
the following error codes are returned under certain conditions: error explanation aborterror if you abort the transaction, then all requests still in progress receive this error.
... 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 into the object store.
IDBRequest.readyState - Web APIs
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.
... 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 into the object store in another request.
IDBRequest.transaction - Web APIs
following the upgrade, the transaction ​property will again be null.
... 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 into the object store in another request.
IDBTransaction.abort() - Web APIs
syntax transaction.abort(); exceptions this method may raise a domexception of the following type: exception description invalidstateerror the transaction has 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.
IDBTransaction.objectStore() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description notfounderror the requested object store is not in this transaction's scope.
... example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBVersionChangeEvent.newVersion - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
...for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of // implementations you want to test.
IDBVersionChangeEvent - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
...for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of implementations you want to test.
ImageCapture.getPhotoSettings() - Web APIs
syntax const settingspromise = imagecapture.getphotosettings() return value a promise that resolves with a photosettings object containing the following properties: filllightmode: the flash setting of the capture device, one of "auto", "off", or "on".
... example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotosettings() to modify the size of an input range.
IndexedDB API - Web APIs
custom event interfaces this specification fires events with the following custom interface: idbversionchangeevent the idbversionchangeevent interface indicates that the version of the database has changed, as the result of an idbopendbrequest.onupgradeneeded event handler function.
... obsolete interfaces an early version of the specification also defined the following, now removed, interfaces.
Intersection Observer API - Web APIs
it has the following fields: root the element that is used as the viewport for checking visibility of the target.
...the result, given the default value of numsteps (20), is the following list of thresholds: # ratio # ratio 1 0.05 11 0.55 2 0.1 12 0.6 3 0.15 13 0.65 4 0.2 14 0.7 5 0.25 15 0.75 6 0.3 16 0.8 7 0.35 17 0.85 8 0.4 18 0.9 9 0.45 19 0.95 10 0.5 20 1.0 we could, of cou...
Keyboard.lock() - Web APIs
WebAPIKeyboardlock
examples capturing all keys the following example captures all keypresses.
... navigator.keyboard.lock(); capturing specific keys the following example captures the "w", "a", "s", and "d" keys.
KeyboardEvent: code values - Web APIs
the following tables show what code values are used for each native scancode or virtual keycode on major platforms.
...so, following table is created from source code which maps from scancode to code value.
Keyboard API - Web APIs
the following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled w on an english qwerty keyboard.
...those keys and key combinations are typically captured by the user agent or the underlying operating system, as illustrated in the following example.
LocalFileSystemSync - Web APIs
exceptions this method can raise an fileexception with the following code: exception description security_error the application does not have permission to access the file system interface.
... exceptions this method can raise a fileexception with the following codes: exception description encoding_err the syntax of the url was invalid.
LockManager.request() - Web APIs
examples general example the following example shows the basic use of the request() method with an asynchronous function as the callback.
...}); mode example the following example shows how to use the mode option for readers and writers.
LockedFile.getMetadata() - Web APIs
the following metadata are supported: size : will provide the size of the file lastmodified : will provide the date when the file was last modified return a filerequest object.
...they have the following format: size : a number lastmodified : a date object specifications specification status comment filesystem api editor's draft draft proposal ...
MediaSession.playbackState - Web APIs
the value may be one of the following: none the browsing context doesn't currently know the current playback state, or the playback state is not available at this time.
... example the following example sets up event handlers, for pausing and playing: var audio = document.queryselector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.mediasession.playbackstate = "paused"; } specifications specification status comment media session standardthe definition of 'playbackstate' in that specification.
MediaSession - Web APIs
examples the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhand...
...ler('pause', function() {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); navigator.mediasession.setactionhandler('seekforward', function() {}); navigator.mediasession.setactionhandler('previoustrack', function() {}); navigator.mediasession.setactionhandler('nexttrack', function() {}); } the following example sets up event handlers for pausing and playing: var audio = document.queryselector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.mediasession.playbackstate = "paused"; } specifications specification status ...
MediaSource.duration - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
...their sourcebuffer.updating property is true.) example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endo...
Using the MediaStream Recording API - Web APIs
ure: if (navigator.mediadevices && navigator.mediadevices.getusermedia) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }) // success callback .then(function(stream) { }) // error callback .catch(function(err) { console.log('the following getusermedia error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } the whole thing is wrapped in a test that checks whether getusermedia is supported before running anything else.
... next, we create an html structure like the following, inserting it into our clip container, which is an <article> element.
MediaTrackSettings - Web APIs
properties some or all of the following will be included in the object, either because it's not supported by the browser or because it's not available due to context.
... properties of shared screen tracks tracks containing video shared from a user's screen (regardless of whether the screen data comes from the entire screen or a portion of a screen, like a window or tab) are generally treated like video tracks, with the exception that they also support the following added settings: cursor a domstring which indicates whether or not the mouse cursor is being included in the generated stream and under what conditions.
MediaTrackSupportedConstraints - Web APIs
properties some combination—but not necessarily all—of the following properties will exist on the object.
... properties specific to shared screen tracks for tracks containing video sources from the user's screen contents, the following additional properties are may be included in addition to those available for video tracks.
Media Session API - Web APIs
examples the following example shows feature detection for the media session api.
...the following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playbutton.addeventlistener('pointerup', function(event) { var audio = document.queryselector('audio'); // user interacted with the page.
Transcoding assets for Media Source Extensions - Web APIs
[0] (c) copyright 2008, blender foundation / www.bigbuckbunny.org / https://peach.blender.org/about/ tools required when working with mse, the following tools are a must have: ffmpeg — a command-line utility for transcoding your media into the required formats.
... run the following commands (shown with sample output): $ python mp4-dash-encode.py -b 5 -v bunny_fragmented.mp4 encoding 5 bitrates, min bitrate = 500.0 max bitrate = 2000.0 media source: video: resolution=640x360 encoding bitrate: 500, resolution: 256x144 encoding bitrate: 875, resolution: 384x216 encoding bitrate: 1250, resolution: 480x270 encoding bitrate: 1625, resolution: 560x316 encoding bitrate: 2000, reso...
Microdata DOM API - Web APIs
var inner = document.createelement('ul'); for (var name = 0; name < items[item].properties.names.length; name += 1) { var propli = document.createelement('li'); propli.appendchild(document.createtextnode(items[item].properties.names[name])); inner.appendchild(propli); } itemli.appendchild(inner); outer.appendchild(itemli); } document.body.appendchild(outer); if faced with the following from an earlier example: <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name http://example.com/fn">hedral</h1> <p itemprop="desc">hedral is a male american domestic shorthair, with a fluffy <span itemprop="http://example.com/color">black</span> fur with <span itemprop="http://example.com/color">white</span> paws and belly.</p> <img itemprop="img" src="hedral.jpeg" a...
...lt="" title="hedral, age 18 months"> </section> ...it would result in the following output: name http://example.com/fn desc http://example.com/color img (the duplicate occurrence of "http://example.com/color" is not included in the list.) htmlpropertiescollection the htmlpropertiescollection interface is used for collections of elements that add name-value pairs to a particular item in the microdata model.
Navigator.getBattery() - Web APIs
exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: securityerror the user agent does not expose battery information to insecure contexts and this method was called from insecure context.
... notallowederror note: no user agent currently throws this exception, but the specification describes the following behaviors: this document is not allowed to use this feature.
Navigator.getUserMedia() - Web APIs
your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here.
... navigator.mozgetusermedia; if (navigator.getusermedia) { navigator.getusermedia({ audio: true, video: { width: 1280, height: 720 } }, function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); }; }, function(err) { console.log("the following error occurred: " + err.name); } ); } else { console.log("getusermedia not supported"); } ...
Navigator.onLine - Web APIs
to check if you are online, query window.navigator.online, as in the following example: if (navigator.online) { console.log('online'); } else { console.log('offline'); } if the browser doesn't support navigator.online the above example will always come out as false/undefined.
... to see changes in the network state, use addeventlistener to listen for the events on window.online and window.offline, as in the following example: window.addeventlistener('offline', function(e) { console.log('offline'); }); window.addeventlistener('online', function(e) { console.log('online'); }); specifications specification status comment html living standardthe definition of 'navigator.online' in that specification.
NavigatorPlugins.plugins - Web APIs
examples the following example function returns the version of the shockwave flash plugin.
...in chrome) return flash.description.replace(/shockwave flash /,""); } } the following example displays information about the installed plugin(s).
Node.compareDocumentPosition() - Web APIs
the return value is a bitmask of the following values: name value document_position_disconnected 1 document_position_preceding 2 document_position_following 4 document_position_contains 8 document_position_contained_by 16 document_position_implementation_specific 32 syntax comparemask = node.comparedocumentposition(othernode) parameters othernode the other node with which to compare the first node’s document position.
... example const head = document.head; const body = document.body; if (head.comparedocumentposition(body) & node.document_position_following) { console.log('well-formed document'); } else { console.error('<head> is not before <body>'); } note: because the result returned by comparedocumentposition() is a bitmask, the bitwise and operator must be used for meaningful results.
Node.nextSibling - Web APIs
WebAPINodenextSibling
the node.nextsibling read-only property returns the node immediately following the specified one in their parent's childnodes, or returns null if the specified node is the last child in the parent element.
...', el.nodename); el = el.nextsibling; i++; } console.groupend(); </script> /************************************************** the console displays the following: siblings of div-1 1.
Node.removeChild() - Web APIs
WebAPINoderemoveChild
this will also happen if child was in fact a child of element at the time of the call, but was removed by an event handler invoked in the course of trying to remove the element (e.g., blur.) errors thrown the method throws an exception in 2 different ways: if the child was in fact a child of element and so existing on the dom, but was removed the method throws the following exception: uncaught notfounderror: failed to execute 'removechild' on 'node': the node to be removed is not a child of this node.
... if the child doesn't exist on the dom of the page, the method throws the following exception: uncaught typeerror: failed to execute 'removechild' on 'node': parameter 1 is not of type 'node'.
NonDocumentTypeChildNode.nextElementSibling - Web APIs
the nondocumenttypechildnode.nextelementsibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.
...x var nextnode = elementnodereference.nextelementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <script type="text/javascript"> var el = document.getelementbyid('div-01').nextelementsibling; console.log('siblings of div-01:'); while (el) { console.log(el.nodename); el = el.nextelementsibling; } </script> this example outputs the following into the console when it loads: siblings of div-01: div script polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("nextelementsibling" in document.documentelement)){ object.defineproperty(element.prototype, ...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
>this is a list item</li> <li>this is another list item</li> <div id="div-03">here is div-03</div> <script> let el = document.getelementbyid('div-03').previouselementsibling; document.write('<p>siblings of div-03</p><ol>'); while (el) { document.write('<li>' + el.nodename + '</li>'); el = el.previouselementsibling; } document.write('</ol>'); </script> this example outputs the following into the page when it loads: siblings of div-03 1.
...div polyfills polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("previouselementsibling" in document.documentelement)){ object.defineproperty(element.prototype, "previouselementsibling", { get: function(){ var e = this.previoussibling; while(e && 1 !== e.nodetype) e = e.previoussibling; return e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/previouselementsibling/previouselementsibling.md (function (arr) { arr.foreach(function (item) { if (item.h...
Notification.close() - Web APIs
the user already read the notification on the webpage in the case of a messaging app or the following song is already playing in a music app).
... examples in the following snippet, we have a simple function that when called creates an options object and then a new notification.
Page Visibility API - Web APIs
the example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code: // set the name of the hidden property and the change event for visibility var hidden, visibilitychange; if (typeof document.hidden !== "undefined") { // opera 12.10 and firefox 18 and later support hidden = "hidden"; visibilitychange = "visibilitychange"; } else if (typeof document.mshidden !== "undefined") { hidden = "mshidden"; visibilitychange = "msvisibilitychange"; } else if ...
... videoelement.addeventlistener("play", function(){ document.title = 'playing'; }, false); } properties added to the document interface the page visibility api adds the following properties to the document interface: document.hidden read only returns true if the page is in a state considered to be hidden to the user, and false otherwise.
PaymentAddress - Web APIs
obsolete properties the following properties are obsolete and should no longer be used, but may still be present in some browser versions.
... examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
PaymentRequest.show() - Web APIs
examples in the following example, a paymentrequest object is instantiated before the show() method is called.
... // paymentresponse.methodname contains the selected payment method // paymentresponse.details contains a payment method specific response await response.complete("success"); } catch (err) { console.error("uh oh, something bad happened", err.message); } } the following example shows how to update the payment sheet as it's being presented to the end-user.
PaymentResponse.complete() - Web APIs
it must be one of the following: success the payment was successfully processed.
... examples the following example sends payment information to a secure server using the fetch api.
performance.measure() - Web APIs
the measure's performance entry will have the following property values: entrytype - set to "measure".
... return value void example the following example shows how measure() is used to create a new measure performance entry in the browser's performance entry buffer.
PerformanceEntry - Web APIs
performanceentry instances will always be one of the following subtypes: performancemark performancemeasure performanceframetiming performancenavigationtiming performanceresourcetiming performancepainttiming note: this feature is available in web workers.
... example the following example checks all performanceentry properties to see if the browser supports them and if so, write their values to the console.
PerformanceNavigationTiming.type - Web APIs
the value must be one of the following: navigate navigation started by clicking a link, entering the url in the browser's address bar, form submission, or initializing through a script operation other than reload and back_forward as listed below.
... example the following example illustrates this property's usage.
PerformancePaintTiming - Web APIs
h="220" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="311" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancepainttiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties (for "paint" performance entry types) by qualifying and constraining the properties as follows: performanceentry.entrytype returns "paint".
...ance; let performanceentries = performance.getentriesbytype('paint'); performanceentries.foreach( (performanceentry, i, entries) => { console.log("the time to " + performanceentry.name + " was " + performanceentry.starttime + " milliseconds."); }); } else { console.log('performance timing isn\'t supported.'); } } the code above produces console output something like the following: the time to first-paint was 2785.915 milliseconds.
PerformanceResourceTiming - Web APIs
properties this interface extends the following performanceentry properties for resource performance entry types by qualifying and constraining them as follows: performanceentry.entrytyperead only returns "resource".
... the interface also supports the following properties which are listed in the order in which they are recorded for the fetching of a single resource.
Using the Performance API - Web APIs
the following code example shows the use of domhighrestimestamp and the performance.now() method.
...in the following example, json serialization for the performance, performance.timing and performance.navigation objects is printed in the object element.
PluginArray - Web APIs
examples the following example function returns the version of the shockwave flash plugin.
...id('plugintable'); for(var i = 0; i < pluginslength; i++) { let newrow = table.insertrow(); newrow.insertcell().textcontent = navigator.plugins[i].name; newrow.insertcell().textcontent = navigator.plugins[i].filename; newrow.insertcell().textcontent = navigator.plugins[i].description; newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; } the following example displays information about the installed plugin(s).
Push API - Web APIs
WebAPIPush API
see the following articles for more information: cross-site request forgery (csrf) prevention cheat sheet preventing csrf and xsrf attacks for an app to receive push messages, it has to have an active service worker.
... service worker additions the following additions to the service worker api have been specified in the push api spec to provide an entry point for using push messages.
RTCConfiguration.bundlePolicy - Web APIs
this string, which must be a member of the rtcbundlepolicy enumeration, has the following possible values: balanced the ice agent begins by creating one rtcdtlstransport to handle each type of content added: one for audio, one for video, and one for the rtc data channel, if applicable.
... examples the following example creates a new rtcpeerconnection with a configuration setting the connection's bundlepolicy to max-compat to maximize compatibility while attempting to optimize network use.
RTCIceCandidatePairStats - Web APIs
in addition, it adds the following new properties: availableincomingbitrate optional provides an informative value representing the available inbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's incoming rtp streams.
... obsolete properties the following properties have been removed from the specification and should no longer be used.
RTCIdentityErrorEvent.protocol - Web APIs
firefox implements the interface of this property under the following name: rtcpeerconnectionidentityerrorevent.
... syntax var protocol = event.protocol; event.protocol = "idp.html"; example pc.onidpassertionerror = function( ev ) { alert("the idp uses the following protocol '" + ev.protocol + "."); } ...
RTCPeerConnection - Web APIs
obsolete method the following method was obsoleted long ago and was never implemented in all major browsers.
... constant description "new" at least one of the connection's ice transports (rtcicetransports or rtcdtlstransports) are in the "new" state, and none of them are in one of the following states: "connecting", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state.
RTCRtpStreamStats - Web APIs
it's based on rtcstats and adds the following additional fields.
...in addition, some or all of the following properties are available.
RTCSessionDescription() - Web APIs
that dictionary has the following properties: type required.
... a string which is a member of the rtcsdptype enum; it must have one of the following values: this enum defines strings that describe the current state of the session description, as used in the type property.
ReadableStream.ReadableStream() - Web APIs
underlyingsource can contain the following: start(controller) this is a method, called immediately when the object is constructed.
... examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStream - Web APIs
examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser.
... fetch("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 - Web APIs
examples in the following example, an artifical response is created to stream html fragments fetched from another resource to the browser.
... fetch("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" return reader.read().then(({ done, value }) => { // is there no more data to read?
Request.redirect - Web APIs
WebAPIRequestredirect
syntax var myredirect = request.redirect; value a requestredirect enum value, which can be one the following strings: follow error manual if not specified when the request is created, it takes the default value of follow.
... example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification.
Response - Web APIs
WebAPIResponse
body interface properties response implements body, so it also has the following properties available to it: body.body read only a simple getter exposing a readablestream of the body contents.
... body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion.
SVGAnimatedPathData - Web APIs
name type description animatednormalizedpathseglist svgpathseglist provides access to the current animated contents of the 'd' attribute in a form where all path data commands are expressed in terms of the following subset of svgpathseg types: svg_pathseg_moveto_abs (m), svg_pathseg_lineto_abs (l), svg_pathseg_curveto_cubic_abs (c) and svg_pathseg_closepath (z).
... normalizedpathseglist svgpathseglist provides access to the base (i.e., static) contents of the 'd' attribute in a form where all path data commands are expressed in terms of the following subset of svgpathseg types: svg_pathseg_moveto_abs (m), svg_pathseg_lineto_abs (l), svg_pathseg_curveto_cubic_abs (c) and svg_pathseg_closepath (z).
Screen Capture API - Web APIs
additions to existing dictionaries the screen capture api adds properties to the following dictionaries defined by other specifications.
... dictionaries the following dictionaries are defined by the screen capture api.
Sensor APIs - Web APIs
const sensor = new absoluteorientationsensor(); sensor.start(); sensor.onerror = event => { if (event.error.name === 'securityerror') console.log("no permissions to use absoluteorientationsensor."); }; the following table describes for each sensor type, the name required for the permissions api, the <iframe> element's allow attribute and the feature-policy directive.
... the following example illustrates this using the magnetometer sensor.
Using server-sent events - Web APIs
fields each message received has some combination of the following fields, one per line: event a string identifying the type of event described.
... examples data-only messages in the following example, there are three messages sent.
ServiceWorkerRegistration.showNotification() - Web APIs
it can have the following properties: actions: an array of actions to display in the notification.
...it may contain the following values: action: a domstring identifying a user action to be displayed on the notification.
SubtleCrypto.exportKey() - Web APIs
it can be one of the following: raw: raw format.
... exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when trying to export a non-extractable key.
SubtleCrypto.importKey() - Web APIs
it can be one of the following: raw: raw format.
... exceptions the promise is rejected when one of the following exceptions is encountered: syntaxerror raised when keyusages is empty but the unwrapped key is of type secret or private.
SubtleCrypto.unwrapKey() - Web APIs
it can be one of the following: raw: raw format.
... exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when the unwrapping key is not a key for the requested unwrap algorithm or if the cryptokey.usages value of that key doesn't contain unwrap.
SubtleCrypto.wrapKey() - Web APIs
it can be one of the following: raw: raw format.
... exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when the wrapping key is not a key for the requested wrap algorithm.
USB.requestDevice() - Web APIs
WebAPIUSBrequestDevice
each filter object can have the following properties: vendorid productid classcode subclasscode protocolcode serialnumber return value a promise that resolves with an instance of usbdevice.
... example the following example looks for one of two usb devices.
User Timing API - Web APIs
the mark's performance entry will have the following property values: entrytype - set to "mark".
... the measure's performance entry will have the following property values: entrytype - set to "measure".
WebGLRenderingContext.blendEquationSeparate() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination.
... when using a webgl 2 context, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination.
WebGLRenderingContext.bufferData() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another.
... when using a webgl 2 context, the following values are available additionally: gl.static_read: the contents are intended to be specified once by reading data from webgl, and queried many times by the application.
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer.
... when using a webgl 2 context, the following values are available additionally: gl.color_attachment1 gl.color_attachment2 gl.color_attachment3 gl.color_attachment4 gl.color_attachment5 gl.color_attachment6 gl.color_attachment7 gl.color_attachment8 gl.color_attachment9 gl.color_attachment10 gl.color_attachment11 gl.color_attachment12 gl.color_attachment13 gl.color_attac...
WebGLRenderingContext.framebufferTexture2D() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer.
... when using a webgl 2 context, the following values are available additionally: gl.depth_stencil_attachment: depth and stencil buffer.
WebGLRenderingContext.getBufferParameter() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another.
... when using a webgl 2 context, the following values are available additionally: gl.static_read, gl.dynamic_read, gl.stream_read, gl.static_copy, gl.dynamic_copy, gl.stream_copy.
WebGLRenderingContext.getUniformLocation() - Web APIs
additionally, for uniforms declared as arrays, the following names are also valid: the uniform name without the [0] suffix.
... errors the following errors may occur; to check for errors after getuniformlocation() returns, call geterror().
WebGLRenderingContext.hint() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.fragment_shader_derivative_hint: same as ext.fragment_shader_derivative_hint_oes mode sets the behavior.
... examples the following example hints that the quality of filtering when generating mipmap images should be most efficient instead of best quality.
WebGLRenderingContext.texImage2D() - Web APIs
when using the webgl_depth_texture extension: gl.depth_component gl.depth_stencil when using the ext_srgb extension: ext.srgb_ext ext.srgb_alpha_ext when using a webgl 2 context, the following values are available additionally: gl.r8 gl.r16f gl.r32f gl.r8ui gl.rg8 gl.rg16f gl.rg32f gl.rg8ui gl.rg16ui gl.rg32ui gl.rgb8 gl.srgb8 gl.rgb565 gl.r11f_g11f_b10f gl.rgb9_e5 gl.rgb16f gl.rgb32f gl.rgb8ui gl.rgba8 gl.srgb8_alpha8 gl.rgb5_a1 gl.rgb10_a2 gl.rgba4 gl.rgba16f gl.rgba32f gl.rgba...
... when using the webgl_depth_texture extension: gl.unsigned_short gl.unsigned_int ext.unsigned_int_24_8_webgl (constant provided by the extension) when using the oes_texture_float extension: gl.float when using the oes_texture_half_float extension: ext.half_float_oes (constant provided by the extension) when using a webgl 2 context, the following values are available additionally: gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) pixels one of the following objects can be used as...
WebGLRenderingContext.texSubImage2D() - Web APIs
when using the ext_srgb extension: ext.srgb_ext ext.srgb_alpha_ext when using a webgl 2 context, the following values are available additionally: gl.red gl.rg gl.red_integer gl.rg_integer gl.rgb_integer gl.rgba_integer type a glenum specifying the data type of the texel data.
... when using the oes_texture_float extension: gl.float when using the oes_texture_half_float extension: gl.half_float_oes when using a webgl 2 context, the following values are available additionally: gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) pixels one of the following objects can be used as...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
possible values: gl.byte: signed 8-bit integer, with values in [-128, 127] gl.short: signed 16-bit integer, with values in [-32768, 32767] gl.unsigned_byte: unsigned 8-bit integer, with values in [0, 255] gl.unsigned_short: unsigned 16-bit integer, with values in [0, 65535] gl.float: 32-bit ieee floating point number when using a webgl 2 context, the following values are available additionally: gl.half_float: 16-bit ieee floating point number normalized a glboolean specifying whether integer data values should be normalized into a certain range when being cast to a float.
... for example, the following vertex: { "position": [1.0, 2.0, 1.5], "normal": [1.0, 0.0, 0.0], "texcoord": [0.5, 0.25] } will be stored in the array buffer as follows: 00 00 80 3f 00 00 00 40 00 00 0c 3f 7f 00 00 00 7f ff 3f ff creating the array buffer first, we dynamically create the array buffer from json data using a dataview.
Using shaders to apply color in WebGL - Web APIs
we'll do that by adding the following code to our initbuffers() function: function initbuffers(){ ...
... then, drawscene() can have the following added to it so it actually uses these colors when drawing the square: // tell webgl how to pull out the colors from the color buffer // into the vertexcolor attribute.
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
these correspond to the following three types of transport supported by rtcpeerconnection: rtcrtpsender rtcrtpsenders handle the encoding and transmission of mediastreamtrack data to a remote peer.
... async function enablehold(audiostream) { try { await audiotransceiver.sender.replacetrack(audiostream.getaudiotracks()[0]); audiotransceiver.receiver.track.enabled = false; audiotransceiver.direction = "sendonly"; } catch(err) { /* handle the error */ } } the three lines of code within the try block perform the following steps: replace their outgoing audio track with a mediastreamtrack containing hold music.
Signaling and video calling - Web APIs
these messages have the following fields: type the message type; either "video-offer" or "video-answer".
...the offer has the following members: type the message type: "video-offer".
WebRTC API - Web APIs
datachannel a new rtcdatachannel is available following the remote peer opening a new data channel.
... track the track event, of type rtctrackevent is sent to an rtcpeerconnection when a new track is added to the connection following the successful negotiation of the media's streaming.
Writing a WebSocket server in C# - Web APIs
if it is 126, the following 2 bytes (16-bit unsigned integer) are the length.
... if it is 127, the following 8 bytes (64-bit unsigned integer) are the length.
Geometry and reference spaces in WebXR - Web APIs
the following code snippet shows two simple functions, degreestoradians() and radianstodegrees(), which convert back and forth between the two units for measuring angles.
... the directionality of the coordinate system can be seen in the following diagram: an xrrigidtransform called the origin offset is used to transform points from the space's own effective coordinate system to the xr device's native coordinate system.
WebXR permissions and security - Web APIs
once that check is passed, the request to enter immersive-vr mode is allowed if all of the following are true: the requestsession() call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application.
... implicit user intent (implicit user consent) is assumed if either of the following scenarios is the case: the user has interacted with the document in some way which has in turn caused your request to occur.
Using the Web Animations API - Web APIs
we can achieve this via the following function: var growalice = function() { // play alice's animation.
... nommingcake.play(); } when a user holds their mouse down or presses their finger on the cake on a touch screen, we can now call growalice to make all the animations play: cake.addeventlistener("mousedown", growalice, false); cake.addeventlistener("touchstart", growalice, false); other useful methods in addition to pausing and playing, we can use the following animation methods: animation.finish() skips to the end of the animation.
Basic concepts behind Web Audio API - Web APIs
: left 1: r: right quad 0: l: left 1: r: right 2: sl: surround left 3: sr: surround right 5.1 0: l: left 1: r: right 2: c: center 3: lfe: subwoofer 4: sl: surround left 5: sr: surround right up-mixing and down-mixing when the number of channels doesn't match between an input and an output, up- or down-mixing happens according the following rules.
... you can grab data using the following methods: analysernode.getfloatfrequencydata() copies the current frequency data into a float32array array passed into it.
Window.captureEvents() - Web APIs
syntax window.captureevents(eventtype) eventtype is a combination of the following values: event.abort, event.blur, event.click, event.change, event.dblclick, event.dragddrop, event.error, event.focus, event.keydown, event.keypress, event.keyup, event.load, event.mousedown, event.mousemove, event.mouseout, event.mouseover, event.mouseup, event.move, event.reset, event.resize, event.select, event.submit, event.unload.
... note that you can pass a list of events to this method using the following syntax: window.captureevents(event.keypress | event.keydown | event.keyup).
Window.open() - Web APIs
WebAPIWindowopen
toolbar and ui parts features in modern browsers (firefox 76 or newer, google chrome, safari, chromium edge), the following features are just a condition for whether to open popup or not.
... the following features control the visibility of each ui parts, all features can be set to yes or 1, or just be present to be on.
Window.personalbar - Web APIs
syntax objref =window.personalbar example fixme: https://bugzilla.mozilla.org/show_bug.cgi?id=790023 the following complete html example shows the way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window.
... <!doctype html> <html> <head> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.personalbar.visible = !window.personalbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser displays the following dialog: to toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above.
Window.releaseEvents() - Web APIs
syntax window.releaseevents(eventtype) eventtype is a combination of the following values: event.abort, event.blur, event.click, event.change, event.dblclick, event.dragddrop, event.error, event.focus, event.keydown, event.keypress, event.keyup, event.load, event.mousedown, event.mousemove, event.mouseout, event.mouseover, event.mouseup, event.move, event.reset, event.resize, event.select, event.submit, event.unload.
... example window.releaseevents(event.keypress) notes note that you can pass a list of events to this method using the following syntax: window.releaseevents(event.keypress | event.keydown | event.keyup).
Window.self - Web APIs
WebAPIWindowself
example uses of window.self like the following could just as well be replaced by window.
... if (window.parent.frames[0] != window.self) { // this window is not the first frame in the list } furthermore, when executing in the active document of a browsing context, window is a reference to the current global object and thus all of the following are equivalent: var w1 = window; var w2 = self; var w3 = window.window; var w4 = window.self; // w1, w2, w3, w4 all strictly equal, but only w2 will function in workers specifications specification status comment html living standardthe definition of 'window.self' in that specification.
Window.sessionStorage - Web APIs
example the following snippet accesses the current origin's session storage object and adds data to it with storage.setitem().
... sessionstorage.setitem('mycat', 'tom'); the following example autosaves the contents of a text field, and if the browser is refreshed, restores the text field content so that no writing is lost.
Window.statusbar - Web APIs
WebAPIWindowstatusbar
syntax objref = window.statusbar example the following complete html example shows a way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window.
...ng="en"> <head> <meta charset="utf-8" /> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.statusbar.visible=!window.statusbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser displays the following dialog: to toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above.
Window.toolbar - Web APIs
WebAPIWindowtoolbar
syntax objref = window.toolbar example the following complete html example shows way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window.
... <!doctype html> <html> <head> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.toolbar.visible=!window.toolbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser displays the following dialog: to toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above.
Worklet.addModule() - Web APIs
WebAPIWorkletaddModule
options optional an object with any of the following options: credentials: a requestcredentials value that indicates whether to send credentials (e.g.
... exceptions if addmodule() fails, it rejects the promise, delivering one of the following errors to the rejection handler.
WritableStream.WritableStream() - Web APIs
underlyingsink can contain the following: start(controller) optional this is a method, called immediately when the object is constructed.
... examples the following example illustrates several features of this interface.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
the function is passed the channel property of an xmlhttprequest to extract the following information: was the connection secure?
... var req = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('get', url, true); req.addeventlistener("error", function(e) { var error = createtcperrorfromfailedxhr(req); dumpsecurityinfo(req, error); }, false); req.onload = function(e) { dumpsecurityinfo(req); }; req.send(); } then test("https://addons.mozilla.org"); produced the following output in my console: connection status: succeeded security info: security state: secure common name (cn) = addons.mozilla.org organisation = mozilla corporation issuer = verisign, inc.
Synchronous and asynchronous requests - Web APIs
the following example shows theoretical analytics code that attempts to submit data to a server by using a synchronous xmlhttprequest in an unload handler.
... the following example shows a theoretical analytics code pattern that submits data to a server by using the sendbeacon() method.
XRInputSourceArray - Web APIs
properties the following properties are available on xrinputsourcearray objects.
... methods the following methods are available on xrinputsourcearray objects.
XRReferenceSpace - Web APIs
xrreferencespace also provides the following methods.
... events in addition to other events that may be sent to xrspace or eventtarget objects, the following also apply to xrreferencespace objects.
XRSession - Web APIs
WebAPIXRSession
methods xrsession provides the following methods in addition to those inherited from its parent interface, eventtarget.
... events the following events are delivered to xrsession objects.
XRSystem - Web APIs
WebAPIXRSystem
methods in addition to inheriting methods from its parent interface, eventtarget, the xrsystem interface includes the following methods: issessionsupported() returns a promise which resolves to true if the browser supports the given xrsessionmode.
... examples the following example shows how to use both issessionsupported() and requestsession().
Using the group role - Accessibility
possible effects on user agents and assistive technology when the group role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a group role in the operating system's accessibility api.
...following this the focused control may be announced.
ARIA Test Cases - Accessibility
following all that, the focused control should be spoken.
... markup used: role = (one of the following): "application", "article", "banner", "complementary", "contentinfo", "directory", "document", "log", "main", "note", "navigation", "region", "search", "status" notes: screen readers may wish to provide some landmark-specific conveniences such as automatically starting at "main" when reading the page after page load, or providing a special key to get to the search bar, etc.
ARIA: feed role - Accessibility
the feed pattern enables reliable assistive technology reading mode interaction by establishing the following interoperability agreement between the web page and assistive technologies: in the context of a feed, the web page code is responsible for: appropriate visual scrolling of the content based on which article contains dom focus.
... keyboard interaction supporting the following, or a similar, interface is recommended when focus is inside the feed: page down: move focus to next article.
ARIA: switch role - Accessibility
the assistive technology, if it supports the switch role, responds by doing the following: screen readers should announce the element as a switch, optionally providing instructions as to how to activate the switch.
... examples the following examples should help you understand how to apply and use the switch role.
ARIA: dialog role - Accessibility
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.
... possible effects on user agents and assistive technology when the dialog role is used, the user agent should do the following: expose the element as a dialog in the operating system's accessibility api.
ARIA: listbox role - Accessibility
required javascript features selecting an option in a single select listbox when the user selects an option, the following must occur: deselect the previously selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the newly unselected option to appear not selected.
... update the aria-activedescendant value on the listbox to the id of the newly selected option visually handle the blur, focus, and selected states of the option toggling the state of an option in a multi select listbox when the user clicks on an option, hits space when focused on an option, or otherwise toggles the state of an option, the following must occur: toggle the aria-selected state of the currently focused option, changing the state of the aria-selected to true if it was false or false if it was true.
ARIA: textbox role - Accessibility
it supports the following values: inline: predicted text is inserted after the caret.
... possible effects on user agents and assistive technology when the textbox role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a textbox role in the operating system's accessibility api.
Architecture - Accessibility
example take the following html code: <div>hello<a href="http://www.mozilla.org/access">my link<img src="image.gif">is cool</a>bye</div> both the <a> and <img> are hyperlinks also, both the <div> and <a> are hypertexts so the <a> is both a hypertext and a hyperlink, because it contains text and is contained within text.
...the following magic offsets are useful to define in your code: #define char_offset_end_of_line = -1 #define char_offset_caret = -2 more information many more details on the mozilla document hierarchy are in the original design document for newatk.
Perceivable - Accessibility
1.4.8 visual presentation (aaa) for text content presentation, the following should be true: foreground and background colors should be user-selectable.
... understanding non-text contrast 1.4.12 text spacing (aa) added in 2.1 no loss of content or functionality occurs when the following styles are applied: line height (line spacing) to at least 1.5 times the font size spacing following paragraphs to at least 2 times the font size letter spacing (tracking) to at least 0.12 times the font size word spacing to at least 0.16 times the font size understanding text spacing 1.4.13 content on hover or focus (aa) added in 2.1 while ...
::cue - CSS: Cascading Style Sheets
WebCSS::cue
syntax ::cue | ::cue( <selector> ) permitted properties rules whose selectors include this element may only use the following css properties: background background-attachment background-clip background-color background-image background-origin background-position background-repeat background-size color font font-family font-size font-stretch font-style font-variant font-weight line-height opacity outline outline-color outline-style outline-width ruby-position text-combine-upright text-decorati...
...on text-decoration-color text-decoration-line text-decoration-style text-decoration-thickness text-shadow visibility white-space examples styling webvtt cues as white-on-black the following css sets the cue style so that the text is white and the background is a translucent black box.
:defined - CSS: Cascading Style Sheets
WebCSS:defined
/* selects any defined element */ :defined { font-style: italic; } /* selects any instance of a specific custom element */ simple-custom:defined { display: block; } syntax :defined examples hiding elements until they are defined the following snippets are taken from our defined-pseudo-class demo (see it live also).
...ent.createelement('div'); divelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(divelem); } }) then insert a copy of this element into the document, along with a standard <p>: <simple-custom text="custom element example text"></simple-custom> <p>standard paragraph example text</p> in the css we first include the following rules: // give the two elements distinctive backgrounds p { background: yellow; } simple-custom { background: cyan; } // both the custom and the built-in element are given italic text :defined { font-style: italic; } then provide the following two rules to hide any instances of our custom element that are not defined, and display instances that are defined as block level elements: simp...
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
WebCSS:is
/* selects any paragraph inside a header, main or footer element that is being hovered */ :is(header, main, footer) p:hover { color: red; cursor: pointer; } /* the above is equivalent to the following */ header p:hover, main p:hover, footer p:hover { color: red; cursor: pointer; } /* backwards-compatible version with :-*-any() and :matches() (it is not possible to group selectors into single rule, because presence of invalid selector would invalidate whole rule.) */ :-webkit-any(header, main, footer) p:hover { color: red; cursor: pointer; } :-moz-any(header, main, footer) p:hove...
...for example, the following css: /* 3-deep (or more) unordered lists use a square */ ol ol ul, ol ul ul, ol menu ul, ol dir ul, ol ol menu, ol ul menu, ol menu menu, ol dir menu, ol ol dir, ol ul dir, ol menu dir, ol dir dir, ul ol ul, ul ul ul, ul menu ul, ul dir ul, ul ol menu, ul ul menu, ul menu menu, ul dir menu, ul ol dir, ul ul dir, ul menu dir, ul dir dir, menu ...
:where() - CSS: Cascading Style Sheets
WebCSS:where
take the following html: <article> <h2>:is()-styled links</h2> <section class="is-styling"> <p>here is my main content.
... to make selecting the links inside them simpler, but still distinct, we could use :is() or :where(), in the following manner: html { font-family: sans-serif; font-size: 150%; } :is(section.is-styling, aside.is-styling, footer.is-styling) a { color: red; } :where(section.where-styling, aside.where-styling, footer.where-styling) a { color: orange; } however, what if we later want to override the color of links in the footers using a simple selector?
@charset - CSS: Cascading Style Sheets
WebCSS@charset
as there are several ways to define the character encoding of a style sheet, the browser will try the following methods in the following order (and stop as soon as one yields a result) : the value of the unicode byte-order character placed at the beginning of the file.
...it must be the name of a web-safe character encoding defined in the iana-registry, and must be double-quoted, following exactly one space character (u+0020), and immediately terminated with a semicolon.
font-weight - CSS: Cascading Style Sheets
common weight name mapping the numerical values 100 to 900 roughly correspond to the following common weight names: value common weight name 100 thin (hairline) 200 extra light (ultra light) 300 light 400 normal 500 medium 600 semi bold (demi bold) 700 bold 800 extra bold (ultra bold) 900 black (heavy) variable fonts most fonts have a particular weight which ...
...t-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax <font-weight-absolute>{1,2}where <font-weight-absolute> = normal | bold | <number <a href="/docs/css/value_definition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[1,1000]> examples setting normal font weight in a @font-face rule the following finds a local open sans font or import it, and allows using the font for normal font weights.
-ms-high-contrast - CSS: Cascading Style Sheets
syntax the -ms-high-contrast media feature is specified as one of the following values.
... examples the following declarations will match applications that are being displayed in high contrast mode with any color variation, a black-on-white color variation, and a white-on-black color variation, respectively.
forced-colors - CSS: Cascading Style Sheets
usage notes properties affected by forced-color mode in forced colors mode, the values of the following properties are treated as if they have no author-level values specified.
... examples note: no browser currently implements this feature so the following example will not work.
overflow-block - CSS: Cascading Style Sheets
optional-paged content that overflows the block axis can be seen by scrolling to it, but page breaks can be manually triggered (such as via break-inside, etc.) to cause the following content to display on the following page.
... paged content is broken up into discrete pages; content that overflows one page in the block axis is displayed on the following page.
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
flex containers in the following live example, i have floated two blocks and then set display: flex on the container.
...the following feature query would include uc browser, which supports feature queries and old flexbox syntax, prefixed: @supports (display: flex) or (display: -webkit-box) { // code for supporting browsers } for more information about using feature queries see using feature queries in css on the mozilla hacks blog.
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
the following live sample uses css grid layout to create a layout that has as many columns of at least 160 pixels as will fit, distributing the extra space between all columns.
... in the following live example i have a non-wrapped flex container.
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
the writing modes the writing modes specification defines the following values of the writing-mode property, which serve to change the direction that blocks are laid out on the page, to match the direction that blocks lay out when content is formatted in that particular writing mode.
... in the following live example i have a flex container with three child elements.
Introduction to formatting contexts - CSS: Cascading Style Sheets
this means that every element inside the <html> element's block is laid out according to normal flow following the rules for block and inline layout.
... a new bfc is created in the following situations: elements made to float using float absolutely positioned elements (including position: fixed or position: sticky) elements with display: inline-block table cells or elements with display: table-cell, including anonymous table cells created when using the display: table-* properties table captions or elements with display: table-caption block elements where overflow has a value...
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
in the following example, i have four grid areas within my grid.
... i can use the align-items property on the grid container, to align the items using one of the following values: auto normal start end center stretch baseline first baseline last baseline * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: repeat(8, 1fr); grid-gap: 10px; grid-auto-rows: 100px; grid-template-areas: "a a a a b b b b" "a a a a b b b b" "c c c c d d d d" "c c c c d d d d"; align-items: start; } .item1 { grid-area: a; } .item2 { grid-area: b; } .item3 { grid-area: c; } .i...
Grid template areas - CSS: Cascading Style Sheets
grid-template the grid-template property sets the following properties: grid-template-rows grid-template-columns grid-template-areas the property is referred to as the explicit grid shorthand because it is setting those things that you control when you define an explicit grid, and not those which impact any implicit row or column tracks that might be created.
... the following code creates a layout using grid-template that is the same as the layout created earlier in this guide.
Layout using named grid lines - CSS: Cascading Style Sheets
the following definition, creates four 1fr tracks, which each have a start and end line.
...for example, to create a three column layout with a header and footer, i might have the following markup.
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
div class="box3">three</div> <div class="box4">four</div> </div> .box1 { grid-column-start: 1; grid-row-start: 1; grid-row-end: 4; } .box2 { grid-column-start: 3; grid-row-start: 1; grid-row-end: 3; } .box3 { grid-column-start: 2; grid-row-start: 1; } .box4 { grid-column-start: 2; grid-column-end: 4; grid-row-start: 3; } our shorthand would look like the following code, with no forward slash and second value for the items spanning one track only.
...the following two examples will create the same grid area.
The stacking context - CSS: Cascading Style Sheets
a stacking context is formed, anywhere in the document, by any element in the following scenarios: root element of the document (<html>).
... element with any of the following properties with value other than none: transform filter perspective clip-path mask / mask-image / mask-border element with a isolation value isolate.
Overview of CSS Shapes - CSS: Cascading Style Sheets
in the following example i have an image floated left.
...the result is that the content now curves around the circular shape rather than following the rectangle created by the box of the image.
Sticky footers - CSS: Cascading Style Sheets
requirements the sticky footer pattern needs to meet the following requirements: footer sticks to the bottom of the viewport when content is short.
... the recipe download this example note: in this example and the following one we are using a wrapper set to min-height: 100% in order that our live example works.
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
syntax the -ms-high-contrast media feature is specified as one of the following values.
... example the following declarations will match applications that are being displayed in high contrast mode with any color variation, a black-on-white color variation, and a white-on-black color variation, respectively.
Privacy and the :visited selector - CSS: Cascading Style Sheets
only the following styles can be applied to visited links: color background-color border-color (and its sub-properties) column-rule-color outline-color the color parts of the fill and stroke attributes in addition, even for the above styles, you won't be able to change the transparency between unvisited and visited links, as you otherwise would be able to using rgba(), hsla(), or the transparent keyword.
...they may, however, require the following changes to existing sites: using background images to style links based on whether they've been visited will no longer work, since only colors can be used to style visited links.
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
with the following css: .two { --test: 10px; } .three { --test: 2em; } in this case, the results of var(--test) are: for the class="two" element: 10px for the class="three" element: 2em for the class="four" element: 10px (inherited from its parent) for the class="one" element: invalid value, which is the default value of any custom property keep in mind that these are custom properties, not actual v...
...the function only accepts two parameters, assigning everything following the first comma as the second parameter.
Viewport concepts - CSS: Cascading Style Sheets
sticky headers or footers, with the following styles, will stick to the top and bottom of the layout viewport respectively.
...to tell a mobile browser to use the viewport width instead of the default 980px as the width of the screen, developers can include a viewport meta tag, like the following: <meta name="viewport" content="width=device-width"> the width property controls the size of the viewport.
background - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: background-attachment background-clip background-color background-image background-origin background-position background-repeat background-size syntax /* using a <background-color> */ background: green; /* using a <bg-image> and <repeat-style> */ background: url("test.jpg") repeat-y; /* using a <box> and <background-color> */ background: border-box red; /* a single...
... the syntax of each layer is as follows: each layer may include zero or one occurrences of any of the following values: <attachment> <bg-image> <position> <bg-size> <repeat-style> the <bg-size> value may only be included immediately after <position>, separated with the '/' character, like this: "center/80%".
border-block-end - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-block-end-color border-block-end-style border-block-end-width syntax border-block-end: 1px; border-block-end: 2px dotted; border-block-end: medium dashed blue; border-block-end can be used to set the values for one or more of border-block-end-width, border-block-end-style, and border-block-end-color.
... values the border-block-end is specified with one or more of the following, in any order: <'border-width'> the width of the border.
border-block-start - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-block-start-color border-block-start-style border-block-start-width syntax border-block-start: 1px; border-block-start: 2px dotted; border-block-start: medium dashed blue; border-block-start can be used to set the values for one or more of border-block-start-width, border-block-start-style, and border-block-start-color.
... values the border-block-start is specified with one or more of the following, in any order: <'border-width'> the width of the border.
border-inline-end - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-inline-end-color border-inline-end-style border-inline-end-width syntax border-inline-end: 1px; border-inline-end: 2px dashed; border-inline-end: medium dashed blue; the physical border to which border-inline-end maps depends on the element's writing mode, directionality, and text orientation.
... shorthand:border-bottom-style: as specifiedborder-left-style: as specifiedborder-right-style: as specifiedborder-top-style: as specifiedborder-inline-end-color: computed coloranimation typeas each of the properties of the shorthand:border-inline-end-color: a colorborder-inline-end-style: discreteborder-inline-end-width: a length values the border-inline-end is specified with one or more of the following, in any order: <'border-width'> the width of the border.
border-inline-start - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-inline-start-color border-inline-start-style border-inline-start-width syntax border-inline-start: 1px; border-inline-start: 2px dotted; border-inline-start: medium dashed green; the physical border to which border-inline-start maps depends on the element's writing mode, directionality, and text orientation.
... values the border-inline-start is specified with one or more of the following, in any order: <'border-width'> the width of the border.
border-style - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-bottom-style border-left-style border-right-style border-top-style syntax /* keyword values */ border-style: none; border-style: hidden; border-style: dotted; border-style: dashed; border-style: solid; border-style: double; border-style: groove; border-style: ridge; border-style: inset; border-style: outset; /* vertical | horizontal */ border-style: dotted solid; /* top...
...it can have the following values: none like the hidden keyword, displays no border.
border-width - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-bottom-width border-left-width border-right-width border-top-width syntax /* keyword values */ border-width: thin; border-width: medium; border-width: thick; /* <length> values */ border-width: 4px; border-width: 1.2rem; /* vertical | horizontal */ border-width: 2px 1.5em; /* top | horizontal | bottom */ border-width: 1px 2em 1.5cm; /* top | right | bottom | left */ border-width: 1px 2em 0 4...
...if it's a keyword, it must be one of the following values: thin a thin border medium a medium border thick a thick border note: because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific.
border - CSS: Cascading Style Sheets
WebCSSborder
constituent properties this property is a shorthand for the following css properties: border-color border-style border-width syntax /* style */ border: solid; /* width | style */ border: 2px dotted; /* style | color */ border: outset #f33; /* width | style | color */ border: medium dashed green; /* global values */ border: inherit; border: initial; border: unset; the border property may be specified using one, two, or three of the values listed below.
...however, outlines differ from borders in the following ways: outlines never take up space, as they are drawn outside of an element's content.
break-after - CSS: Cascading Style Sheets
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.
... formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | always | all | avoid-page | page | left | right | recto | verso | avoid-column | column | avoid-region | region examples breaking into neat columns in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of <h2>s and paragraphs laid out in multiple columns using column-width: 200px.
break-before - CSS: Cascading Style Sheets
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.
... formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | always | all | avoid-page | page | left | right | recto | verso | avoid-column | column | avoid-region | region examples breaking into neat columns in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of <h2>s and paragraphs laid out in multiple columns using column-width: 200px.
break-inside - CSS: Cascading Style Sheets
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.
... subset of values should be aliased as follows: page-break-inside break-inside auto auto avoid avoid formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | avoid-page | avoid-column | avoid-region examples avoiding breaking inside a figure in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of paragraphs laid out in multiple columns using column-width: 200px.
clip-path - CSS: Cascading Style Sheets
WebCSSclip-path
the geometry box can be one of the following values: margin-box uses the margin box as the reference box.
...ner viewbox"> <svg viewbox="0 0 192 192"> <g class="none"> <rect x="24" y="24" width="144" height="144" /> <text x="96" y="91">i love</text> <text x="96" y="109" class="em">clipping</text> </g> </svg> </div> </div> </div> <div class="note">clip-path: url(#mypath)<br><br> assuming the following clippath definition: <pre> &lt;svg&gt; &lt;clippath id="mypath" clippathunits="objectboundingbox"&gt; &lt;path d="m0.5,1 c 0.5,1,0,0.7,0,0.3 a 0.25,0.25,1,1,1,0.5,0.3 a 0.25,0.25,1,1,1,1,0.3 c 1,0.7,0.5,1,0.5,1 z" /&gt; &lt;/clippath&gt; &lt;/svg&gt;</pre> </div> <div class="row"> <div class="cell"> <span>html</span> <div class="containe...
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
for example to make a heading inline we would use the following css: h1 { display: inline; } more recently we have gained css grid layout and flexbox.
...this means that some following text could come up alongside the flex container.
filter - CSS: Cascading Style Sheets
WebCSSfilter
; filter: contrast(200%); filter: drop-shadow(16px 16px 20px blue); filter: grayscale(50%); filter: hue-rotate(90deg); filter: invert(75%); filter: opacity(25%); filter: saturate(30%); filter: sepia(60%); /* multiple filters */ filter: contrast(175%) brightness(3%); /* use no filter */ filter: none; /* global values */ filter: inherit; filter: initial; filter: unset; with a function, use the following: filter: <filter-function> [<filter-function>]* | none for a reference to an svg <filter> element, use the following: filter: url(file.svg#filter-element-id) interpolation if both the beginning and end filters have a function list of the same length without <url>, each of their filter functions is interpolated according to its specific rules.
...the following example enhances the contrast and brightness of the image: filter: contrast(175%) brightness(103%) <table class="standard-table"> <thead> <tr> <th style="text-align: left;" scope="col">original image</th> <th style="text-align: left;" scope="col">live example</th> <th style="text-align: left;" scope="col">static example</th> </tr> </thead> <tbody> <tr> ...
font-family - CSS: Cascading Style Sheets
the following keywords are defined: serif glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings.
... for example, the following declarations are valid: font-family: gill sans extrabold, sans-serif; font-family: "goudy bookletter 1911", sans-serif; the following declarations are invalid: font-family: goudy bookletter 1911, sans-serif; font-family: red/black, sans-serif; font-family: "lucida" grande, sans-serif; font-family: ahem!, sans-serif; font-family: test@foo, sans-serif; font-family: #pound, sans-serif; font-famil...
font-size - CSS: Cascading Style Sheets
WebCSSfont-size
ont-size: medium; font-size: large; font-size: x-large; font-size: xx-large; font-size: xxx-large; /* <relative-size> values */ font-size: smaller; font-size: larger; /* <length> values */ font-size: 12px; font-size: 0.8em; /* <percentage> values */ font-size: 80%; /* global values */ font-size: inherit; font-size: initial; font-size: unset; the font-size property is specified in one of the following ways: as one of the absolute-size or relative-size keywords as a <length> or a <percentage>, relative to the parent element's font size values xx-small, x-small, small, medium, large, x-large, xx-large, xxx-large absolute-size keywords, based on the user's default font size (which is medium).
...take the following html and css: html { font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ } span { font-size: 1.6em; } <div> <span>outer <span>inner</span> outer</span> </div> the result is: assuming that the browser's default font-size is 16px, the words “outer” would be rendered at 16px, but the word “inner” would be rendered at 25.6px.
font-variation-settings - CSS: Cascading Style Sheets
weight (wght) the following live example's css can be edited to allow you to play with font weight values.
... slant (slnt) the following live example's css can be edited to allow you to play with font slant/oblique values.
font-weight - CSS: Cascading Style Sheets
fallback weights if the exact weight given is unavailable, then the following rule is used to determine the weight actually rendered: if the target weight given is between 400 and 500 inclusive: look for available weights between the target and 500, in ascending order.
... inherited value bolder lighter 100 400 100 200 400 100 300 400 100 400 700 100 500 700 100 600 900 400 700 900 400 800 900 700 900 900 700 common weight name mapping the numerical values 100 to 900 roughly correspond to the following common weight names (see the opentype specification): value common weight name 100 thin (hairline) 200 extra light (ultra light) 300 light 400 normal (regular) 500 medium 600 semi bold (demi bold) 700 bold 800 extra bold (ultra bold) 900 black (heavy) 950 extra ...
grid-template - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: grid-template-areas grid-template-columns grid-template-rows syntax /* keyword value */ grid-template: none; /* grid-template-rows / grid-template-columns values */ grid-template: 100px 1fr / 50px 1fr; grid-template: auto 1fr / auto 1fr auto; grid-template: [linename] 100px / [columnname1] 30% [columnname2] 70%; grid-template: fit-content(100px) / fit-content(40%); /* grid-t...
... sets grid-template-areas to the strings listed, grid-template-rows to the track sizes following each string (filling in auto for any missing sizes), and splicing in the named lines defined before/after each size, and grid-template-columns to the track listing specified after the slash (or none, if not specified).
<length-percentage> - CSS: Cascading Style Sheets
examples length-percentage examples the following simple example demonstrates several properties that use <length-percentage> values.
...therefore, all of the following values are acceptable for width: width: 200px; width: 20%; width: calc(100% - 200px); specifications specification status comment css values and units module level 4the definition of '<length-percentage>' in that specification.
outline - CSS: Cascading Style Sheets
WebCSSoutline
constituent properties this property is a shorthand for the following css properties: outline-color outline-style outline-width syntax /* style */ outline: solid; /* color | style */ outline: #f66 dashed; /* style | width */ outline: inset thick; /* color | style | width */ outline: green solid 3px; /* global values */ outline: inherit; outline: initial; outline: unset; the outline property may be specified using one, two, or three of the values listed below.
...however, outlines differ from borders in the following ways: outlines never take up space, as they are drawn outside of an element's content.
place-self - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: align-self justify-self syntax /* keyword values */ place-self: auto center; place-self: normal start; /* positional alignment */ place-self: center normal; place-self: start auto; place-self: end normal; place-self: self-start auto; place-self: self-end normal; place-self: flex-start auto; place-self: flex-end normal; place-self: left auto; place-self: right normal; /* b...
... examples simple demonstration in the following example we have a simple 2 x 2 grid layout.
text-emphasis-position - CSS: Cascading Style Sheets
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.
text-overflow - CSS: Cascading Style Sheets
formal definition initial valueclipapplies toblock container elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ clip | ellipsis | <string> ]{1,2} examples css p { width: 200px; border: 1px solid; padding: 2px 5px; /* both of the following are required for text-overflow */ white-space: nowrap; overflow: hidden; } .overflow-visible { white-space: initial; } .overflow-clip { text-overflow: clip; } .overflow-ellipsis { text-overflow: ellipsis; } .overflow-string { /* not supported in most browsers, see the 'browser compatibility' section below */ text-overflow: " [..]"; } html <p class="overflow-visible">lore...
...m ipsum dolor sit amet, consectetur adipisicing elit.</p> <p class="overflow-clip">lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> <p class="overflow-ellipsis">lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> <p class="overflow-string">lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> result note: live results in the following table may be shown incorrectly due to a limitation of the mdn editor which removes the all contents of style attributes which have text-overflow properties with string value.
matrix3d() - CSS: Cascading Style Sheets
a1a2a3a4b1b2b3b4c1c2c3c4d1d2d3d4 examples cube squashing example the following example shows a 3d cube created from dom elements and transforms, which can be hovered/focused to apply a matrix3d() transform to it.
... the matrix below describes the following transformations: translates every x point by -50px translates every y point by -100px translates every z point by 0 scales down by 10% */ transform: matrix3d( 1,0,0,0, 0,1,0,0, 0,0,1,0, -50,-100,0,1.1 ); } 50% { transform: matrix3d( 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,0.9 ); } to { t...
will-change - CSS: Cascading Style Sheets
the <animateable-feature> can be one of the following values: scroll-position indicates that the author expects to animate or change the scroll position of the element in the near future.
...it cannot be one of the following values: unset, initial, inherit, will-change, auto, scroll-position, or contents.
Cross-browser audio basics - Developer guides
given the following html: <audio id="my-audio" src="audiofile.mp3"> ...
... browser support the following tables list basic audio support across desktop and mobile browsers, and what audio codecs are supported.
Video player styling basics - Developer guides
for example, the play/pause button has the following background image definitions (the full base64 strings have been omitted for brevity): .controls button[data-state="play"] { background-image: url('data:image/png;base64,ivborw0kggoaaa ...
... progress bar the <progress> element has the following basic style set up: .controls progress { display:block; width:100%; height:81%; margin-top:0.125rem; border:none; color:#0095dd; -moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px; } like the <button> elements, <progress> also has a default border, which is removed here.
Creating a cross-browser video player - Developer guides
the control set most browser's default video controls have the following functionality: play/pause mute volume control progress bar skip ahead go fullscreen the custom control set will also support this functionality, with the addition of a stop button.
... to detect if a browser actually supports the fullscreen api and that it is enabled, the following may be called: var fullscreenenabled = !!(document.fullscreenenabled || document.mozfullscreenenabled || document.msfullscreenenabled || document.webkitsupportsfullscreen || document.webkitfullscreenenabled || document.createelement('video').webkitrequestfullscreen); this simply tests all the different prefixed (and of course the non-prefixed!) booleans to see if fullscreen is possible.
XHTML - Developer guides
WebGuideHTMLXHTML
the following example shows an html document and corresponding "xhtml" document, and the accompanying http content-type headers they should be served with.
...the problems are described in more details in the following articles: beware of xhtml by david hammond sending xhtml as text/html considered harmful by ian hickson xhtml's dirty little secret by mark pilgrim xhtml - what's the point?
Parsing and serializing XML - Developer guides
creating an xml document using one of the following approaches to create an xml document (which is an instance of document.
... use the following approaches to serialize the contents of the xml document you created in the previous section.
Printing - Developer guides
using a print style sheet add the following to your <head> tag.
...the following is a possible example which will print a file named externalpage.html: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>mdn example</title> <script type="text/javascript"> function closeprint () { document.body.removechild(this.__container__); } function setprint () { this.contentwindow.__container__ = this; this.contentwindow.onbe...
User input and controls - Developer guides
user input and controls workflow the following diagram illustrates the typical workflow for implementing user input mechanisms: first of all, you need to decide which input mechanisms you want to cover in your application out of mouse, keyboard, finger touch and so on.
... the following is a set of recommendations and best practices for using such tools in open web apps.
HTML attribute: accept - HTML: Hypertext Markup Language
each unique file type specifier may take one of the following forms: a valid case-insensitive filename extension, starting with a period (".") character.
... formats and pdf files, might look like this: <input type="file" accept="image/*,.pdf"> using file inputs a basic example <form method="post" enctype="multipart/form-data"> <div> <label for="file">choose file to upload</label> <input type="file" id="file" name="file" multiple> </div> <div> <button>submit</button> </div> </form> div { margin-bottom: 10px; } this produces the following output: note: you can find this example on github too — see the source code, and also see it running live.
HTML attribute: crossorigin - HTML: Hypertext Markup Language
these attributes are enumerated, and have the following possible values: keyword description anonymous cors requests for this element will have the credentials flag set to 'same-origin'.
... example: crossorigin with the script element you can use the following <script> element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials.
Block-level elements - HTML: Hypertext Markup Language
the following example demonstrates the block-level element's influence: block-level elements html <p>this paragraph is a block-level element; its background has been colored to display the paragraph's parent element.</p> css p { background-color: #8abb55; } usage block-level elements may appear only within a <body> element.
... elements the following is a complete list of all html "block-level" elements (although "block-level" is not technically defined for elements that are new in html5).
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
examples all headings the following code shows all the heading levels, in use.
... <h1>heading level 1</h1> <h2>heading level 2</h2> <h3>heading level 3</h3> <h4>heading level 4</h4> <h5>heading level 5</h5> <h6>heading level 6</h6> here is the result of this code: example page the following code shows a few headings with some content under them.
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
referrerpolicy how much of the referrer to send when following the link.
...the following keywords have special meanings for where to load the url: _self: the current browsing context.
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
it may have one of the following values: none: indicates that the audio should not be preloaded.
... examples basic usage the following example shows simple usage of the <audio> element to play an ogg file.
<base>: The Document Base URL element - HTML: Hypertext Markup Language
WebHTMLElementbase
if either of the following attributes are specified, this element must come before other elements with attribute values of urls, such as <link>’s href attribute.
... the following keywords have special meanings: _self (default): show the result in the current browsing context.
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
WebHTMLElementcanvas
the following is some data we've collected from various tests and other sources (e.g.
...the following guides can help to make it more accessible.
<caption>: The Table Caption element - HTML: Hypertext Markup Language
WebHTMLElementcaption
deprecated attributes the following attributes are deprecated and should not be used.
...it may have one of the following values: left the caption is displayed to the left of the table.
<form> - HTML: Hypertext Markup Language
WebHTMLElementform
attributes for form submission the following attributes control behavior during form submission.
...the following keywords have special meanings: _self (default): load into the same browsing context as the current one.
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, email inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid multiple whether or not to allow multipl...
...browsers that implement the specification should be using an algorithm equivalent to the following regular expression: /^[a-za-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-za-z0-9](?:[a-za-z0-9-]{0,61} [a-za-z0-9])?(?:\.[a-za-z0-9](?:[a-za-z0-9-]{0,61}[a-za-z0-9])?)*$/ to learn more about how form validation works and how to take advantage of the :valid and :invalid css properties to style the input based on whether or not the current value is valid, see form data validation.
<input type="hidden"> - HTML: Hypertext Markup Language
WebHTMLElementinputhidden
note: there is a live example below the following line of code — if it is working correctly, you should see nothing!
... additional attributes in addition to the attributes common to all <input> elements, hidden inputs offer the following attributes: attribute description name like all input types, the name of the input to report when submitting the form; the special value _charset_ causes the hidden input's value to be reported as the character encoding used to submit the form name this is actually one of the common attributes, but it has a special meaning available for hidden inputs.
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, password field inputs support the following attributes: attribute description maxlength the maximum length the value may be, in utf-16 characters minlength the minimum length in characters that will be considered valid pattern a regular expression the value must match in order to be valid placeholder an example value to display in the field when the field is empty re...
...for passwords, this should typically be one of the following: on allow the browser or a password manager to automatically fill out the password field.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
additional attributes in addition to the common attributes shared by all <input> elements, radio inputs support the following attributes: attribute description checked a boolean indicating whether or not this radio button is the currently-selected item in the group value the string to use as the value of the radio when submitting the form, if the radio is currently toggled on checked a boolean attribute which, if present, indicates that this radio button is the currently ...
... styling radio inputs the following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements.
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
you can also get and set the value in javascript using the input element's value property, for example: var weekcontrol = document.queryselector('input[type="week"]'); weekcontrol.value = '2017-w45'; additional attributes in addition to the attributes common to <input> elements, week inputs offer the following attributes: attribute description max the latest year and week to accept as valid input min the earliest year and week to accept as valid input readonly a boolean which, if present, indicates that the user cannot edit the field's contents step the stepping interval (the distance between allowed values) to use for both user interface...
...in the following example we are setting a minimum value of week 01, 2017 and a maximum value of week 52, 2017: <form> <label for="week">what week would you like to start?</label> <input id="week" type="week" name="week" min="2017-w01" max="2017-w52"> <span class="validity"></span> </form> here's the css used in the above example.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
it may have the following values: any, meaning that the icon can be scaled to any size as it is in a vector format, like image/svg+xml.
... examples including a stylesheet to include a stylesheet in a page, use the following syntax: <link href="style.css" rel="stylesheet"> providing alternative stylesheets you can also specify alternative style sheets.
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
the value of this attribute will be in one of the following categories: omitted or a javascript mime type: this indicates the script is javascript.
... <script src="javascript.js"></script> and the following examples show how to put (an inline) script inside the <script> element.
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementtt
<p>enter the following at the telnet command prompt: <code>set localecho</code><br /> the telnet client should display: <tt>local echo is on</tt></p> result overriding the default font you can override the browser's default font—if the browser permits you to do so, which it isn't required to do—using css: css tt { font-family: "lucida console", "menlo", "monaco", "courier", monospace; } h...
...tml <p>enter the following at the telnet command prompt: <code>set localecho</code><br /> the telnet client should display: <tt>local echo is on</tt></p> result usage notes the <tt> element is, by default, rendered using the browser's default non-proportional font.
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
it can have the following values: 17 hidden global attributes, html, reference the hidden global attribute is a boolean attribute indicating that the element is not yet, or is no longer, relevant.
... 176 <plaintext>: the plain text element (deprecated) element, html, obsolete, plain text, reference, web, plaintext the html plaintext element (<plaintext>) renders everything following the start tag as raw text, ignoring any following html.
MIME types (IANA media types) - HTTP
for historical reasons, the mime sniffing standard (the definition of how browsers should interpret media types and figure out what to do with content that doesn't have a valid one) allows javascript to be served using any mime type that essentially matches any of the following: application/javascript application/ecmascript application/x-ecmascript application/x-javascript text/javascript text/ecmascript text/javascript1.0 text/javascript1.1 text/javascript1.2 text/javascript1.3 text/javascript1.4 text/javascript1.5 text/jscript text/livescript text/x-ecmascript text/x-javascript note: even though any given user agent may sup...
... content-type: multipart/form-data; boundary=aboundarystring (other headers associated with the multipart document as a whole) --aboundarystring content-disposition: form-data; name="myfile"; filename="img.jpg" content-type: image/jpeg (data) --aboundarystring content-disposition: form-data; name="myfield" (data) --aboundarystring (more subparts) --aboundarystring-- the following <form>: <form action="http://localhost:8000/" method="post" enctype="multipart/form-data"> <label>name: <input name="mytextfield" value="test"></label> <label><input type="checkbox" name="mycheckbox"> check</label> <label>upload file: <input type="file" name="myfile" value="test.txt"></label> <button>send the file</button> </form> will send this message: post / http/1.1 host: localhost...
Cache-Control - HTTP
header type general header forbidden header name no cors-safelisted response header yes syntax caching directives have the following rules to be valid: case-insensitive, but lowercase is recommended.
... examples preventing caching to disable caching of a resource, you can send the following response header: good: cache-control: no-store bad: cache-control: private,no-cache,no-store,max-age=0,must-revalidate,pre-check=0,post-check=0 caching static assets for the files in the application that will not change, you can usually add aggressive caching by sending the response header below.
CSP: base-uri - HTTP
syntax one or more sources can be allowed for the base-uri policy: content-security-policy: base-uri <source>; content-security-policy: base-uri <source> <source>; sources while this directive uses the same arguments as other csp directives, some of them don’t make sense for `<base>`, such as the keywords 'unsafe-inline' and 'strict-dynamic' <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... <meta http-equiv="content-security-policy" content="base-uri 'self'"> <base href="https://example.com/"> // error: refused to set the document's base uri to 'https://example.com/' // because it violates the following content security policy // directive: "base-uri 'self'" specifications specification status comment content security policy level 3the definition of 'base-uri' in that specification.
CSP: connect-src - HTTP
syntax one or more sources can be allowed for the connect-src policy: content-security-policy: connect-src <source>; content-security-policy: connect-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: connect-src https://example.com/ the following connections are blocked and won't load: <a ping="https://not-example.com"> <script> var xhr = new xmlhttprequest(); xhr.open('get', 'https://not-example.com/'); xhr.send(); var ws = new websocket("https://not-example.com/"); var es = new eventsource("https://not-example.com/"); navigator.sendbeacon("https://not-example.com/", { ...
CSP: default-src - HTTP
for each of the following directives that are absent, the user agent looks for the default-src directive and uses this value for it: child-src connect-src font-src frame-src img-src manifest-src media-src object-src prefetch-src script-src script-src-elem script-src-attr style-src style-src-elem style-src-attr worker-src csp version 1 directive type fetch directive syntax one or more sources can be allowed for the default-src policy: content-security-policy: default-src <source>; content-security-policy: default-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip...
...the following header: content-security-policy: default-src 'self'; script-src https://example.com is the same as: content-security-policy: connect-src 'self'; font-src 'self'; frame-src 'self'; img-src 'self'; manifest-src 'self'; media-src 'self'; object-src ...
CSP: font-src - HTTP
syntax one or more sources can be allowed for the font-src policy: content-security-policy: font-src <source>; content-security-policy: font-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: font-src https://example.com/ the following font resource loading is blocked and won't load: <style> @font-face { font-family: "myfont"; src: url("https://not-example.com/font"); } body { font-family: "myfont"; } </style> specifications specification status comment content security policy level 3the definition of 'font-src' in that specification.
CSP: form-action - HTTP
syntax one or more sources can be set for the form-action policy: content-security-policy: form-action <source>; content-security-policy: form-action <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... <meta http-equiv="content-security-policy" content="form-action 'none'"> <form action="javascript:alert('foo')" id="form1" method="post"> <input type="text" name="fieldname" value="fieldvalue"> <input type="submit" id="submit" value="submit"> </form> // error: refused to send form data because it violates the following // content security policy directive: "form-action 'none'".
CSP: frame-src - HTTP
syntax one or more sources can be allowed for the frame-src policy: content-security-policy: frame-src <source>; content-security-policy: frame-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: frame-src https://example.com/ the following <iframe> is blocked and won't load: <iframe src="https://not-example.com/"></iframe> specifications specification status comment content security policy level 3the definition of 'frame-src' in that specification.
CSP: img-src - HTTP
syntax one or more sources can be allowed for the img-src policy: content-security-policy: img-src <source>; content-security-policy: img-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: img-src https://example.com/ the following <img> is blocked and won't load: <img src="https://not-example.com/foo.jpg" alt="example picture"> specifications specification status comment content security policy level 3the definition of 'img-src' in that specification.
CSP: manifest-src - HTTP
syntax one or more sources can be allowed for the manifest-src policy: content-security-policy: manifest-src <source>; content-security-policy: manifest-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: manifest-src https://example.com/ the following <link> is blocked and won't load: <link rel="manifest" href="https://not-example.com/manifest"> specifications specification status comment content security policy level 3the definition of 'manifest-src' in that specification.
CSP: media-src - HTTP
syntax one or more sources can be allowed for the media-src policy: content-security-policy: media-src <source>; content-security-policy: media-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: media-src https://example.com/ the following <audio>, <video> and <track> elements are blocked and won't load: <audio src="https://not-example.com/audio"></audio> <video src="https://not-example.com/video"> <track kind="subtitles" src="https://not-example.com/subtitles"> </video> specifications specification status comment content security policy level 3the definition of 'media-src' in that specification.
CSP: object-src - HTTP
syntax one or more sources can be allowed for the object-src policy: content-security-policy: object-src <source>; content-security-policy: object-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... examples violation cases given this csp header: content-security-policy: object-src https://example.com/ the following <object>, <embed>, and <applet> elements are blocked and won't load: <embed src="https://not-example.com/flash"></embed> <object data="https://not-example.com/plugin"></object> <applet archive="https://not-example.com/java"></applet> specifications specification status comment content security policy level 3the definition of 'object-src' in that specification.
CSP: prefetch-src - HTTP
syntax one or more sources can be allowed for the prefetch-src policy: content-security-policy: prefetch-src <source>; content-security-policy: prefetch-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
... example prefetch resources do not match header given a page with the following content security policy: content-security-policy: prefetch-src https://example.com/ fetches for the following code will return network errors, as the urls provided do not match prefetch-src's source list: <link rel="prefetch" src="https://example.org/"></link> <link rel="prerender" src="https://example.org/"></link> specification specification status comment cont...
Expect-CT - HTTP
ct requirements can be satisfied via any one of the following mechanisms: x.509v3 certificate extension to allow embedding of signed certificate timestamps issued by individual logs a tls extension of type signed_certificate_timestamp sent during the handshake supporting ocsp stapling (that is, the status_request tls extension) and providing a signedcertificatetimestamplist when a site enables the expect-ct header, they are requesting that the browser check that any certificate for that site appears in public ct logs.
... example the following example specifies enforcement of certificate transparency for 24 hours and reports violations to foo.example.
Feature-Policy - HTTP
<allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
...it can do so by delivering the following http response header to define a feature policy: feature-policy: microphone 'none'; geolocation 'none' by specifying the 'none' keyword for the origin list, the specified features will be disabled for all browsing contexts (this includes all iframes), regardless of their origin.
SameSite cookies - HTTP
fixing common warnings samesite=none requires secure the following warning might appear in your console: some cookies are misusing the “samesite“ attribute, so it won’t work as expected.
... cookies without samesite default to samesite=lax recent versions of modern browsers provide a more secure default for samesite to your cookies and so the following message might appear in your console: some cookies are misusing the “samesite“ attribute, so it won’t work as expected.
Strict-Transport-Security - HTTP
by following the guidelines and successfully submitting your domain, browsers will never connect to your domain using an insecure connection.
... strict-transport-security: max-age=31536000; includesubdomains in the following example, max-age is set to 2 years, raised from what was a former limit max-age of 1 year.
HTTP headers - HTTP
WebHTTPHeaders
the provided pixel value is a number rounded to the smallest following integer (i.e.
...the provided pixel value is a number rounded to the smallest following integer (i.e.
Link prefetching FAQ - HTTP
yes, we send the following header along with each prefetch request: x-moz: prefetch of course, this request header is not at all standardized, and it may change in future mozilla releases.
... privacy implications along with the referral and url-following implications already mentioned above, prefetching will generally cause the cookies of the prefetched site to be accessed.
Network Error Logging - HTTP
the following object keys can be specified in the nel header: report_to the reporting api group to send network error reports to (see below).
... "https://example.com/previous-page", "body": { "elapsed_time": 18, "method": "post", "phase": "dns", "protocol": "http/1.1", "referrer": "https://example.com/previous-page", "sampling_fraction": 1, "server_ip": "", "status_code": 0, "type": "dns.name_not_resolved", "url": "https://example-host.com/" } } the type of the network error may be one of the following pre-defined values from the specification, but browsers can add and send their own error types: dns.unreachable the user's dns server is unreachable dns.name_not_resolved the user's dns server responded but was unable to resolve an ip address for the requested uri.
Proxy Auto-Configuration (PAC) file - HTTP
return value format the javascript function returns a single string if the string is null, no proxies should be used the string can contain any number of the following building blocks, separated by a semicolon: direct connections should be made directly, without any proxies proxy host:port the specified proxy should be used socks host:port the specified socks server should be used recent versions of firefox support as well: http host:port the specified proxy should be used https host:port the specified https proxy should be used socks4 host:po...
...ostname based conditions shexpmatch() time based conditions weekdayrange() daterange() timerange() logging utility alert() there was one associative array (object) already defined, because at the time javascript code was unable to define it by itself: proxyconfig.bindings note: pactester (part of the pacparser package) was used to test the following syntax examples.
Meta programming - JavaScript
terminology the following terms are used when talking about the functionality of proxies.
... handlers and traps the following table summarizes the available traps available to proxy objects.
Quantifiers - JavaScript
types the following table is also duplicated on this cheatsheet.
... note: in the following, item refers not only to singular characters, but also includes character classes, unicode property escapes, groups and ranges.
Using Promises - JavaScript
read the following example: new promise((resolve, reject) => { console.log('initial'); resolve(); }) .then(() => { throw new error('something failed'); console.log('do this'); }) .catch(() => { console.error('do that'); }) .then(() => { console.log('do this, no matter what happened before'); }); this will output the following text: initial do that do this, no matter what happened befor...
...several of these mistakes manifest in the following example: // bad example!
About the JavaScript reference - JavaScript
where to find javascript information javascript documentation of core language features (pure ecmascript, for the most part) includes the following: the javascript guide the javascript reference if you are new to javascript, start with the guide.
... structure of the reference in the javascript reference you can find the following chapters: standard built-in objects this chapter documents all the javascript standard built-in objects, along with their methods and properties.
TypeError: "x" is not a constructor - JavaScript
the following javascript standard built-in objects are not a constructor: math, json, symbol, reflect, intl, atomics.
...to do this, you would write the following function: function car(make, model, year) { this.make = make; this.model = model; this.year = year; } now you can create an object called mycar as follows: var mycar = new car('eagle', 'talon tsi', 1993); in promises when returning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it.
Default parameters - JavaScript
in the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return nan.
... the following function will throw a referenceerror when invoked, because the default parameter value does not have access to the child scope of the function body: function f(a = go()) { // throws a `referenceerror` when `f` is invoked.
arguments.callee - JavaScript
the following example defines a function, which, in turn, defines and returns a factorial function.
... function create() { return function(n) { if (n <= 1) return 1; return n * arguments.callee(n - 1); }; } var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1) a use of arguments.callee with no good alternative however, in a case like the following, there are not alternatives to arguments.callee, so its deprecation could be a bug (see bug 725398): function createperson(sidentity) { var operson = new function('alert(arguments.callee.identity);'); operson.identity = sidentity; return operson; } var john = createperson('john smith'); john(); specifications specification ecmascript (ecma-262)the definition of ...
setter - JavaScript
note the following when working with the set syntax: it can have an identifier which is either a number or a string; it must have exactly one parameter (see incompatible es5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); it must not appear in an object literal with another set or with a data entry for the same property.
... ( { set x(v) { }, set x(v) { } } and { x: ..., set x(v) { } } are forbidden ) examples defining a setter on new objects in object initializers the following example define a pseudo-property current of object language.
Array.prototype.reduce() - JavaScript
it is almost always safer to provide an initialvalue, because there can be up to four possible output types without initialvalue, as shown in the following example: let maxcallback = ( acc, cur ) => math.max( acc.x, cur.x ); let maxcallback2 = ( max, cur ) => math.max( max, cur ); // reduce without initialvalue [ { x: 2 }, { x: 22 }, { x: 42 } ].reduce( maxcallback ); // nan [ { x: 2 }, { x: 22 } ].reduce( maxcallback ); // 22 [ { x: 2 } ].reduce( maxcallback ); // { x: 2 } [ ].reduce...
...( maxcallback ); // typeerror // map & reduce with initialvalue; better solution, also works for empty or larger arrays [ { x: 22 }, { x: 42 } ].map( el => el.x ) .reduce( maxcallback2, -infinity ); how reduce() works suppose the following use of reduce() occurred: [0, 1, 2, 3, 4].reduce(function(accumulator, currentvalue, currentindex, array) { return accumulator + currentvalue }) the callback would be invoked four times, with the arguments and return values in each call being as follows: callback iteration accumulator currentvalue currentindex array return value first call 0 1 1 [0, 1, 2, 3, 4] 1 second call 1 2 2 [0, 1, 2, 3, 4] 3 third call 3 3 3 [0, 1, 2, 3, 4] ...
Array.prototype.concat() - JavaScript
examples concatenating two arrays the following code concatenates two arrays: const letters = ['a', 'b', 'c']; const numbers = [1, 2, 3]; letters.concat(numbers); // result in ['a', 'b', 'c', 1, 2, 3] concatenating three arrays the following code concatenates three arrays: const num1 = [1, 2, 3]; const num2 = [4, 5, 6]; const num3 = [7, 8, 9]; const numbers = num1.concat(num2, num3); console.log(numbers); // results in [1, 2, 3, 4, 5, ...
...6, 7, 8, 9] concatenating values to an array the following code concatenates three values to an array: const letters = ['a', 'b', 'c']; const alphanumeric = letters.concat(1, [2, 3]); console.log(alphanumeric); // results in ['a', 'b', 'c', 1, 2, 3] concatenating nested arrays the following code concatenates nested arrays and demonstrates retention of references: const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.concat' in that specification.
Array.prototype.findIndex() - JavaScript
examples find the index of a prime number in an array the following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number.
... function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log([4, 6, 8, 9, 12].findindex(isprime)); // -1, not found console.log([4, 6, 7, 9, 12].findindex(isprime)); // 2 (array[2] is 7) find index using arrow function the following example finds the index of a fruit using an arrow function: const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; const index = fruits.findindex(fruit => fruit === "blueberries"); console.log(index); // 3 console.log(fruits[index]); // blueberries specifications specification ecmascript (ecma-262)the definition of 'array.prototype.findindex' in that specification.
Array.prototype.indexOf() - JavaScript
you can work around this by utilizing the following code at the beginning of your scripts.
... if (k in o && o[k] === searchelement) return k; } return -1; }; } examples using indexof() the following example uses indexof() to locate values in an array.
Array.isArray() - JavaScript
polyfill running the following code before any other code will create array.isarray() if it's not natively available.
... if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isarray(new array(3)); // little known fact: array.prototype itself is an array: array.isarray(array.prototype); // all following calls return false array.isarray(); array.isarray({}); array.isarray(null); array.isarray(undefined); array.isarray(17); array.isarray('array'); array.isarray(true); array.isarray(false); array.isarray(new uint8array(32)); array.isarray({ __proto__: array.prototype }); instanceof vs isarray when checking for array instance, array.isarray is preferred o...
Array.prototype.join() - JavaScript
examples joining an array four different ways the following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.
... var a = ['wind', 'water', 'fire']; a.join(); // 'wind,water,fire' a.join(', '); // 'wind, water, fire' a.join(' + '); // 'wind + water + fire' a.join(''); // 'windwaterfire' joining an array-like object the following example joins array-like object (arguments), by calling function.prototype.call on array.prototype.join.
Array.prototype.length - JavaScript
examples iterating over an array in the following example, the array numbers is iterated through by looking at the length property.
... var numbers = [1, 2, 3, 4, 5]; var length = numbers.length; for (var i = 0; i < length; i++) { numbers[i] *= 2; } // numbers is now [2, 4, 6, 8, 10] shortening an array the following example shortens the array numbers to a length of 3 if the current length is greater than 3.
Array.prototype.pop() - JavaScript
examples removing the last element of an array the following code creates the myfish array containing four elements, then removes its last element.
... var myfish = ['angel', 'clown', 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the following code creates the myfish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter.
Array.prototype.reverse() - JavaScript
examples reversing the elements in an array the following example creates an array a, containing three elements, then reverses the array.
... const a = [1, 2, 3]; console.log(a); // [1, 2, 3] a.reverse(); console.log(a); // [3, 2, 1] reversing the elements in an array-like object the following example creates an array-like object a, containing three elements and a length property, then reverses the array-like object.
Array.prototype.shift() - JavaScript
examples removing an element from an array the following code displays the myfish array before and after removing its first element.
...in the following example every iteration will remove the next element from an array, until it is empty: var names = ["andrew", "edward", "paul", "chris" ,"john"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // andrew, edward, paul, chris, john specifications specification ecmascript (ecma-262)the definition of 'array.prototype.shift' in that specification.
Array.prototype.some() - JavaScript
you can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it.
... typeerror('array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new typeerror(); } var t = object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisarg, t[i], i, t)) { return true; } } return false; }; } examples testing value of array elements the following example tests whether any element in the array is bigger than 10.
Boolean - JavaScript
for example, the condition in the following if statement evaluates to true: var x = new boolean(false); if (x) { // this code is executed } this behavior does not apply to boolean primitives.
... for example, the condition in the following if statement evaluates to false: var x = false; if (x) { // this code is not executed } do not use a boolean object to convert a non-boolean value to a boolean value.
Date() constructor - JavaScript
individual date and time component values given at least a year and month, this form of date() returns a date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters.
... examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
Date.parse() - JavaScript
examples using date.parse() the following calls all return 1546300800000.
... the first according to es5 will imply utc time, and the others are specifying utc timezone via the iso date specification (z and +00:00) date.parse("2019-01-01") date.parse("2019-01-01t00:00:00.000z") date.parse("2019-01-01t00:00:00.000+00:00") the following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system.
Date.prototype.toGMTString() - JavaScript
syntax dateobj.togmtstring() return value a string representing the given date following the internet greenwich mean time (gmt) convention.
... examples simple example in this example, the togmtstring() method converts the date to gmt (utc) using the operating system's time-zone offset and returns a string value that is similar to the following form.
Error.prototype.stack - JavaScript
examples using the stack property the following html markup demonstrates the use of stack property.
...utf-8"> <title>stack trace example</title> <body> <script> function trace() { try { throw new error('myerror'); } catch(e) { alert(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg'); </script> assuming the above markup is saved as c:\example.html on a windows file system it produces an alert message box with the following text: starting with firefox 30 and later containing the column number: trace@file:///c:/example.html:9:17 b@file:///c:/example.html:16:13 a@file:///c:/example.html:19:13 @file:///c:/example.html:21:9 firefox 14 to firefox 29: trace@file:///c:/example.html:9 b@file:///c:/example.html:16 a@file:///c:/example.html:19 @file:///c:/example.html:21 firefox 13 and earlier would instead produce the f...
Function.caller - JavaScript
consider: function f(n) { g(n - 1); } function g(n) { if (n > 0) { f(n); } else { stop(); } } f(2); at the moment stop() is called the call stack will be: f(2) -> g(1) -> f(1) -> g(0) -> stop() the following is true: stop.caller === g && f.caller === g && g.caller === f so if you tried to get the stack trace in the stop() function like this: var f = stop; var stack = 'stack trace:'; while (f) { stack += '\n' + f.name; f = f.caller; } the loop would never stop.
... examples checking the value of a function's caller property the following code checks the value a function's caller property.
Intl.DisplayNames() constructor - JavaScript
the following unicode extension key is allowed: nu the numbering system to be used.
... options optional an object with some or all of the following properties: localematcher the locale matching algorithm to use.
Intl.ListFormat() constructor - JavaScript
an object with some or all of the following properties: localematcher the locale matching algorithm to use.
... examples using format the following example shows how to create a list formatter using the english language.
Intl.ListFormat - JavaScript
examples using format the following example shows how to create a list formatter using the english language.
...; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car using formattoparts the following example shows how to create a list formatter returning formatted parts const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).formattoparts(list)); // [ { "type": "element", "value": "motorcycle" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "bus" }, // { "type": "literal", "value": ", and ...
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used.
... only one of the following two groups of properties is included: minimumintegerdigits minimumfractiondigits maximumfractiondigits the values provided for these properties in the options argument or filled in as defaults.
Intl.PluralRules() constructor - JavaScript
an object with some or all of the following properties: localematcher the locale matching algorithm to use.
... the following properties fall into two groups: minimumintegerdigits, minimumfractiondigits, and maximumfractiondigits in one group, minimumsignificantdigits and maximumsignificantdigits in the other.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used.
... only one of the following two groups of properties is included: minimumintegerdigits minimumfractiondigits maximumfractiondigits the values provided for these properties in the options argument or filled in as defaults.
Intl.RelativeTimeFormat() constructor - JavaScript
an object with some or all of the following properties: localematcher the locale matching algorithm to use.
... examples basic format usage the following example shows how to create a relative time formatter using the english language.
Intl.RelativeTimeFormat - JavaScript
examples basic format usage the following example shows how to use a relative time formatter for the english language.
...rtf.format(1, "day"); // > "in 1 day" using formattoparts the following example shows how to create a relative time formatter returning formatted parts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit.
JSON.stringify() - JavaScript
therefore, if compatibility with older javascript engines is required, it is perilous to directly substitute the string returned by json.stringify into a javascript string to be passed to eval or new function or as part of a jsonp url, and the following utility can be used: function jsfriendlyjsonstringify (s) { return json.stringify(s).
...az":"quux","foo":"bar"}' console.log(a !== b) // true // some memoization functions use json.stringify to serialize arguments, // which may cause a cache miss when encountering the same object like above example of using json.stringify() with localstorage in a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of json.stringify(): // creating an example of json var session = { 'screens': [], 'state': true }; session.screens.push({ 'name': 'screena', 'width': 450, 'height': 250 }); session.screens.push({ 'name': 'screenb', 'width': 650, 'height': 350 }); session.screens.push({ 'name': 'screenc', 'width': 750, 'height': 120 }); session.screens.push({ 'name': ...
Map.prototype.forEach() - JavaScript
it takes the following arguments: value optional value of each iteration.
... examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new map([['foo', 3], ['bar', {}], ['baz', undefined]]).foreach(logmapelements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object object]" // "map.get('baz') = undefined" specifications specification ecmascript (ecma-...
Math.clz32() - JavaScript
consider the following 32-bit word: var a = 32776; // 00000000000000001000000000001000 (16 leading zeros) math.clz32(a); // 16 var b = ~32776; // 11111111111111110111111111110111 (32776 inversed, 0 leading zeros) math.clz32(b); // 0 (this is equal to how many leading one's there are in a) using this logic, a clon function can be created as follows: var clz = math.clz32; function clon(integer){ return clz...
...owest bits return 32 - clz(~integer) |0; } function ctron(integer) { // count trailing ones integer = integer | 0; // coerce to an integer return ctrz(~integer) |0; } // unfourtunately, asm.js demands slow crummy objects: return {a: ctrz, b: ctron}; })(window, null, null); var ctrz = counttrailsmethods.a; var ctron = counttrailsmethods.b; polyfill the following polyfill is the most efficient.
Math.fround() - JavaScript
internally, javascript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0.
... polyfill this can be emulated with the following function, if float32array are supported: math.fround = math.fround || (function (array) { return function(x) { return array[0] = x, array[0]; }; })(new float32array(1)); supporting older browsers is slower, but also possible: if (!math.fround) math.fround = function(arg) { arg = number(arg); // return early for ±0 and nan.
Number - JavaScript
examples using the number object to assign values to numeric variables the following example uses the number object's properties to assign values to several numeric variables: const biggestnum = number.max_value const smallestnum = number.min_value const infinitenum = number.positive_infinity const neginfinitenum = number.negative_infinity const notanum = number.nan integer range for number the following example shows the minimum and maximum integer values th...
... using number to convert a date object the following example converts the date object to a numerical value using number as a function: let d = new date('december 17, 1995 03:24:00') console.log(number(d)) this logs 819199440000.
Object.prototype.hasOwnProperty() - JavaScript
o = new object(); o.propone = null; o.hasownproperty('propone'); // returns true o.proptwo = undefined; o.hasownproperty('proptwo'); // returns true examples using hasownproperty to test for a property's existence the following example determines whether the o object contains a property named prop: o = new object(); o.hasownproperty('prop'); // returns false o.prop = 'exists'; o.hasownproperty('prop'); // returns true direct vs.
... inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties.
Object.prototype.propertyIsEnumerable() - JavaScript
examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // returns true a.propertyisenumerable(0); // returns true user-defined vs.
... built-in objects the following example demonstrates the enumerability of user-defined vs.
Object.prototype.toSource() - JavaScript
description the tosource() method returns the following values: for the built-in object object, tosource() returns the following string indicating that the source code is not available: function object() { [native code] } for instances of object, tosource() returns a string representing the source code.
... examples using tosource() the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); calling the tosource() method of thedog displays the javascript source that defines the object: thedog.tosource(); // returns ({name:"gab...
Promise.prototype.then() - JavaScript
following, an example to demonstrate the asynchronicity of the then method.
...in the following example, the first then() will return 42 wrapped in a resolving promise even though the previous promise in the chain was rejected.
Promise - JavaScript
for the following code, the transiton of promisea into a "settled" state will cause both instances of .then() to be invoked.
...t( function() { const randomint = date.now(); const value = randomint % 10; try { if(value >= threshold_a) { throw new error(`too large: ${value}`); } } catch(msg) { reject(`error in callback ${msg}`); } resolve(value); return; }, 500); // to experiment with error at set-up, uncomment the following 'throw'.
handler.getPrototypeOf() - JavaScript
} }); parameters the following parameter is passed to the getprototypeof() method.
... description interceptions this trap can intercept these operations: object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof invariants if the following invariants are violated, the proxy will throw a typeerror: getprototypeof() method must return an object or null.
handler.setPrototypeOf() - JavaScript
syntax const p = new proxy(target, { setprototypeof: function(target, prototype) { } }); parameters the following parameters are passed to the setprototypeof() method.
... interceptions this trap can intercept these operations: object.setprototypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a typeerror: if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target).
RegExp() constructor - JavaScript
flags may contain any combination of the following characters: g (global match) find all matches rather than stopping after the first match.
... the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated.
RegExp.prototype.compile() - JavaScript
flags if specified, flags can have any combination of the following values: g global match i ignore case m multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string) y sticky; matches only from the index indicated by the lastindex property of this regular expression in the target string (and does not attempt to match from any later indexes).
... examples using compile() the following example shows how to recompile a regular expression with a new pattern and a new flag.
RegExp.prototype.exec() - JavaScript
description consider the following example: // match "quick brown" followed by "jumps", ignoring characters in between // remember "brown" and "jumps" // ignore case let re = /quick\s(brown).+?(jumps)/ig; let result = re.exec('the quick brown fox jumps over the lazy dog'); the following table shows the results for this script: object property/index description example result [0] the ful...
...'; msg += 'next match starts at ' + myre.lastindex; console.log(msg); } this script displays the following text: found abb.
RegExp.$1-$9 - JavaScript
examples using $n with string.replace the following script uses the replace() method of the string instance to match a name in the format first last and output it in the format last, first.
... var re = /(\w+)\s(\w+)/; var str = 'john smith'; str.replace(re, '$2, $1'); // "smith, john" regexp.$1; // "john" regexp.$2; // "smith" using $n with regexp.test the following script uses the test() method of the regexp instance to grab a number in a generic string.
RegExp.prototype.test() - JavaScript
const str = 'hello world!'; const result = /^hello/.test(str); console.log(result); // true the following example logs a message which depends on the success of the test: function testinput(re, str) { let midstring; if (re.test(str)) { midstring = 'contains'; } else { midstring = 'does not contain'; } console.log(`${str} ${midstring} ${re.source}`); } using test() on a regex with the "global" flag when a regex has the global flag set, test() will advance the lastindex of the reg...
... the following example demonstrates this behaviour: const regex = /foo/g; // the "global" flag is set // regex.lastindex is at 0 regex.test('foo') // true // regex.lastindex is now at 3 regex.test('foo') // false // regex.lastindex is at 0 regex.test('barfoo') // true // regex.lastindex is at 6 regex.test('foobar') //false // regex.lastindex is at 0 // (...and so on) specifications s...
String.prototype.slice() - JavaScript
examples using slice() to create a new string the following example uses slice() to create a new string.
...console.log(str5) // output: "" using slice() with negative indexes the following example uses slice() with negative indexes.
String.prototype.trim() - JavaScript
polyfill running the following code before any other code will create trim() if it's not natively available.
... if (!string.prototype.trim) { string.prototype.trim = function () { return this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; } examples using trim() the following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim()); // 'foo' // another example of .trim() removing whitespace from just one side.
TypedArray.from() - JavaScript
this means that the following are equivalent: typedarray.from(obj, mapfn, thisarg) typedarray.from(array.prototype.map.call(obj, mapfn, thisarg)).
... polyfill you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of from() in implementations that do not natively support it.
TypedArray.prototype.map() - JavaScript
examples mapping a typed array to a typed array of square roots the following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array.
... const numbers = new uint8array([1, 4, 9]); const roots = numbers.map(math.sqrt); // roots is now: uint8array [1, 2, 3], // numbers is still uint8array [1, 4, 9] mapping a typed array of numbers using a function containing an argument the following code shows how map works when a function requiring one argument is used with it.
WebAssembly.Memory - JavaScript
the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib).
... the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above.
WebAssembly.Table() constructor - JavaScript
syntax new webassembly.table(tabledescriptor); parameters tabledescriptor an object that can contain the following members: element a string representing the type of value to be stored in the table.
... examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
WebAssembly.Table.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
... var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification.
WebAssembly.Table.prototype.length - JavaScript
syntax table.length; examples using length the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
... var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification.
encodeURI() - JavaScript
the following example shows all the parts that a uri "scheme" can possibly contain.
...ate throws "urierror: malformed uri sequence" console.log(encodeuri('\ud800')); // lone low surrogate throws "urierror: malformed uri sequence" console.log(encodeuri('\udfff')); encoding for ipv6 if one wishes to follow the more recent rfc3986 for urls, which makes square brackets reserved (for ipv6) and thus not encoded when forming something which could be part of a url (such as a host), the following code snippet may help: function fixedencodeuri(str) { return encodeuri(str).replace(/%5b/g, '[').replace(/%5d/g, ']'); } specifications specification ecmascript (ecma-262)the definition of 'encodeuri' in that specification.
parseFloat() - JavaScript
if parsefloat encounters a character other than a plus sign (+), minus sign (- u+002d hyphen-minus), numeral (0–9), decimal point (.), or exponent (e or e), it returns the value up to that character, ignoring the invalid character and characters following it.
... examples parsefloat returning a number the following examples all return 3.14: parsefloat(3.14); parsefloat('3.14'); parsefloat(' 3.14 '); parsefloat('314e-2'); parsefloat('0.0314e+2'); parsefloat('3.14some non-digit characters'); parsefloat({ tostring: function() { return "3.14" } }); parsefloat returning nan the following example returns nan: parsefloat('ff2'); parsefloat and bigint the following examples both return 900719925474099300,...
Iteration protocols - JavaScript
these protocols can be implemented by any object by simply following some conventions.
... 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.
Logical AND assignment (&&=) - JavaScript
syntax expr1 &&= expr2 description short-circuit evaluation the logical and operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule: (some falsy expression) && expr is short-circuit evaluated to the falsy expression; short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place).
... logical and assignment short-circuits as well meaning that x &&= y is equivalent to: x && (x = y); and not equivalent to the following which would always perform an assignment: x = x && y; examples using logical and assignment let x = 0; let y = 1; x &&= 0; // 0 x &&= 1; // 0 y &&= 1; // 1 y &&= 0; // 0 specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification.
Logical NOT (!) - JavaScript
examples using not the following code shows examples of the !
...n4 = !!false // !!falsy returns false n5 = !!"" // !!falsy returns false n6 = !!boolean(false) // !!falsy returns false converting between nots the following operation involving booleans: !!bcondition is always equal to: bcondition specifications specification ecmascript (ecma-262)the definition of 'logical not expression' in that specification.
Logical nullish assignment (??=) - JavaScript
syntax expr1 ??= expr2 description short-circuit evaluation the nullish coalescing operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule: (some expression that is neither null nor undefined) ??
...(x = y); and not equivalent to the following which would always perform an assignment: x = x ??
instanceof - JavaScript
examples demonstrating that string and date are of type object and exceptional cases the following code uses instanceof to demonstrate that string and date objects are also of type object (they are derived from object).
... ({}) instanceof object // returns true, same case as above mynonobj instanceof object // returns false, prototype is end of prototype chain (null) mystring instanceof date // returns false mydate instanceof date // returns true mydate instanceof object // returns true mydate instanceof string // returns false demonstrating that mycar is of type car and type object the following code creates an object type car and an instance of that object type, mycar.
typeof - JavaScript
description the following table summarizes the possible return values of typeof.
...ypeof declaredbutundefinedvariable === 'undefined'; typeof undeclaredvariable === 'undefined'; // objects typeof {a: 1} === 'object'; // use array.isarray or object.prototype.tostring.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new date() === 'object'; typeof /regex/ === 'object'; // see regular expressions section for historical results // the following are confusing, dangerous, and wasteful.
empty - JavaScript
see the following example with an empty loop body: let arr = [1, 2, 3]; // assign all array values to 0 for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; console.log(arr); // [0, 0, 0] unintentional usage it is a good idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon.
... in the following example, the usage is probably not intentional: if (condition); // caution, this "if" does nothing!
continue - JavaScript
examples using continue with while the following example shows a while loop that has a continue statement that executes when the value of i is 3.
... var i = 0; var n = 0; while (i < 5) { i++; if (i === 3) { continue; } n += i; } using continue with a label in the following example, a statement labeled checkiandj contains a statement labeled checkj.
do...while - JavaScript
when condition evaluates to false, control passes to the statement following the do...while.
... examples using do...while in the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5.
import.meta - JavaScript
note that this will include query parameters and/or hash (i.e., following the ?
... for example, with the following html: <script type="module"> import './index.mjs?someurlinfo=5'; </script> ..the following javascript file will log the `someurlinfo parameter: // index.mjs new url(import.meta.url).searchparams.get('someurlinfo'); // 5 the same applies when a file imports another: // index.mjs import './index2.mjs?someurlinfo=5'; // index2.mjs new url(import.meta.url).searchparams.get('someurlinfo'); // 5 note that while node.js will pass on query parameters (or the hash) as in the latter example, as of node 14.1.0, a url with query parameters will err when loading in the form node --experimental-modules index.mjs?someurlinfo=5 (it is treated as a file rather than a url in this context).
return - JavaScript
for example, the following function returns the square of its argument, x, where x is a number.
... the following return statements all break the function execution: return; return true; return false; return x; return x + y / 3; automatic semicolon insertion the return statement is affected by automatic semicolon insertion (asi).
while - JavaScript
examples using while the following while loop iterates as long as n is less than three.
...therefore, x and n take on the following values: after the first pass: n = 1 and x = 1 after the second pass: n = 2 and x = 3 after the third pass: n = 3 and x = 6 after completing the third pass, the condition n < 3 is no longer true, so the loop terminates.
with - JavaScript
examples using with the following with statement specifies that the math object is the default object.
... the statements following the with statement refer to the pi property and the cos and sin methods, without specifying an object.
Trailing commas - JavaScript
parameter definitions the following function definition pairs are legal and equivalent to each other.
... function f(p) {} function f(p,) {} (p) => {}; (p,) => {}; the trailing comma also works with method definitions for classes or objects: class c { one(a,) {} two(a, b,) {} } var obj = { one(a,) {}, two(a, b,) {}, }; function calls the following function invocation pairs are legal and equivalent to each other.
JavaScript shells - JavaScript
standalone javascript shells the following javascript shells are stand-alone environments, like perl or python.
... shelljs - portable unix shell commands for node.js list of javascript shells the following javascript shells work with mozilla.
icons - Web app manifests
examples "icons": [ { "src": "icon/lowres.webp", "sizes": "48x48", "type": "image/webp" }, { "src": "icon/lowres", "sizes": "48x48" }, { "src": "icon/hd_hi.ico", "sizes": "72x72 96x96 128x128 256x256" }, { "src": "icon/hd_hi.svg", "sizes": "72x72" } ] values image objects may contain the following values: member description sizes a string containing space-separated image dimensions.
... purpose can have one or more of the following values, separated by spaces: monochrome: a user agent can present this icon where a monochrome icon with a solid fill is needed.
Authoring MathML - MathML
for example the following function verifies the mathml support by testing the mspace element (you may replace mspace with mpadded): function hasmathmlsupport() { var div = document.createelement("div"), box; div.innerhtml = "<math><mspace height='23px' width='77px'/></math>"; document.body.appendchild(div); box = div.firstchild.firstchild.getboundingclientrect(); document.body.removechild(div); return math.a...
...bs(box.height - 23) <= 1 && math.abs(box.width - 77) <= 1; } alternatively, the following ua string sniffing will allow to detect the rendering engines with native mathml support (gecko and webkit).
<math> - MathML
WebMathMLElementmath
attributes in addition to the following attributes, the <math> element accepts any attributes of the <mstyle> element.
...it can have one of the following values: block, which means that this element will be displayed outside the current span of text, as a block that can be positioned anywhere without changing the meaning of the text; inline, which means that this element will be displayed inside the current span of text, and cannot be moved out of it without changing the meaning of that text.
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
to keep images from breaking out of their containers when the container becomes narrower than the image, developers started using css like the following: img { max-width: 100%; height: auto; } this is really useful for responsive layouts, but unfortunately it causes the jank problem to return — the above css overrides the width and height attribute information, meaning that if the image has not loaded for some reason, its height will be set to 0.
...this appears in the browser's internal ua stylesheet, similar to the following: img, input[type="image"], video, embed, iframe, marquee, object, table { aspect-ratio: attr(width) / attr(height); } this actually affects any element that acts as a container for complex or mixed visual media — <embed>, <iframe>, <marquee>, <object>, <table>, and <video>, in addition to actual images (<img> and <input type="image">).
Animation performance and frame rate - Web Performance
the rendering waterfall the process a browser uses to paint changes to a page when an element is animating css properties can be described as a waterfall consisting of the following steps: recalculate style: when a property for an element changes, the browser must recalculate computed styles.
... when a canvas is animating a drawing, the canvas animation can be described as a waterfall consisting of the following steps: these sequenced need to fit into a single frame, since the screen isn't updated until it is complete.
Add to Home screen - Progressive web apps (PWAs)
to enable your app to be added to a home screen, it needs the following: to be served over https — the web is increasingly being moved in a more secure direction, and many modern web technologies (a2hs included) will work only on secure contexts.
... the click handler contains the following steps: hide the button again with display: none — it is no longer needed once the app is installed.
How to make PWAs installable - Progressive web apps (PWAs)
requirements to make the web site installable, it needs the following things in place: a web manifest, with the correct fields filled in the web site to be served from a secure (https) domain an icon to represent the app on the device a service worker registered, to allow the app to work offline (this is required only by chrome for android currently) currently, only the chromium-based browsers such as chrome, edge, and samsung internet require the service ...
... the js13kpwa.webmanifest file of the js13kpwa web app is included in the <head> block of the index.html file using the following line of code: <link rel="manifest" href="js13kpwa.webmanifest"> there are a few common kinds of manifest file that have been used in the past: manifest.webapp was popular in firefox os app manifests, and many use manifest.json for web manifests as the contents are organized in a json structure.
Progressive web apps (PWAs)
in order to call a web app a pwa, technically speaking it should have the following features: secure contexts (https), one or more service workers, and a manifest file.
... core pwa guides the following guides show you what need to do to implement a pwa, by examining a simple example and showing you how all the pieces work.
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
example: masking for example, you can make a gradient mask for html content using svg and css code similar to the following, inside your html document: <svg height="0"> <mask id="mask-1"> <lineargradient id="gradient-1" y2="1"> <stop stop-color="white" offset="0"/> <stop stop-opacity="0" offset="1"/> </lineargradient> <circle cx="0.25" cy="0.25" r="0.25" id="circle" fill="white"/> <rect x="0.5" y="0.2" width="300" height="100" fill="url(#gradient-1)"/> </mask> </svg> .target { mask...
...rexponent="10" lighting-color="white"> <fepointlight x="-5000" y="-10000" z="20000"/> </fespecularlighting> </filter> <filter id="f5"> <fecolormatrix values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0" style="color-interpolation-filters:srgb"/> </filter> </svg> the five filters are applied using the following css: p.target { filter:url(#f3); } p.target:hover { filter:url(#f5); } b.target { filter:url(#f1); } b.target:hover { filter:url(#f4); } pre.target { filter:url(#f2); } pre.target:hover { filter:url(#f3); } view this example live example: blurred text in order to blur text, webkit based browsers have a (prefixed) css filter called blur (see also css filter).
begin - SVG: Scalable Vector Graphics
WebSVGAttributebegin
each individual value can be one of the following : <offset-value>, <syncbase-value>, <event-value>, <repeat-value>, <accesskey-value>, <wallclock-sync-value> or the keyword indefinite.
...each value can be one of the following: <offset-value> this value defines a clock-value that represents a point in time relative to the beginning of the svg document (usually the load or domcontentloaded event).
clip - SVG: Scalable Vector Graphics
WebSVGAttributeclip
as a presentation attribute, it can be applied to any element but it has effect only on the following six elements: <svg>, <symbol>, <image>, <foreignobject>, <pattern>, <marker> html,body,svg { height:100% } <svg viewbox="0 0 20 10" xmlns="http://www.w3.org/2000/svg"> <!-- auto clipping --> <svg x="0" width="10" height="10" clip="auto"> <circle cx="5" cy="5" r="4" stroke="green" /> </svg> <!-- rect(top, right, bottom, left) clipping --> <svg x="10" width="10" height="1...
... value auto | rect() default value auto animatable yes the value auto defines a clipping path along the bounds of the viewport created by the given element.the value rect() defines a clipping rectangle following the following syntax: rect(<top>, <right>, <bottom>, <left>).
dominant-baseline - SVG: Scalable Vector Graphics
that font baseline-table is chosen using the following priority order of baseline-table names: ideographic, alphabetic, hanging, mathematical.
...that font baseline-table is chosen using the following priority order of baseline-table names: alphabetic, ideographic, hanging, mathematical.
overflow - SVG: Scalable Vector Graphics
it has the same parameter values and meaning as the css overflow property, however, the following additional points apply: if it has a value of visible, the attribute has no effect (i.e., a clipping rectangle is not created).
... as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <foreignobject>, <iframe>, <image>, <marker>, <pattern>, <symbol>, <svg>, and <text> html, body, svg { height: 100%; } <svg viewbox="0 0 200 30" xmlns="http://www.w3.org/2000/svg" overflow="auto"> <text y="20">this text is wider than the svg, so there should be a scrollbar shown.</text> </svg> usage notes value visible | hidden | scroll | auto de...
paint-order - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following ten elements: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, and <tspan> usage notes value normal | [ fill || stroke || markers ] default value normal animatable yes normal this value indicates that the fill will be painted first, then the stroke, and finally the markers.
...g fill="crimson" stroke="white" stroke-width="6" stroke-linejoin="round" text-anchor="middle" font-family="sans-serif" font-size="50px" font-weight="bold"> <text x="200" y="75">stroke over</text> <text x="200" y="150" paint-order="stroke" id="stroke-under">stroke under</text> </g> </svg> the example would be rendered as follows: the stroke under effect could be achieved via the following css property: #stroke-under { paint-order: stroke; } specifications specification status comment scalable vector graphics (svg) 2the definition of 'paint-order' in that specification.
preserveAspectRatio - SVG: Scalable Vector Graphics
the alignment value must be one of the following keywords: none do not force uniform scaling.
... meet or slice reference the meet or slice reference is optional and, if provided, must be one of the following keywords: meet (the default) - scale the graphic such that: aspect ratio is preserved the entire viewbox is visible within the viewport the viewbox is scaled up as much as possible, while still meeting the other criteria in this case, if the aspect ratio of the graphic does not match the viewport, some of the viewport will extend beyond the bounds of the viewbox (i.e., ...
stroke-dashoffset - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following twelve elements: <altglyph>, <circle>, <ellipse>, <path>, <line>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="-3 0 33 10" xmlns="http://www.w3.org/2000/svg"> <!-- no dash array --> <line x1="0" y1="1" x2="30" y2="1" stroke="black" /> <!-- no dash offset --> <line x1="0" y1="3" x2="30" y2="3" stroke="black" stroke-dasharray="3 1" /> <!-- the start of the dash array computation is pulled by 3...
... --> <line x1="0" y1="7" x2="30" y2="7" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="-3" /> <!-- the start of the dash array computation is pulled by 1 user units which ends up in the same rendering as the previous example --> <line x1="0" y1="9" x2="30" y2="9" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="1" /> <!-- the following red lines highlight the offset of the dash array for each line --> <path d="m0,5 h-3 m0,7 h3 m0,9 h-1" stroke="rgba(255,0,0,.5)" /> </svg> usage notes value <percentage> | <length> default value 0 animatable yes the offset is usually expressed in user units resolved against the pathlength but if a <percentage> is used, the value is resolved a...
stroke-miterlimit - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following nine elements: <altglyph>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="0 0 38 30" xmlns="http://www.w3.org/2000/svg"> <!-- impact of the default miter limit --> <path stroke="black" fill="none" stroke-linejoin="miter" id="p1" d="m1,9 l7 ,-3 l7 ,3 m2,0 l3.5 ,-3 l3.5 ,3 m2,0 l2 ...
... m2, 0 l0.75,-3 l0.75,3 m2, 0 l0.5 ,-3 l0.5 ,3" /> <!-- impact of a large miter limit (8) --> <path stroke="black" fill="none" stroke-linejoin="miter" stroke-miterlimit="8" id="p3" d="m1,29 l7 ,-3 l7 ,3 m2, 0 l3.5 ,-3 l3.5 ,3 m2, 0 l2 ,-3 l2 ,3 m2, 0 l0.75,-3 l0.75,3 m2, 0 l0.5 ,-3 l0.5 ,3" /> <!-- the following pink lines highlight the position of the path for each stroke --> <path stroke="pink" fill="none" stroke-width="0.05" d="m1, 9 l7,-3 l7,3 m2,0 l3.5,-3 l3.5,3 m2,0 l2,-3 l2,3 m2,0 l0.75,-3 l0.75,3 m2,0 l0.5,-3 l0.5,3 m1,19 l7,-3 l7,3 m2,0 l3.5,-3 l3.5,3 m2,0 l2,-3 l2,3 m2,0 l0.75,-3 l0.75,3 m2,0 l0.5,-3 l0.5,3 m1,29 l7,-3 l7,3 m2,0 l3.5,-3 l3.5,3 m2,0 l2,-3 l2,3 m2,...
visibility - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following nineteen elements: <a>, <altglyph>, <audio>, <canvas>, <circle>, <ellipse>, <foreignobject>, <iframe>, <image>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, <tspan>, <video> html, body, svg { height: 100%; } <svg viewbox="0 0 220 120" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="200" height="100" stroke="black" stroke-width="5" fill="...
... example the following example toggles the css visibility of the svg image path.
SVG In HTML Introduction - SVG: Scalable Vector Graphics
(another style rule makes an error message appear.) this approach has the following points in its favor: we have taken a regular html form that could have been part of an existing web site, and added an attractive, interactive background the approach is backwards compatible to browsers that do not support svg; simply, no background appears in them it's very simple and performs very well the picture dynamically sizes itself to the required size in an intelligent way we can...
...like in the following example: var img = document.createelementns("http://www.w3.org/2000/svg", "image"); img.setattributens("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); details the viewbox attribute establishes a logical coordinate system which the svg picture's coordinates are relative to.
SVG fonts - SVG: Scalable Vector Graphics
all following attributes are rendering instructions for the font layout engine, for example, how much of the glyphs' overall heights are ascenders.
... following <font-face-src> is a <missing-glyph> element.
Texts - SVG: Scalable Vector Graphics
WebSVGTutorialTexts
each of the following properties can be set as an attribute or via a css declaration: font-family, font-style, font-weight, font-variant, font-stretch, font-size, font-size-adjust, kerning, letter-spacing, word-spacing and text-decoration.
...s <tspan font-weight="bold" fill="red">bold and red</tspan> </text> playable code <svg width="350" height="60" xmlns="http://www.w3.org/2000/svg"> <text> this is <tspan font-weight="bold" fill="red">bold and red</tspan> </text> <style><![cdata[ text{ dominant-baseline: hanging; font: 28px verdana, helvetica, arial, sans-serif; } ]]></style> </svg> the tspan element has the following custom attributes: x set a new absolute x coordinate for the containing text.
Secure contexts - Web security
some apis on the web are very powerful, giving an attacker the ability to do the following and more: invade a user's privacy.
... resources that are not local, to be considered secure, must meet the following criteria: must be served over https:// or wss:// urls the security properties of the network channel used to deliver the resource must not be considered deprecated feature detection pages can use feature detection to check whether they are in a secure context or not by using the issecurecontext boolean, which is exposed on the global scope.
Using shadow DOM - Web Components
as an example, consider the following html fragment: <!doctype html> <html> <head> <meta charset="utf-8"> <title>simple dom example</title> </head> <body> <section> <img src="dinosaur.png" alt="a red tyrannosaurus rex: a two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."> <p>here we will add a link to the <a href="https://www.mozilla.org...
.../">mozilla homepage</a></p> </section> </body> </html> this fragment produces the following dom structure: shadow dom allows hidden dom trees to be attached to elements in the regular dom tree — this shadow dom tree starts with a shadow root, underneath which can be attached to any elements you want, in the same way as the normal dom.
current - XPath
the following two are symantically equivalent.
...thus within all of the following three expressions the current function (not the entire expressions) returns the same node.
Index - XPath
WebXPathIndex
9 following axe, xpath the following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.
... 10 following-sibling axe, xpath the following-sibling axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
the following is an alphabetized and annotated list of the elements, axes, and functions from the w3c's 1.0 recommendation for xslt, as well as from the appropriate sections of the xpath recommendation.
...essing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported) xsl:with-param (supported) axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self functions boolean() (supported) ceiling() (supported) concat() (supported) contains() (supported) count() (supported) current() (supported) document() (supported) element-available() (supported) false() (supported) floor() (supported) format-number() (supported) function-available...
Converting WebAssembly text format to wasm - WebAssembly
a first look at the text format let’s look at a simple example of this — the following program imports a function called imported_func from a module called imports, and exports a function called exported_func: (module (func $i (import "imports" "imported_func") (param i32)) (func (export "exported_func") i32.const 42 call $i ) ) the webassembly function exported_func is exported for use in our environment (e.g.
...try this: wat2wasm simple.wat -v this will give you an output in your terminal in the following way: ...
Interacting with page scripts - Archive of obsolete content
clicking "i will not work" fails, and the following message is logged: permission denied to access property 'greeting' expose functions to page scripts the structured clone algorithm is a bit more powerful than simple json serialization, but not much: in particular, functions aren't cloned.
Testing the Add-on SDK - Archive of obsolete content
with gulp installed, and after installing the addon-sdk's npm dependencies, we can run the latter three test suites mentioned for cfx with jpm using the following commands: gulp test:examples --filter <addon_example_folder_name> gulp test:addons --filter <addon_folder_name> gulp test:modules --filter <file_name>:<test_name> or run all of the tests with gulp test.
XUL Migration Guide - Archive of obsolete content
the following complete add-on uses nsipromptservice to display an alert dialog: var {cc, ci} = require("chrome"); var promptsvc = cc["@mozilla.org/embedcomp/prompt-service;1"].
clipboard - Archive of obsolete content
the following types are supported: text (plain text) html (a string of html) image (a base-64 encoded png) if no data type is provided, then the module will detect it for you.
hotkeys - Archive of obsolete content
the following commonly used hotkey combinations will not pass amo review: accel-z, accel-c, accel-x, accel-v or accel-q if you choose to use a key combination that's already defined, choose one which makes sense for the operation it will perform.
l10n - Archive of obsolete content
and the following code: var _ = require("sdk/l10n").get; console.log(_("hello_string")); the following output will be logged: info: hello!
private-browsing - Archive of obsolete content
opting into private browsing add-ons built using the sdk must opt into private browsing by setting the following key in their package.json file: "permissions": {"private-browsing": true} if an add-on has not opted in, then the high-level sdk modules will not expose private windows, or objects (such as tabs) that are associated with private windows: the windows module will not list any private browser windows, generate any events for private browser windows, or let the add-on open any private browser...
self - Archive of obsolete content
loadreason this property contains of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade isprivatebrowsingsupported this property indicates whether or not the add-on supports private browsing.
simple-storage - Archive of obsolete content
accessing storage from the console in the add-on debugger, you can access your add-on's simple-storage programmatically from the console using the following: loader.modules['resource://gre/modules/commonjs/sdk/simple-storage.js'].exports.storage clarification from mozilla needed: writing the above line in add-on debugger console results in "referenceerror: loader is not defined".
ui - Archive of obsolete content
this module exports constructors for the following: actionbutton togglebutton frame toolbar sidebar each object has its own reference page, linked above: for all the details please refer to the reference page.
windows - Archive of obsolete content
rowserwindows.length); the currently active window is given by browserwindows.activewindow: var windows = require("sdk/windows").browserwindows; windows.on('activate', function(window) { console.log("a window was activated."); var activewindowtitle = windows.activewindow.title; console.log("active window title is: " + activewindowtitle); }); events the browserwindows property emits the following events which can be listened to using its on function.
console/traceback - Archive of obsolete content
the stack is represented as an array in which the most recent stack frame is the last element; each element thus represents a stack frame and has the following keys: filename the name of the file that the stack frame takes place in.
core/promise - Archive of obsolete content
in the following example we implement functions that take multiple promises and return one that resolves to first one being fulfilled: function race() { let { promise, resolve } = defer(); array.slice(arguments).foreach(function(promise) { promise.then(resolve); }); return promise; } var asyncaorb = race(readasync(urla), readasync(urlb)); note: that this implementation forgives failures and would f...
frame/hidden-frame - Archive of obsolete content
the following code creates a hidden frame, loads a web page into it, and then logs its title: var hiddenframes = require("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ onready: function() { this.element.contentwindow.location = "http://www.mozilla.org/"; let self = this; this.element.addeventlistener("domcontentloaded", function() { console.log(sel...
frame/utils - Archive of obsolete content
remote boolean if true separate process will be used for this frame, and all the following options are ignored.
io/file - Archive of obsolete content
apart from these options, this api always passes the following options: create_file, truncate (see //github.com/realityripple/uxp/blob/master/nsprpub/pr/include/prio.h#550).
places/history - Archive of obsolete content
// we'd compose the query with the following options let lastweek = date.now - (1000*60*60*24*7); search( // first query looks for all entries before last week with 'ruby' [{ query: "ruby", to: lastweek }, // second query searches all entries after last week with 'javascript' { query: "javascript", from: lastweek }], // we want to order chronologically by visit date { sort: "date" } ).on("end", function (results) { // results...
stylesheet/style - Archive of obsolete content
it accepts the following values: "agent", "user" and "author".
system/unload - Archive of obsolete content
it is called with a single argument, one of the following strings describing the reason for unload: "uninstall", "disable", "shutdown", "upgrade", or "downgrade".
test/assert - Archive of obsolete content
usage to use the assert module, write a set of unit tests following the instructions in the unit testing tutorial.
util/collection - Archive of obsolete content
for example, the following code...
util/object - Archive of obsolete content
extend(arguments) returns an object that inherits from the first argument and contains all of the properties from all following arguments, with precedence from right to left.
Adding a Button to the Toolbar - Archive of obsolete content
create a directory called "data", mkdir data and save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png then open the file called "index.js" in the root of your addon directory and add the following code to it: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://www.mozilla.org/"); } now run the add-on with j...
Creating annotations - Archive of obsolete content
first, import the panel module: var panels = require('sdk/panel'); then add the following code to the main() function: var annotationeditor = panels.panel({ width: 220, height: 220, contenturl: data.url('editor/annotation-editor.html'), contentscriptfile: data.url('editor/annotation-editor.js'), onmessage: function(annotationtext) { if (annotationtext) { console.log(this.annotationanchor); console.log(annotationtext); } annotationeditor.hide(); }, ...
Implementing the widget - Archive of obsolete content
main.js now in the lib directory open main.js and add the following code: var widgets = require('sdk/widget'); var data = require('sdk/self').data; var annotatorison = false; function toggleactivation() { annotatorison = !annotatorison; return annotatorison; } exports.main = function() { var widget = widgets.widget({ id: 'toggle-switch', label: 'annotator', contenturl: data.url('widget/pencil-off.png'), contentscriptwhen: 'ready', c...
Storing annotations - Archive of obsolete content
add the following to your add-on's main function: simplestorage.on("overquota", function () { notifications.notify({ title: 'storage space exceeded', text: 'removing recent annotations'}); while (simplestorage.quotausage > 1) simplestorage.storage.annotations.pop(); }); because we use a notification to alert the user, we need to import the notifications module: var notifications = require("sdk/n...
Creating Reusable Modules - Archive of obsolete content
copy the file picker code into this new file, and add the following line at the end: exports.promptforfile = promptforfile; this defines the public interface of the new module.
Getting Started (jpm) - Archive of obsolete content
open it and add the following code: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("http://www.mozilla.org/"); } note that "entry point" defaul...
Getting started (cfx) - Archive of obsolete content
open it and add the following code: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://www.mozilla.org/"); } save the file.
List Open Tabs - Archive of obsolete content
the following add-on adds an action button that logs the urls of open tabs when the user clicks it: require("sdk/ui/button/action").actionbutton({ id: "list-tabs", label: "list tabs", icon: "./icon-16.png", onclick: listtabs }); function listtabs() { var tabs = require("sdk/tabs"); for (let tab of tabs) console.log(tab.url); } note: to get this working, you will need to save an icon for the button to your add-on's "data" directory as "icon-16.png".
Listen for Page Load - Archive of obsolete content
the following add-on listens to the tab's built-in ready event and just logs the url of each tab as the user loads it: require("sdk/tabs").on("ready", logurl); function logurl(tab) { console.log(tab.url); } you will find this console output in the browser console, not the web console.
Modifying the Page Hosted by a Tab - Archive of obsolete content
in the following example, we are loading two scripts, first.js & second.js.
Using XPCOM without chrome - Archive of obsolete content
examples bookmarks observer normally, a bookmark observer would require chrome components and xpcomutils as described in the following links: (observing changes to bookmarks and tags) , (creating event targets).
Alerts and Notifications - Archive of obsolete content
basic modal alert alert('hello'); pop-ups the following code presents a non-modal pop-up, which automatically disappears after an appropriate delay.
Cookies - Archive of obsolete content
setting a cookie the following code demonstrates how to set a cookie in firefox.
Customizing the download progress bar - Archive of obsolete content
in your jar.mn file, add the following (replacing "myextension" with the name of your extension's chrome package): % overlay chrome://mozapps/content/downloads/downloads.xul chrome://myextension/content/downloads-overlay.xul in downloads-overlay.xul, reference the new stylesheet: <?xml version="1.0"?> <?xml-stylesheet href="chrome://myextension/skin/myextension.css" type="text/css"?> <overlay id="mydownloadoverlay" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> </overlay> in jar.mn, make sure that there is an asterisk in front of the entry for myextension.css so that it w...
Downloading Files - Archive of obsolete content
the following methods of downloading files may not work as expected after firefox 26, and should no longer be used.
Finding window handles - Archive of obsolete content
recall that nsibasewindow -> nativehandle returns the following in the different operating systems: windows - hwnd mac os x - nswindow* linux - gdkwindow* (it will be gdkwindow* no matter what desktop/window manager) is in use, for explanation why see the article: standard os libraries - unix section) windows components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!b...
Forms related code snippets - Archive of obsolete content
this date-picker code snippet will automatically create an html code like the following: <table id="zdp-cal-1" class="zdp-calendar" style="z-index: 1026; position: absolute; left: 294px; top: 47px;"> <caption><span id="zdp-decr-year-1" class="zdp-decrease-year">&laquo;</span><span id="zdp-decr-month-1" class="zdp-decrease-month">&lt;</span><span id="zdp-incr-year-1" class="zdp-increase-year">&raquo;</span><span id="zdp-incr-month-1" class="zdp-increase-month">&gt;</span> <sp...
Examples and demos from articles - Archive of obsolete content
[article] typewriter effect [html] the following example will delete and re-type simulating a typewriter all the text content of the nodelist which match a specified group of selectors.
HTML in XUL for rich tooltips - Archive of obsolete content
usetooltip(event)" tooltip="myhtmltip" /> <menuitem id="htmltip2" label="foo2" onmouseover="htmltip.onmousetooltip(event)" tooltip="myhtmltip" /> </popup> <popupset id="mainpopupset"> <tooltip id="myhtmltip"> <html:div id="myhtmltipdiv" type="content"/> </tooltip> </popupset> </overlay> insert your version of the following into the javascript overlay.
HTML to DOM - Archive of obsolete content
", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert our newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textcontent = "this is inside the body!"; using a hidden iframe element to parse html to a window's dom sample code may need more work.
IsDefaultNamespace - Archive of obsolete content
the following is a snippet to get isdefaultnamespace() supported across other browsers.
JavaScript Debugger Service - Archive of obsolete content
jsd.clearfilters(); // clear the list of filters // we exclude the scripts with the following filenames from being tracked jsd.appendfilter(createfilter("*/firefox/components/*")); jsd.appendfilter(createfilter("*/firefox/modules/*")); jsd.appendfilter(createfilter("xstringbundle")); jsd.appendfilter(createfilter("chrome://*")); jsd.appendfilter(createfilter("x-jsd:ppbuffer*")); jsd.appendfilter(createfilter("xpcsafejsobjectwrapper.cpp")); jsd.appendfilter(createfilter("file://*")); not...
Label and description - Archive of obsolete content
note: if running in a xulrunner application add the following preferences to your default preferences file: pref("network.protocol-handler.expose.http", false); pref("network.protocol-handler.warn-external.http", false); change or add additional protocols (https or ftp) as needed.
On page load - Archive of obsolete content
creating an overlay first, you need to create an overlay to one (or more, depending on which applications you target) of the following xul documents: application uri to overlay firefox chrome://browser/content/browser.xul thunderbird chrome://messenger/content/messenger.xul navigator from seamonkey chrome://navigator/content/navigator.xul attaching a script attach a script to your overlay (see "attaching a script to an overlay") that adds a load event listener to appconten...
QuerySelector - Archive of obsolete content
// if you'd like to convert it to a array for convenience, use this instead: // return array.prototype.slice.call(el.queryselectorall(selector)); } alert($('#myid').id); (note that while using the firefox web console, the above functions are available automatically.) both xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or following the jquery style of chaining by returning 'this' within each prototype method of $()): htmldocument.prototype.$ = function (selector) { // only for html return this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { re...
Rosetta - Archive of obsolete content
the following code is nothing but the base for an extensible collection of compilers.
Sidebar - Archive of obsolete content
resizing the sidebar programmatically in case you need to change the width of the sidebar, use the following code: function setsidebarwidth(newwidth) { var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); mainwindow.document.getel...
JavaScript Daemons Management - Archive of obsolete content
the following daemons management framework is the major version of setinterval – a little framework.
XPath - Archive of obsolete content
notes and sample code for xpath and ajax (the following was moved from document.evaluate) obj.evaluate(xpathexpression,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return; } ...
getAttributeNS - Archive of obsolete content
as some browsers do not support getattributens, the following might be used to work on them as well.
Communication between HTML and your extension - Archive of obsolete content
communication between an html page and and extension after building a sample extension by reading carefully and following the complete instructions for building an extension i was able to get an extension that could display something on the status bar.
Extension Packaging - Archive of obsolete content
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>.
How to convert an overlay extension to restartless - Archive of obsolete content
branch : services.prefs; branch.setcomplexvalue(prefname, components.interfaces.nsisupportsstring, string); } just grab the above, move your default preferences file to your chrome mapping, and then do the following line once during your startup: services.scriptloader.loadsubscript("chrome://myaddon/content/defaultprefs.js", {pref:setdefaultpref} ); that's it.
Inline options - Archive of obsolete content
you must also specify the optionstype as 2: <em:optionsurl>chrome://myaddon/content/name_of_my_file_to_use_for_inline_opts.xul</em:optionsurl> <em:optionstype>2</em:optionstype> your chrome.manifest file should contain the following, otherwise the path chrome://myaddon/content/name_of_my_file_to_use_for_inline_opts.xul will not exist content myaddon ./ this method allows you to maintain compatibility with previous versions of firefox by adding an override to your chrome.manifest: ...
Interaction between privileged and non-privileged pages - Archive of obsolete content
in the following code sample 2 methods are combined: setting an extra attribute in the original event target element, and creating a new event message with a new event target element.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
if for some reason you want to override these styles (not recommended), you'll need the following rule: -moz-appearance: none; -moz-appearance can be used in many cases where you want to strip the native look out of an element.
Adding sidebars - Archive of obsolete content
in the following example, the second child will be displayed, not the first which would be the default.
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
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.
Mozilla Documentation Roadmap - Archive of obsolete content
here are some important feeds you should consider following: planet mozilla.
Observer Notifications - Archive of obsolete content
let's see the following example code on how to send out a notification from non-chrome code.
XUL School Tutorial - Archive of obsolete content
the project is now published here following its sharing licenses.
Security best practices in extensions - Archive of obsolete content
non-chrome urls in chrome xul or html such as the following example are not allowed: <script type="text/javascript" src="http://mysite.greatsite.com/js/wow-content.js" /> in general, scripts that are from remote sources that run in the chrome context are not acceptable, as many times the source of the script can never be 100% guaranteed, and they are vulnerable to man-in-the-middle attacks.
Setting up an extension development environment - Archive of obsolete content
in the following example, the described command starts a new instance of firefox, with a profile called dev; even if an instance of firefox is already running.
Signing an XPI - Archive of obsolete content
s\codesigning\signed> zip -r -d fsb.xpi * -x meta-inf/zigbert.rsa adding: meta-inf/manifest.mf (deflated 37%) adding: meta-inf/zigbert.sf (deflated 40%) adding: chrome/fsb.jar (deflated 74%) adding: chrome.manifest (deflated 69%) adding: install.rdf (deflated 62%) test your certificate to test your certificate, install it into your browser, and attempt to load the signed extension by following these steps: 1.
Supporting search suggestions in search plugins - Archive of obsolete content
for example, if the search term is "fir", and you don't need to return descriptions or alternate query urls, you might return the following json: ["fir", ["firefox", "first choice", "mozilla firefox"]] note that in this example, only the query string and completion array are specified, leaving out the optional elements.
Updating addons broken by private browsing changes - Archive of obsolete content
if your code refers to any of the following interfaces: ff 15: nsidomstoragemanager ff 16: nsitransferable ff 18: imgicache moziasyncfavicons nsifaviconservice nsiwebbrowserpersist ff 19: nsicontentprefservice nsidownloadmanager nsidownload nsihttpauthmanager nsistricttransportsecurityservice ff 20: nsiprivatebrowsingservice nsirecentbadcertservice furthermore, if your code uses any of these common chrome apis: ff 19: saveurl saveinternal openlinkin ff 20: openbrowserwindow gprivatebrowsingui finally, if your c...
Using Dependent Libraries In Extension Components - Archive of obsolete content
the following are the necessary modifications you will need in order to write a stub loader for an os x extension.
Underscores in class and ID Names - Archive of obsolete content
note: browser support for underscores in css has greatly improved since this article was originally published in 2001 and the following recommendation is no longer accurate for most circumstances.
CSS3 - Archive of obsolete content
the support of tri-dimensional transforms to be applied to any element by adding the css transform-style, perspective, perspective-origin, and backface-visibility properties and extended the transform property with the following transforms are: matrix 3d(), translate3d(), translatez(), scale3d(), scalez(), rotate3d(), rotatex(), rotatey(), rotatez(), and perspective().
Creating a dynamic status bar extension - Archive of obsolete content
the following sections will examine these one by one.
Creating a status bar extension - Archive of obsolete content
this is accomplished by the following line of xml: <overlay id="status-bar-sample-1-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> once that's accomplished, we can describe our user interface.
DOMSubtreeModified - Archive of obsolete content
example the following code will display the time of last dom change on the title bar of the page.
Install.js - Archive of obsolete content
it assumes the following structure of your xpi file: sampleext.xpi chrome\ sampleext.jar content\ sampleext\ locale\ (optional) en-us\ sampleext\ ...
List of Former Mozilla-Based Applications - Archive of obsolete content
the following is a list of all known applications that at one point used mozilla technologies or that are no longer being actively maintained.
List of Mozilla-Based Applications - Archive of obsolete content
the following is a list of all known active applications that are built using mozilla technologies.
Environment variables affecting crash reporting - Archive of obsolete content
the following environment variables affect crash reporting: moz_crashreporter_url sets the url that the crash reporter will submit reports to.
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
to find the path to the browser executable (exe) applicable to netscape 6.1, 6.2.x, netscape 7.0 (and up), mozilla 1.0, and compuserve 7.0 finding the browser executable is useful if you wish to launch the browser following installation of the plugin dll.
Notes on HTML Reflow - Archive of obsolete content
the reflow reason controls how a frame reacts during a reflow, and is one of the following: initial, for the very first time that the frame hierarchy is flowed.
Same-origin policy for file: URIs - Archive of obsolete content
for cross-window dom access, each file is treated as a separate origin, with one exception: if a file is loaded from another file that would otherwise be able to load it following this same-origin policy, they are considered to have the same origin.
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
the following <embed> attributes have <param> tag equivalents: <param name="type" ...> is equivalent to typespecifies the mime type of the plug-in.
How Mozilla finds its configuration files - Archive of obsolete content
you may use the following items: a program to convert registry.dat file into a readable (and editable) xml file.
How Thunderbird and Firefox find their configuration files - Archive of obsolete content
you'd obtain a file such as the following: [general] startwithlastprofile=1 [profile0] name=default isrelative=0 path=h:\thunderbird a discussion about this file can be found here ...
Locked config settings - Archive of obsolete content
this file also needs to be "called" from c:\program files\mozilla.org\mozilla\defaults\pref\all.js by appending the following line at the end: pref("general.config.filename", "mozilla.cfg"); note: newer versions of mozilla or firefox store the all.js file in greprefs rather than defaults\pref the moz-byteshift.pl script allows to encode...: moz-byteshift.pl -s 13 <mozilla.cfg.txt >mozilla.cfg ...
Protecting Mozilla's registry.dat file - Archive of obsolete content
in summary, you can use the following series of commands in your logon script (usually stored in /home/samba/netlogon/startup.bat on the server): rem ================================================== rem mozilla rem ================================================== attrib -r -s "%userprofile%\application data\mozilla" >nul 2>nul attrib -r -s "%userprofile%\application data\mozilla\registry.dat" >nul 2>nul mkdir "%userprofile%\appl...
Automatically Handle Failed Asserts in Debug Builds - Archive of obsolete content
as an example, consider the following failed assertion: assertion: no document: 'mdocument != nsnull', file d:/cvs-1.11.4/mozilla/content/xul/content/src/nsxulelement.cpp, line 3173 (note that i have my source tree in d:/cvs-1.11.4/mozilla) if you have a dword in hkcu\software\mozilla.org\windbgdlg\ named "d:/cvs-1.11.5/mozilla/content/xul/content/src/nsxulelement.cpp," (with the comma - matches are whole-word only) and value 0x5, th...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
copy the following files into the content sub-subdirectory: tinderstatusoverlay.xul tinderstatus.js tinderstatus.css tb-busted.png tb-nostatus.png tb-success.png tb-testfailed.png these are the files we're going to put into the xpi.
Prerequisites - Archive of obsolete content
in order to complete this tutorial you need to have and know how to use the following programs on your computer: an installation of mozilla; zip and unzip utilities; a text editor.
Specifying the appearance - Archive of obsolete content
make your own icons for the four states or use the following icons: no status , success , test failed and busted .
chrome.manifest - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "chrome.manifest": skin global my_theme jar:chrome/my_theme.jar!/global/ skin mozapps my_theme jar:chrome/my_theme.jar!/mozapps/ skin messenger my_theme jar:chrome/my_theme.jar!/messenger/ skin messenger-newsblog my_theme jar:chrome/my_theme.jar!/messenger-newsblog/ skin communicator my_theme jar:chrome/my_theme.jar!/communicator/ skin help my_theme jar:chrome/my_theme.jar!/help/ skin navigator my_theme jar:chrome/my_theme.jar!/navigator/ skin editor my_theme jar:chrome/my_theme.jar!/editor/ ...
install.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "install.rdf": <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>author@oftheme.com</em:id> <em:version>2.0b1</em:version> <!-- seamonkey --> <em:targetapplication> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.0b1pre</em:minversion> <em:maxversion>2.0b2pre</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>my_theme</em:name> <em:description>my first theme</em:description> <!-- front end integration hooks (used by theme ...
contents.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "contents.rdf": <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <!-- list all the skins being supplied by this theme --> <rdf:seq about="urn:mozilla:skin:root"> <rdf:li resource="urn:mozilla:skin:myskin/1.0" /> </rdf:seq> <rdf:description about="urn:mozilla:skin:myskin/1.0" chrome:displayname="my skin" chrome:accesskey="m" chrome:author="me" chrome:description="this is my custom skin for mozilla" chrome:name="myskin/1.0" chrome:image="preview.png"> <chrome:packages> <rdf:seq about="urn:mozilla:skin:myskin/1.0:packages"> <rdf:li resource="urn:m...
toolbarBindings.xml - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "toolbarbindings.xml": <bindings id="toolbarbindings"> <binding id="toolbar-primary" extends="chrome://global/content/bindings/toolbar.xml#toolbar-primary"> <content> <xul:hbox class="toolbar-holder toolbar-primary-holder" flex="1" xbl:inherits="orient=tborient,buttonstyle"> <xul:hbox class="toolbar-button-box" flex="1"> <children/> </xul:hbox> <xul:image class="toolbar-primary-icon" xbl:inherits="buttonstyle"/> </xul:hbox> </content> </binding> </bindings> ...
Download Manager preferences - Archive of obsolete content
the following table however, includes preferences which must be included in any product for the download manager to function.
Editor Embedding Guide - Archive of obsolete content
first getnext (returns the next name in the name/value pair list) hasmoreelements getvaluetype (numeric enum type see nsicommandparams for values) if the name/value pair is known or it was obtained using the methods described above, it is possible to call the following methods: getbooleanvalue getlongvalue getdoublevalue getstringvalue getcstringvalue getisupportsvalue all of these take pointers to values except for getstringvalue which demands a reference to an nsastring.
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
following on from the above example, to create a new window, we would do the following: // first, get the event queue service.
Exception logging in JavaScript - Archive of obsolete content
note that the following will have no effect on the ns_nointerface exceptions outlined in rules 3 and 4 above - those exceptions will not be reported in any case.
External CVS snapshots in mozilla-central - Archive of obsolete content
the following list of directories (incomplete) contain them.
Disabling interruptible reflow - Archive of obsolete content
add the following variables to your environment to disable gecko interruptible reflow: gecko_reflow_interrupt_mode=counter gecko_reflow_interrupt_frequency=1000000 gecko_reflow_interrupt_checks_to_skip=1000000 now start firefox within this environment.
JSS build instructions for OSX 10.6 - Archive of obsolete content
the following build instructions were provided by pavrw.
GRE Registration - Archive of obsolete content
linux on linux, registration information is kept in ini-style files of the following form: [1.7.10] gre_path=/usr/lib/mozilla-1.7.10 feature=value feature2=value2 these ini files can be in any of the following locations: /etc/gre.conf /etc/gre.d/*.conf ~/.gre.conf ~/.gre.d/*.conf mozilla has never officially shipped a linux gre based on the mozilla suite.
popChallengeResponse - Archive of obsolete content
the resultstring will either be a base-64 encoded popodeckeyrespcontent message, or one of the following error strings: error string description "error:invalidparameter:xxx" the parameter xxx was an invalid value.
Libraries - Archive of obsolete content
the following libraries are available: twitter ...
Settings - Archive of obsolete content
with the above manifest the following stored properties are available in the jetpack's code: * jetpack.storage.settings.twitter.username * jetpack.storage.settings.twitter.password * jetpack.storage.settings.facebook.username * jetpack.storage.settings.facebook.password * jetpack.storage.settings.music * jetpack.storage.settings.volume see also simple storage jep 24 ...
Settings - Archive of obsolete content
with the above manifest the following stored properties are available in the jetpack's code: jetpack.storage.settings.twitter.username jetpack.storage.settings.twitter.password jetpack.storage.settings.facebook.username jetpack.storage.settings.facebook.password jetpack.storage.settings.music jetpack.storage.settings.volume ...
Modularization techniques - Archive of obsolete content
the following example turns nssample.cpp into a file that can be compiled into a dll.
How to Write and Land Nanojit Patches - Archive of obsolete content
the following files in tracemonkey are from nanojit: everything in js/src/nanojit/ everything in js/src/vprof/ scenario 0: a common prefix for all scenarios make private clones of all three repositories: nanojit-central, tracemonkey and tamarin-redux.
Bundles - Archive of obsolete content
sic web application bundle: create file called webapp.ini that contains something like: [parameters] id=unique-app-id@unique-author-id.whatever name=webapp name uri=http://[the-url-what-you-want-to-connect-to]/ status=yes location=no sidebar=no navigation=no zip the file to [whatever].webapp double-click the webapp bundle or use prism -webapp [path-to-webapp] structure a bundle can contain the following files.
Styling - Archive of obsolete content
the folder names must match the following: windows - winnt mac os x - darwin linux - linux the folder names are pulled from mozilla and are the same as those used in other mozilla projects, such as extension and xul applications.
Hacking wiki - Archive of obsolete content
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.
Proxy UI - Archive of obsolete content
right-click a menu is displayed that has the following items: online (proxy: none) online (proxy: auto discover) online (proxy: auto url) online (proxy: manual) --- proxy configuration...
RDF Datasource How-To - Archive of obsolete content
the following xul fragment illustrates how to instantiate a tree control whose body is "rooted" to a resource (http://foo.bar.com/) that your datasource describes: <window xmlns:html="http://www.w3.org/1999/xhtml" xmlns:rdf="http://www.w3.org/tr/wd-rdf-syntax#" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> <tree datasources="rdf:my-datasource" ref="http://foo.bar.com/"> <template>...
Reading textual data - Archive of obsolete content
for the limited use case of reading lines from a local file, the following code using nsiscriptableunicodeconverter works.
Remotely debugging Firefox for Metro - Archive of obsolete content
set up firefox for metro go to about:config in firefox for metro, and set the following required preference: devtools.debugger.remote-enabled = true you may also want to set these optional preferences: devtools.debugger.force-local = false (if you want to connect from a different machine over the network) devtools.debugger.remote-host (to change the tcp hostname where firefox will listen for connections) devtools.debugger.remote-port (to change the tcp port number where fi...
Safely loading URIs - Archive of obsolete content
in general, the following guidelines apply for gecko 1.8: if you plan pass a uri string to nsiwebnavigation.loaduri (which can happen indirectly, e.g.
Same origin policy for XBL - Archive of obsolete content
determining the originating principal the principal originating the load is determined using the following steps: for external stylesheets (<link>, <?xml-stylesheet?>, user sheets, and ua sheets), it depends on where the sheet is loaded from, just like it would for an html document loaded from a similar source.
open - Archive of obsolete content
examples example: using open in the following example, myfile is a file object: myfile.open("read", "text"); see also ...
Static Analysis for Windows Code under Linux - Archive of obsolete content
we highly recommend you to read the cross compiling manual and the dehydra build manual before you start the following reading.
Table Cellmap - Archive of obsolete content
the following routines seem to be hot spots performance wise: nscellmap::colhasspanningcells nscellmap::rowhasspanningcells nscellmap::rowisspannedinto users of nscellmap::getdataat outside nscellmap.cpp the border collapse code relies on the cellmap.
Abc Assembler Tests - Archive of obsolete content
when run, the assembler tests include the abcasm/abs_helper.as file which defines the following functions: start(summary:string):void - start a new test section described by summary end():void - test section finished compare_stricteq(name:string, expected:*, actual:*):void - compare the results of a testcase where name is the testcase name compare_typeerror(name:string, expected:*, actual:*):void - special function for comparing typeerrors (runtimeerrors) - will only compare the first 22 chars of expected and ...
Actionscript Acceptance Tests - Archive of obsolete content
if you do not wish to have shell.as included when compiling, you must create a dir.asc_args file with an override parameter: # the following line will override all compile arguments and just compile a .as file with -import builtin.abc override| ...
Running Tamarin acceptance tests - Archive of obsolete content
running the tamarin test suite requires the following steps: set the avm environment variable to the path of the avmplus executable (avmshell).
Tamarin Build System Documentation - Archive of obsolete content
the list of smoke tests are located in the tamarin-repository, test/run-smokes.txt, assume the start directory is test format is cd testdir; command to run test above the test should be a # comment describing why the test in the smokes, when test failed, possibly a bugzilla bug the tests can be run by following the above instructions for running buildbot scripts locally and executing the all/run-smoke-tests.sh as a rule any test failure should be immediately added to the top of the smoke test list so the list is prioritized how to exclude tests from acceptance or mark them as known failures?
The life of an HTML HTTP request - Archive of obsolete content
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.
Treehydra Manual - Archive of obsolete content
treehydra provides the following callbacks to analysis scripts: process_tree_decl, process_tree, process_tree_type, and process_cp_pre_genericize.
Tuning Pageload - Archive of obsolete content
to best understand what the following preferences affect, there are a few things you should know.
Using cross commit - Archive of obsolete content
details cross-commit accepts the following options: all cvs options (those to the left of the specific cvs command) and cvs commit options (those to the right of a commit command), although the -r and -f cvs options need to be specified as --cvs-r and --cvs-f to avoid conflict with the similarly named (but different in meaning) cvs commit options.
Venkman Introduction - Archive of obsolete content
the following section describes these views and their use within the interface as a whole.
Venkman - Archive of obsolete content
source code the source code for venkman may be found in mercurial at the following url: http://hg.mozilla.org/venkman/summary community view mozilla forums...
Anonymous Content - Archive of obsolete content
whenever an element is inserted or appended, all insertion points are checked following all the same rules that applied when first placing explicit children during anonymous content generation.
DOM Interfaces - Archive of obsolete content
no return value example the following snippet checks to see if any anonymous child of "element" is itself an element.
Elements - Archive of obsolete content
the following xul display types may be used: browser, button, checkbox, description, editor, grippy, iframe, image, label, menu, menuitem, menubar, progressmeter, radio, resizer, scrollbar, scrollbox, spacer, splitter, titlebar, treechildren and treecol.
XML in Mozilla - Archive of obsolete content
the code for most the core xml can be found in the following directories on the mozilla mercurial repository: content/xml/, parser/expat/ and parser/htmlparser/.
Mac stub installer - Archive of obsolete content
to do this, in addition to the above steps to set up the mac installer to debug you will need to do the following: create a file named xpcom.xpi with the shared libraries in the structure described under the [xpcom] section in: <http://lxr.mozilla.org/seamonkey/sou...ackages-mac#33> note that if you are using the debug target of the installer binary all shared libraries are expected to have the name format <libname>debug.shlb now set a break point at xpi_init() in the mac installer code and step into xpi...
Install script template - Archive of obsolete content
ranganathan -- aruneratnospamallowedherenetscape.com petter ericson -- petteratnospamallowedherecycore.com this is an install.js file that does the following -- 1.
Examples - Archive of obsolete content
the following samples demonstrate some of the principal installation functions in the xpinstall api: file.macalias file.windowsshortcut [install.]adddirectory [install.]addfile installtrigger.installchrome installtrigger.startsoftwareupdate windows install example ...
copy - Archive of obsolete content
method of file object syntax int copy( filespecobject source, filespecobject dest ) parameters the copy method has the following parameters: source a filespecobject object reprsenting the file to be copied.
dirGetParent - Archive of obsolete content
method of file object syntax filespecobject dirgetparent( filespecobject fileordir ); parameters the dirgetparent method has the following parameters: fileordir a filespecobject representing the pathname of the file or directory whose parent is being requested.
dirRemove - Archive of obsolete content
method of file object syntax int dirremove( filespecobject dirtoremove [, boolean recursive] ); parameters the dirremove method has the following parameters: dirtoremove a filespecobject representing the directory to be removed.
dirRename - Archive of obsolete content
method of file object syntax int dirrename( filespecobject directory, string newname ); parameters the dirrename method has the following parameters: directory a filespecobject representing the directory to be renamed.
diskSpaceAvailable - Archive of obsolete content
method of file object syntax double diskspaceavailable ( string nativefolderpath ); parameters the diskspaceavailable method has the following parameters: nativefolderpath a string representing the pathname of the partition, a file, or a directory on the partition whose space is being queried.
execute - Archive of obsolete content
method of file object syntax int execute ( filespecobject executablefile, [string aparameters] ); parameters the execute method has the following parameters: executablefile a filespecobject representing the local file already on disk to be executed.
exists - Archive of obsolete content
method of file object syntax boolean exists( filespecobject target ) parameters the exists method has the following parameters: target a filespecobject representing the file or directory being tested for existence.
isDirectory - Archive of obsolete content
method of file object syntax boolean isdirectory ( filespecobject nativefolderpath ); parameters the isdirectory method has the following parameters: nativefolderpath a filespecobject representing the queried directory.
isFile - Archive of obsolete content
method of file object syntax boolean isfile (filespecobject nativefolderpath); parameters the isfile method has the following parameter: nativefolderpath a filespecobject representing the queried file object.
macAlias - Archive of obsolete content
method of file object syntax int macalias( filespecobject destdir, string filename, filespecobject aliasdir, string aliasname ); parameters the macalias method has the following parameters: destdir a filespecobject that represents the directory into which the program file will be installed.
modDate - Archive of obsolete content
method of file object syntax double moddate ( filespecobject nativefolderpath ); parameters the moddate method has the following parameters: nativefolderpath a filespecobject representing the queried file.
move - Archive of obsolete content
method of file object syntax int move( filespecobject source, filespecobject dest ); parameters the move method has the following parameters: source a filespecobject representing the source file.
remove - Archive of obsolete content
method of file object syntax int remove( filespecobject file ) parameters the remove method has the following parameters: file a filespecobject representing the file to be removed.
rename - Archive of obsolete content
method of file object syntax int rename( filespecobject file, string newname ) parameters the rename method has the following parameters: file a filespecobject representing the file to be renamed.
size - Archive of obsolete content
method of file object syntax int size (string nativefolderpath); parameters the size method has the following parameters: nativefolderpath the full pathname to the file.
windowsGetShortName - Archive of obsolete content
method of file object syntax string windowsgetshortname( object localdirspec ) parameters the windowsregisterserver method has the following parameter: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder.
windowsRegisterServer - Archive of obsolete content
method of file object syntax int windowsregisterserver( object localdirspec ) parameters the windowsregisterserver method has the following parameters: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder.
windowsShortcut - Archive of obsolete content
method of file object syntax int windowsshortcut( folderobject atarget, folderobject ashortcutpath, string adescription, folderobject aworkingpath, string aparams, folderobject aicon, number aiconid); parameters the windowsshortcut method has the following parameters: atarget a filespecobject representing the absolute path (including filename) to file that the shortcut will be created for.
init - Archive of obsolete content
method of installversion object syntax init ( int maj, int min, int rev, int bld ); init ( string version ); parameters the init method has the following parameters: maj the major version number.
toString - Archive of obsolete content
method of installversion object syntax string version = installversion.tostring ( initobj ); parameters the tostring method has the following parameter: initobj initobj is an installversion object whose init method has been called.
addDirectory - Archive of obsolete content
; public int adddirectory ( string registryname, string version, string xpisourcepath, object localdirspec, string relativelocalpath, boolean forceupdate); public int adddirectory ( string registryname, installversion version, string xpisourcepath, object localdirspec, string relativelocalpath, boolean forceupdate); parameters the adddirectory method has the following parameters: registryname the pathname in the client version registry for the root directory of the files that are to be installed.this parameter can be an absolute pathname (beginning with a /) or a relative pathname, (not beginning with a slash).
addFile - Archive of obsolete content
relativelocalpath, boolean forceupdate); public int addfile ( string xpisourcepath); public int addfile ( string registryname, string xpisourcepath, object localdirspec, string relativelocalpath); public int addfile ( string registryname, string version, string xpisourcepath, object localdirspec, string relativelocalpath); parameters the addfile method has the following parameters: registryname the pathname in the client version registry about the file.
cancelInstall - Archive of obsolete content
example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ...
confirm - Archive of obsolete content
the following examples show the result of calling confirm() with three buttons 0='a', 1='b' and 2='c'.
deleteRegisteredFile - Archive of obsolete content
method of install object syntax int deleteregisteredfile (string registryname); parameters the deleteregisteredfile method has the following parameter: registryname the pathname in the client version registry for the file that is to be deleted.
gestalt - Archive of obsolete content
method of install object syntax int gestalt ( string selector ); parameters the gestalt method takes the following parameters: selector the selector code for the information you want.
getLastError - Archive of obsolete content
example the following example calls getlasterror after a series of addfile calls: addfile("npplug", ...); addfile("/ms/shared/ctl3d.dll", ...); addfile("/nethelp/royalplug/royalhelp.html",...); err = getlasterror(); ...
getWinProfile - Archive of obsolete content
method of install object syntax winprofile getwinprofile ( object folder, string file); parameters the getwinprofile method has the following parameters: folder an object representing a directory.
initInstall - Archive of obsolete content
stall ( string displayname, string package, installversion version, int flags); int initinstall ( string displayname, string package, string version, int flags); int initinstall ( string displayname, string package, string version); int initinstall ( string displayname, string package, installversion version); parameters the initinstall method has the following parameters: displayname a string that contains the name of the software being installed.
patch - Archive of obsolete content
me, string xpisourcepath, object localdirspec, string relativelocalpath); int patch ( string registryname, installversion version, string xpisourcepath, object localdirspec, string relativelocalpath); int patch ( string registryname, string version, string xpisourcepath, object localdirspec, string relativelocalpath); parameters the patch method has the following parameters: registryname the pathname in the client version registry for the component that is to be patched.this parameter can be an absolute pathname, such as /royalairways/royalsw/executable or a relative pathname, such as executable.
performInstall - Archive of obsolete content
example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner", "/royalairways/tripplanner", "1.0.0.0"); ...
refreshPlugins - Archive of obsolete content
method of install object syntax int refreshplugins( [ areloadpages ] ); parameters the refreshplugins method has the following parameter: areloadpages areloadpages is an optional boolean value indicating whether you want to reload the open web pages after you have refreshed the plug-in list.
registerChrome - Archive of obsolete content
method of install object syntax int registerchrome( switch, srcdir, xpipath); parameters the registerchrome method has the following parameters: switch switch is the chrome switch indicating what type of file is being registered.
setPackageFolder - Archive of obsolete content
method of install object syntax void setpackagefolder ( object folder); parameters the setpackagefolder method has the following parameter: folder an object representing a directory.
Install Object - Archive of obsolete content
the following two lines, for example, are equivalent: f = getfolder("program"); f = install.getfolder("program"); an installation script is composed of calls to the install object, and generally takes the following form: initialize the installation call initinstall with the name of the installation and the necessary registry and version information.
Return Codes - Archive of obsolete content
return codes the methods described in this chapter can return any of the following return codes.
getString - Archive of obsolete content
method of winprofile object syntax string getstring ( string section, string key); parameters the method has the following parameters: section section in the file, such as "boot" or "drivers".
writeString - Archive of obsolete content
method of winprofile object syntax boolean writestring ( string section, string key, string value); parameters the method has the following parameters: section section in the file, such as "boot" or "drivers".
createKey - Archive of obsolete content
method of winreg object syntax int createkey ( string subkey, string classname); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
deleteKey - Archive of obsolete content
method of winreg object syntax int deletekey ( string subkey); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
deleteValue - Archive of obsolete content
method of winreg object syntax int deletevalue ( string subkey, string valname); parameters the deletevalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
getValue - Archive of obsolete content
method of winreg object syntax winregvalue getvalue ( string subkey, string valname); parameters the getvalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
getValueNumber - Archive of obsolete content
method of winreg object syntax number getvaluenumber ( string subkey, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
getValueString - Archive of obsolete content
method of winreg object syntax string getvaluestring ( string subkey, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
isKeyWritable - Archive of obsolete content
method of winreg object syntax boolean iskeywritable( string key); parameters the method has the following parameter: key a string representing the path to the key returns a boolean value: true if the key is writable; false if not.
keyExists - Archive of obsolete content
method of winreg object syntax boolean keyexists ( string key); parameters the method has the following parameter: key a string representing the path to the key returns boolean value description if the user does not have read access to the given key, this will also return false.
setRootKey - Archive of obsolete content
method of winreg object syntax void setrootkey ( int key ); parameters the method has the following parameter: key an integer representing a root key in the registry.
setValue - Archive of obsolete content
method of winreg object syntax string setvalue ( string subkey, string valname, winregvalue value); parameters the setvalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
setValueNumber - Archive of obsolete content
method of winreg object syntax int setvaluenumber ( string subkey, string valname, number value ); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
setValueString - Archive of obsolete content
method of winreg object syntax int setvaluestring ( string subkey, string valname, string value); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
valueExists - Archive of obsolete content
method of winreg object syntax boolean valueexists ( string key, string value ); parameters the method has the following parameters: key a string representing the path to the key.
WinRegValue - Archive of obsolete content
syntax winregvalue ( int datatype, byte[] regdata); parameters the winregvalue constructor takes the following parameter: datatype an integer indicating the type of the data encapsulated by this object.
buttons - Archive of obsolete content
the following values can be used in the list: accept: the ok button, which will accept the changes when pressed.
crop - Archive of obsolete content
ArchiveMozillaXULAttributecrop
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } ...
currentset - Archive of obsolete content
the value of this attribute should be a comma-separated list of item ids from the toolbarpalette or, additionally, any of the following strings: "separator", "spring", "spacer".
dlgtype - Archive of obsolete content
the following values can be used as the dialog type: accept the ok button, which will accept the changes when pressed.
droppedLinkHandler - Archive of obsolete content
« xul reference home droppedlinkhandler type: function this function is called when links are dropped to the browser element, with the following arguments.
id - Archive of obsolete content
ArchiveMozillaXULAttributeid
button was pressed'); } </script> a more abstract version of the above would be a <button id="foo" label="click me" oncommand="setwidgetlabel(this, 'i was pressed')"/> <script> function setwidgetlabel(idname, newcaption){ document.getelementbyid( idname.id ).setattribute('label',newcaption) } </script> not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: warning: empty string passed to getelementbyid() see also name ...
mousethrough - Archive of obsolete content
in the following example, the image appears above the button, yet the mousethrough attribute specified on the image causes mouse events to be ignored on the image and instead fall through to the button.
onchange - Archive of obsolete content
a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e.
panel.type - Archive of obsolete content
should be one of the following: autocomplete specify this for a panel that provides a tree for an autocomplete element.
preference.type - Archive of obsolete content
« xul reference home type type: one of the values below the preference type which should be one of the following values.
searchSessions - Archive of obsolete content
the following values are possible, although custom components may be installed which add others.
seltype - Archive of obsolete content
(default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column.
sizemode - Archive of obsolete content
it can have one of the following values: maximized the window is maximized, and occupies the full size of the screen.
validate - Archive of obsolete content
the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded.
width - Archive of obsolete content
<hbox> <hbox width="40" style="background-color: red;"> <label value="40"/> </hbox> </hbox> however, in the following example, despite that the preferred width of the box is 30 pixels, the displayed size of the box will be larger to accommodate the larger label.
Deprecated and defunct markup - Archive of obsolete content
{many elements on this page are wrongly marked as deprecated, this page needs review} the following xul tags and attribute should be considered deprecated, if not defunct.
Working With Directories - Archive of obsolete content
the following example returns an array of all of a directory's subdirectories: function getsubdirs() { var arr = []; var items = io.getfile("home", "").directoryentries; while (items.hasmoreelements()) { var item = items.getnext(); if (item.isdirectory()) arr.push(item); } return arr; } ...
Reading from Files - Archive of obsolete content
the following methods are available: readboolean will read a single byte from a stream and return false if the byte is zero and true if the byte has a non-zero value.
Menus - Archive of obsolete content
for more information about how to use an overlay to modify a menu, see using menus and popups in extensions the following tables list the ids of menus in firefox that are commonly overlaid upon.
appendNotification - Archive of obsolete content
each description is an object with the following properties: accesskey - the accesskey to appear on the button callback - function to be called when the button is activated.
loadTabs - Archive of obsolete content
the properties of params are following: boolean inbackground boolean replace boolean allowthirdpartyfixup tab targettab number newindex object postdatas number usercontextid ...
loadURIWithFlags - Archive of obsolete content
in addition to the flags allowed for the reloadwithflags method, the following flags are also valid: load_flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect.
ContextMenus - Archive of obsolete content
for example, the following will attach a context menu with the id 'contentareacontextmenu' to a browser element: <browser context="contentareacontextmenu"> indicating the default item on some platforms, one of the items in a context menu is marked as being a default operation.
MenuButtons - Archive of obsolete content
for instance, in the following example, pressing the 'view' button will open a menu which allows the user to select from a set of radio menuitems.
MenuItems - Archive of obsolete content
disabling a menuitem to have an item initially disabled, set the disabled attribute to true as in the following example: <menuitem label="undo" accesskey="u" disabled="true"/> when disabled, the item will appear greyed out and the action associated with the item cannot be carried out.
MoveResize - Archive of obsolete content
for instance, the following example will move a popup to the upper left corner of the screen: popup.moveto(0, 0); the position may be shifted so as not to cover user interface elements provided by the operating system, such as the menu bar or the task bar.
PopupEvents - Archive of obsolete content
this technique, as shown in the following example, is needed if you wish to open a submenu programmatically.
PopupKeys - Archive of obsolete content
the following table lists the keys that are checked, and what the menu keyboard listener does in response: cursor up/down move the highlight within the menu up or down, wrapping around if necessary.
Tooltips - Archive of obsolete content
for example, in the following, a toolbar has a tooltip set for it.
buttons - Archive of obsolete content
the following values can be used in the list: accept: the ok button, which will accept the changes when pressed.
currentSet - Archive of obsolete content
for spacers, separators, and flexible spacers the following strings are used instead of ids: "spacer", "separator", "spring".
Notes - Archive of obsolete content
deleting the "(default)" values in the following registry keys will fix this: hkey_classes_root\http\shell\open\ddeexec hkey_classes_root\https\shell\open\ddeexec you can also do this from within your xpcom component using windows registry interface.
Providing Command-Line Options - Archive of obsolete content
using the example to use this sample code, save the commandline.js file into the components directory and add the following lines to your chrome.manifest file: component {2991c315-b871-42cd-b33f-bfee4fcbf682} components/commandline.js contract @mozilla.org/commandlinehandler/general-startup;1?type=myapp {2991c315-b871-42cd-b33f-bfee4fcbf682} category command-line-handler m-myapp @mozilla.org/commandlinehandler/general-startup;1?type=myapp the javascript code const cc = components.classes; const ci = components.int...
Building Menus With Templates - Archive of obsolete content
after the first level of the menu has been generated, the content will be equivalent to the following (ignoring the template related content): <button label="houses in my neighbourhood" type="menu"> <menupopup> <menu uri="http://www.xulplanet.com/rdf/marion" label="marion street"/> <menu uri="http://www.xulplanet.com/rdf/garden" label="garden avenue"/> </menupopup> </button> the inner pass through the data handles the houses.
Containment Properties - Archive of obsolete content
for example, the following is equivalent to the previous example, except that the full query syntax is used.
Multiple Queries - Archive of obsolete content
the following is the basic structure of a template with multiple queries: <listbox datasources="..." ref="..."> <queryset> <query> ...
Namespaces - Archive of obsolete content
for example using the following xml document containing a list of people: <people xmlns="www.example.com/people"> <person name="napoleon bonaparte" gender="male"/> <person name="cleopatra" gender="female"/> <person name="julius caesar" gender="male"/> <person name="ferdinand magellan" gender="male"/> <person name="laura secord" gender="female"/> </people> <listbox datasources="people.xml" ref="*" querytype="xml"> <template xmlns:ns="www.example.com/people"> <query expr="ns:person"/> <action> <listitem uri="?" label="?ns:name"/> </action> </template> </listbox> once added to the template element the namespaces can then be referenced inside temple rule ...
RDF Query Syntax - Archive of obsolete content
here is the rdf graph again: starting at node a and following the relateditem arcs, we can see that there are three possible values for the ?relateditem variable, b, c and d.
Rule Compilation - Archive of obsolete content
for example, just calling the code like the following on the hidden vbox above will start off the template builder.
Simple Query Syntax - Archive of obsolete content
at its simplest, the simple query syntax is equivalent to the following: <query> <content uri="?start"/> <member container="?start" child="?photo"/> </query> the template builder uses the simple query syntax whenever a template does not have a <query> element.
Sorting Results - Archive of obsolete content
to do this, just add another key after the first separated by a space, as in the following: sort="?name ?gender" in this example, results will be sorted by name, followed by gender for those with identical names.
Template Builder Interface - Archive of obsolete content
a common pattern is to use the following: var rdf = components.classes["@mozilla.org/rdf/rdf-service;1"].
Using Multiple Queries to Generate More Results - Archive of obsolete content
if we add the following data about people to the neighbourhood datasource: <rdf:description rdf:about="http://www.xulplanet.com/rdf/myneighbourhood"> <r:people> <rdf:seq> <rdf:li rdf:resource="http://www.xulplanet.com/rdf/person/1"/> <rdf:li rdf:resource="http://www.xulplanet.com/rdf/person/2"/> </rdf:seq> </r:people> </rdf:description> <rdf:description rdf:about="http://www.x...
Using Recursive Templates - Archive of obsolete content
the result is output like the following: <groupbox> ...
textbox (Toolkit autocomplete) - Archive of obsolete content
a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e.
Things I've tried to do with XUL - Archive of obsolete content
(to add insult, xul layout code *explicitly* trims off '%' from width/height, thus treating it as pixels.) for reference, i'd like the following to give a vbox that resizes along with the window, with the green, red, and blue inside boxes always maintaining a 30%-20%-50% ratio to the height of the parent vbox.
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
the dimensions of the icons in various applications for both modes are summarized in the following table (feel free to add information about other applications): application (theme name) big icon size small icon size firefox 1.0 (winstripe) 24x24 16x16 thunderbird 1.0 (qute) 24x24 16x16 the stylesheet to set the image for your toolbar button, use the following css rules: /* skin/toolbar-button.css */ #myextension-button { list-style-im...
Complete - Archive of obsolete content
the following sections describe this extension's overall structure, and how it implements languages and themes.
Toolbars - Archive of obsolete content
the following articles provide details about implementing and working with toolbars.
Tree Widget Changes - Archive of obsolete content
in this case, disable editing for that cell by setting editable to false for that cell, as in the following: <treecell value="true" editable="false"/> or, for custom views, return false from the iseditable method.
Accesskey display rules - Archive of obsolete content
for this issue, we recommend the following format if you use .properties: <command-name>.label=cancel <command-name>.accesskey=c note that apis of nsipromptservice are using the bad way.
Adding Buttons - Archive of obsolete content
syntax of buttons the button tag has the following syntax: <button id="identifier" class="dialog" label="ok" image="images/image.jpg" disabled="true" accesskey="t"/> the attributes are as follows, all of which are optional: id a unique identifier so that you can identify the button with.
Adding Event Handlers - Archive of obsolete content
for example, you may use urls of the following form: <script src="findfile.js"/> <script src="chrome://findfiles/content/help.js"/> <script src="http://www.example.com/js/items.js"/> this tutorial does not attempt to describe how to use javascript (except as related to event handling) as this is a fairly large topic and there are plenty of other resources that are available for this.
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
the following alternate syntax can be used when the code in a handler is more complex: <binding id="binding-name"> <handlers> <handler event="event-name"> -- handler code goes here -- </handler> </handlers> </binding> handlers example the following example adds some key handlers to create a very primitive local clipboard: example 1 : source <binding id="clipbox"> <content> <xul:textbox...
Adding Style Sheets - Archive of obsolete content
the following list summarizes some of the selectors available: button matches all button tags.
Box Model Details - Archive of obsolete content
the following is an outline of both types of boxes: horizontal boxes lay out their elements next to each other horizontally.
Creating a Wizard - Archive of obsolete content
the following is a summary of attribute functions that are called when the user presses next, in the order that they will be checked.
Creating an Installer - Archive of obsolete content
our find files example for the find files dialog, we'll create a structure in the archive much like the following: install.js findfile content contents.rdf findfile.xul findfile.js skin contents.rdf findfile.css locale contents.rdf findfile.dtd a directory has been added for each part of the package, the content, the skin and the locale.
Cross Package Overlays - Archive of obsolete content
the following example shows how: <rdf:seq about="urn:mozilla:stylesheets"> <rdf:li resource="chrome://messenger/content/messenger.xul"/> </rdf:seq> <rdf:seq about="chrome://messenger/content/messenger.xul"> <rdf:li>chrome://blueswayedshoes/skin/myskinfile.css</rdf:li> </rdf:seq> next, we'll see how to create an installer for a xul application.
Grids - Archive of obsolete content
ArchiveMozillaXULTutorialGrids
the following example demonstrates this: example 4 : source view <grid flex="1"> <columns> <column flex="5"/> <column/> <column/> </columns> <rows> <row flex="10"> <button label="cherry"/> <button label="lemon"/> <button label="grape"/> </row> <row flex="1"> <button label="strawberry"/> <button label="raspberry"/> <button label="peach"/> </row> </rows> </grid> the ...
Groupboxes - Archive of obsolete content
this could be used to add extra elements within the structure, such as in the following example: example 3 : source view <radiogroup> <radio id="no" value="no" label="no number"/> <radio id="random" value="random" label="random number"/> <hbox> <radio id="specify" value="specify" label="specify number:"/> <textbox id="specificnumber"/> </hbox> </radiogroup> note that the radiogroup element does not draw a border around it.
Introduction to RDF - Archive of obsolete content
in the example above, the following uris are generated which can be used to refer to the specific fields: name http://www.some-fictitious-zoo.com/rdf#name species http://www.some-fictitious-zoo.com/rdf#species class http://www.some-fictitious-zoo.com/rdf#class next, we'll see how we can use rdf to populate xul elements.
Keyboard Shortcuts - Archive of obsolete content
vk_f16 vk_f17 vk_f18 vk_f19 vk_f20 vk_f21 vk_f22 vk_f23 vk_f24 vk_num_lock vk_scroll_lock vk_comma vk_period vk_slash vk_back_quote vk_open_bracket vk_back_slash vk_close_bracket vk_quote vk_help for example, to create a shortcut that is activated when the user presses alt and f5, do the following: <keyset> <key id="test-key" modifiers="alt" keycode="vk_f5"/> </keyset> the example below demonstrates some more keyboard shortcuts: <keyset> <key id="copy-key" modifiers="accel" key="c"/> <key id="find-key" keycode="vk_f3"/> <key id="switch-key" modifiers="control alt" key="1"/> </keyset> the first key is invoked when the user presses their platform-specific shortcut key and c.
More Button Features - Archive of obsolete content
for example, the following will create a button where two of the words are red: example 4 : source view <button> <description value="this is a"/> <description value="rather strange" style="color: red;"/> <description value="button"/> </button> any xul element may be placed inside the button.
More Tree Features - Archive of obsolete content
example hierarchical tree the following is a simple example: example 1 : source view <tree rows="6"> <treecols> <treecol id="firstname" label="first name" primary="true" flex="3" /> <treecol id="lastname" label="last name" flex="7" /> </treecols> <treechildren> <treeitem container="true" open="true"> <treerow> <treecell label="guys" /> </treerow> <treechildren> <treeitem> ...
More Wizards - Archive of obsolete content
in the following example, the user must enter a secret code into a textbox on the first page of the wizard.
Persistent Data - Archive of obsolete content
for example, to save the size of a window, you would do the following: <window id="somewindow" width="200" height="300" persist="width height" .
Progress Meters - Archive of obsolete content
determinate progress meter: indeterminate progress meter: the progress meter has the following syntax: <html:progress id="identifier" mode="determined" value="50" max="100"/> the attributes are as follows: id the unique identifer of the progress meter mode the type of the progress meter.
Property Files - Archive of obsolete content
var dir = "/usr/local/document"; var count = 10; var strbundle = document.getelementbyid("strings"); var result = strbundle.getformattedstring("resultmessage", [ dir, count ]); alert(result); this example will display following message in an alert box.
RDF Datasources - Archive of obsolete content
using rdf file example the following is an example of how an rdf file can be used as a datasource.
Scrolling Menus - Archive of obsolete content
example - scrolling list of buttons the following example shows how to create a scrolling list of buttons (you will need to resize the window to see the arrow buttons): example 1 : source view <arrowscrollbox orient="vertical" flex="1"> <button label="red"/> <button label="blue"/> <button label="green"/> <button label="yellow"/> <button label="orange"/> <button label="silver"/> <button label="lavender"/> <button label="gold"/> ...
Stacks and Decks - Archive of obsolete content
for example, you could create an effect similar to the text-shadow property with the following: example 1 : source view <stack> <description value="shadowed" style="padding-left: 1px; padding-top: 1px; font-size: 15pt"/> <description value="shadowed" style="color: red; font-size: 15pt;"/> </stack> both description elements create text with a size of 15 points.
Templates - Archive of obsolete content
rule example the following example demonstrates the earlier example with two rules: example 4 : source <window id="example-window" title="bookmarks list" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <vbox datasources="rdf:bookmarks" ref="nc:bookmarksroot" flex="1"> <template> <ru...
The Box Model - Archive of obsolete content
thus, the two lines below are equivalent: <vbox></vbox> <box orient="vertical"></box> the following example shows how to place three buttons vertically.
Tree Selection - Archive of obsolete content
for example, the following code will select the row at index 5: tree.view.selection.select(5); note that you should not just change the tree's currentindex property to change the selection.
Tree View Details - Archive of obsolete content
the following code is used to delete rows when a row is closed.
Using Spacers - Archive of obsolete content
the simplest spacer looks like the following: <spacer flex="1"/> a spacer is used to place blank space into a window.
XBL Attribute Inheritance - Archive of obsolete content
the following demonstrates this: xul: <box class="labeledtextbox" title="enter some text:" value="ok"/> css: box.labeledtextbox { -moz-binding: url('chrome://example/skin/example.xml#labeledtextbox'); } xbl: <binding id="labeledtextbox"> <content> <xul:label xbl:inherits="value=title"/> <xul:textbox xbl:inherits="value"/> </content> </binding> the textbox inherits the value attribute dire...
XBL Example - Archive of obsolete content
the following xul file produces the result in the image.
XBL Inheritance - Archive of obsolete content
for example, the following binding creates a textbox which adds the text 'http://www' to the beginning of its value when the f4 key is pressed.
XPCOM Interfaces - Archive of obsolete content
for example, to get a sound interface, you can do the following: var sound = components.classes["@mozilla.org/sound;1"].createinstance(); if (sound) sound.queryinterface(components.interfaces.nsisound); xpcom interfaces can inherit from other interfaces.
Using Remote XUL - Archive of obsolete content
for apache, you can do this by adding the following line to your mime.types file: application/vnd.mozilla.xul+xml .xul alternately, add this line to your httpd.conf file or, if the apache server is configured to allow it, to the .htaccess file in the directory from which the xul file is served: addtype application/vnd.mozilla.xul+xml .xul then restart your web server.
Using nsIXULAppInfo - Archive of obsolete content
the following sections provide a few examples of using nsixulappinfo from javascript.
Using the Editor from XUL - Archive of obsolete content
the following event listeners are registered: in nshtmleditor::installeventlisteners(), we install the following.
Using the standard theme - Archive of obsolete content
applying the standard theme in order to use the theme currently chosen by the user of the base application (the so called "global skin"), you have to add the following line to your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> this imports the styles found in the <tt>global/skin</tt> chrome directory and will make the standard xul widgets of your application use the selected chosen theme.
Writing Skinnable XUL and CSS - Archive of obsolete content
the following document outlines rules that one must abide by when writing a skin.
XULBrowserWindow - Archive of obsolete content
in order to do so it implements the following interfaces: nsisupports nsixulbrowserwindow nsiwebprogresslistener nsiwebprogresslistener2 nsisupportsweakreference note: this page is not complete at this time.
XUL element attributes - Archive of obsolete content
« xul reference home the following attributes are common to all xul elements: align type: one of the values below the align attribute specifies how child elements of the box are aligned, when the size of the box is larger than the total size of the children.
The Implementation of the Application Object Model - Archive of obsolete content
they are likely to change following the first release of nglayout, and when they do, anyone that implemented one of those interfaces will have to change as well in order to upgrade to the new world.
XUL controls - Archive of obsolete content
the following table lists the xul user interface controls.
caption - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } image type: uri the uri of the image to appear on the element.
checkbox - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
colorpicker - Archive of obsolete content
a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e.
command - Archive of obsolete content
see also: command attribute, commandset element attributes disabled, label, oncommand,reserved examples the following code will send a paste command (cmd_paste) to the currently focused element: // first include chrome://global/content/globaloverlay.js godocommand("cmd_paste"); example with two buttons <commandset><command id="cmd_openhelp" oncommand="alert('help');"/></commandset> <button label="help" command="cmd_openhelp"/> <button label="more help" command="cmd_openhelp"/> attributes disabled ty...
description - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
dialogheader - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } description type: string descriptive text to appear in addition to the dialog title.
editor - Archive of obsolete content
to enable editing on an editor, do either of the following: set the src attribute on the editor after the outer window has loaded, for example, in the onload handler.
image - Archive of obsolete content
ArchiveMozillaXULimage
the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded.
key - Archive of obsolete content
ArchiveMozillaXULkey
, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata details on key, keycode, and modifiers attributes for example, consider the following key: <key key="r" modifiers="shift"/> this key will only match when the shift key is pressed as well as the r key, and no other keys.
listbox - Archive of obsolete content
(default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column.
listcell - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
menu - Archive of obsolete content
ArchiveMozillaXULmenu
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
menulist - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disableautoselect type: boolean if this attribute is true or omitted, the selected item on the menu will update to match what the user entered in the textbox.
menuseparator - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
notificationbox - Archive of obsolete content
each description is an object with the following properties: accesskey - the accesskey to appear on the button callback - function to be called when the button is activated.
preferences - Archive of obsolete content
note: it's not clear which of the following methods and properties are public.
prefpane - Archive of obsolete content
place the <script> tags as in the following example for preference dialogs to work correctly: <prefwindow> <prefpane id="panegeneral" label="general"> ...
radio - Archive of obsolete content
ArchiveMozillaXULradio
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
richlistbox - Archive of obsolete content
(default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column.
scrollbox - Archive of obsolete content
examples the following shows the xul for a bunch of labels.
separator - Archive of obsolete content
nodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may be used to style the element.
splitter - Archive of obsolete content
nodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may be used to style the element.
stringbundle - Archive of obsolete content
for example, the following defines two properties: message.displayerror=an error occured trying to display this message message.namealreadyused=the name %s is already being used by another account.
textbox - Archive of obsolete content
nodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may be used to style the element.
tooltip - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } default type: boolean if true, the tooltip is used as the default popup for displaying tooltips in the window.
Building XULRunner - Archive of obsolete content
a basic minimal mozconfig which will build a release configuration of xulrunner is: mk_add_options moz_co_project=xulrunner mk_add_options moz_objdir=@topsrcdir@/obj-xulrunner ac_add_options --enable-application=xulrunner #uncomment the following line if you don't want to build javaxpcom: #ac_add_options --disable-javaxpcom cvs tags and xulrunner versions older xulrunner releases where tagged in cvs with (for instance xulrunner_1_8_0_5_release ) up to version 1.8.0.5 the cvs repository does not have specific tags for xulrunner anymore.
Make your xulrunner app match the system locale - Archive of obsolete content
the following is python code to set this preference.
Opening a Link in the Default Browser - Archive of obsolete content
to suppress this warning for particular protocols that are safe to open in the default application, you must set default prefs (thunderbird sets the following prefs): // suppress external-load warning for standard browser schemes pref("network.protocol-handler.warn-external.http", false); pref("network.protocol-handler.warn-external.https", false); pref("network.protocol-handler.warn-external.ftp", false); you can also check whether an external handler for a scheme exists.
Using Crash Reporting in a XULRunner Application - Archive of obsolete content
to enable crash reporting on the client, set the following items in application.ini: [crash reporter] enabled=true serverurl=https://your.server.url/submit note: because crash reports can contain private data including passwords, in production environments they should only be sent via https.
Using SOAP in XULRunner 1.9 - Archive of obsolete content
after some experimentation, the following seems to be the best way to speak soap in xulrunner.
nsIContentPolicy - Archive of obsolete content
this means that implementers of this method must not do any of the following: modify the dom in any way (e.g., setting attributes is a no-no).
2006-11-03 - Archive of obsolete content
bug found in nslocalmailfolder.cpp david bienvenu is following up on this bug.
2006-11-10 - Archive of obsolete content
build problem firefox 2.0 on fc3 november 10th: vin downloaded the latest firefox 2 rc3 and tried to build it on fc3 with the following options: ./configure --enable-application=browser --prefix=$prefix --enable-extensions=default,spatialnavigation then he tried running "make" and received the following error: /usr/bin/ld: testtarray.o(.text+0x2237): unresolvable relocation against symbol `nstarray_base::semptyhdr' /usr/bin/ld: final link failed: nonrepresentable section on output collect2: ld returned 1 exit status gmake[...
2006-11-17 - Archive of obsolete content
however he has been unsuccessful and gets the following errors: checking for gtk - version >= 1.2.0...
2006-11-24 - Archive of obsolete content
he is receiving the following error: error: uncaught exception: [exception...
2006-10-06 - Archive of obsolete content
discussions protocol handlers boris zbarsky posed the question, should random webpages have access to the following protocols: feed, pcast, moz-bookmark, webcal, swebcal.
2006-09-29 - Archive of obsolete content
details can be located at layout confusion refactoring the nshtmlreflowstate(computeblockboxdata, initconstraints) and nsimageframe::getdesiredsize which uses ns_inrinsicsize, into the following method: /** * compute the size that a frame will occupy.
2006-10-27 - Archive of obsolete content
multiple presshells discussion on why current interfaces allow for multiple presshells and how the relationships work for the following objects: docshell, presshell, prescontext, document, domwindow, widget, docshell and contentviewer.
NPAnyCallbackStruct - Archive of obsolete content
syntax typedef struct { int32 type; } npanycallbackstruct; fields the data structure has the following field: type always contains np_print.
NPByteRange - Archive of obsolete content
syntax typedef struct _npbyterange { int32 offset; /* negative offset = from the end */ uint32 length; struct _npbyterange* next; } npbyterange; fields the data structure has the following fields: offset offset in bytes to the start of the requested range.
NPEmbedPrint - Archive of obsolete content
syntax typedef struct _npembedprint { npwindow window; void* platformprint; /* platform-specific */ } npembedprint; fields the data structure has the following fields: window the npwindow the plug-in should use for printing.
NPFullPrint - Archive of obsolete content
syntax typedef struct _npfullprint { npbool pluginprinted; /* true: print fullscreen */ npbool printone; /* true: print one copy */ /* to default printer */ void* platformprint; /* platform-specific */ } npfullprint; fields the data structure has the following fields: pluginprinted determines whether the plug-in prints in full-page mode.
NPN_CreateObject - Archive of obsolete content
syntax #include <npruntime.h> npobject *npn_createobject(npp npp, npclass *aclass); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin wants to instantiate the object.
NPN_DestroyStream - Archive of obsolete content
syntax #include <npapi.h> nperror npn_destroystream(npp instance, npstream* stream, nperror reason); parameters the function has the following parameters: instance pointer to current plug-in instance.
NPN_Enumerate - Archive of obsolete content
syntax #include <npruntime.h> bool npn_enumerate(npp npp, npobject *npobj, npidentifier **identifiers, uint32_t *identifiercount); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request.
NPN_Evaluate - Archive of obsolete content
syntax #include <npruntime.h> bool npn_evaluate(npp npp, npobject *npobj, npstring *script, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin instance's window to evaluate the script in.
NPN_ForceRedraw - Archive of obsolete content
syntax #include <npapi.h> void npn_forceredraw(npp instance); parameters the function has the following parameters: instance plug-in instance for which the function forces redrawing.
NPN_GetAuthenticationInfo - Archive of obsolete content
*host, int32_t port, const char *scheme, const char *realm, char **username, uint32_t *ulen, char **password, uint32_t *plen); parameters this function has the following parameters: instance pointer to the current plug-in instance protocol protocol name (uri scheme) host host name port port number scheme http authentication scheme name realm http authentication realm username out parameter.
NPN_GetIntIdentifier - Archive of obsolete content
syntax #include <npruntime.h> npidentifier npn_getintidentifier(int32_t intid); parameters the function has the following parameter: <tt>intid</tt> the integer for which an opaque identifier should be returned.
NPN_GetProperty - Archive of obsolete content
syntax #include <npruntime.h> bool npn_getproperty(npp npp, npobject *npobj, npidentifier propertyname, npvariant *result); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin instance's is making the request.
NPN_GetStringIdentifier - Archive of obsolete content
syntax #include <npruntime.h> npidentifier npn_getstringidentifier(const nputf8 *name); parameters the function has the following parameters: <tt>name</tt> the string for which an opaque identifier should be returned.
NPN_GetStringIdentifiers - Archive of obsolete content
syntax #include <npruntime.h> void npn_getstringidentifiers(const nputf8 **names, int32_t namecount, npidentifier *identifiers); parameters the function has the following parameters: names an array of strings for which opaque identifiers should be returned.
NPN_GetURLNotify - Archive of obsolete content
syntax #include <npapi.h> nperror npn_geturlnotify(npp instance, const char* url, const char* target, void* notifydata); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPN_GetValue - Archive of obsolete content
syntax #include <npapi.h> nperror npn_getvalue(npp instance, npnvariable variable, void *value); parameters this function has the following parameters: instance pointer to the current plug-in instance.
NPN_GetValueForURL - Archive of obsolete content
syntax #include <npapi.h> typedef enum { npnurlvcookie = 501, npnurlvproxy } npnurlvariable; nperror npn_getvalueforurl(npp instance, npnurlvariable variable, const char *url, char **value, uint32_t *len); parameters this function has the following parameters: instance pointer to the current plug-in instance.
NPN_HasMethod - Archive of obsolete content
syntax #include <npruntime.h> bool npn_hasmethod(npp npp, npobject *npobj, npidentifier methodname); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request.
NPN_HasProperty - Archive of obsolete content
syntax #include <npruntime.h> bool npn_hasproperty(npp npp, npobject *npobj, npidentifier propertyname); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin instance is making the request.
NPN_IdentifierIsString - Archive of obsolete content
syntax #include <npruntime.h> bool npn_identifierisstring(npidentifier identifier); parameters the function has the following parameter: <tt>identifier</tt> the identifier whose type is to be examined.
NPN_IntFromIdentifier - Archive of obsolete content
syntax #include <npruntime.h> int32_t npn_intfromidentifier(npidentifier identifier); parameters the function has the following parameter: <tt>identifier</tt> the integer identifier whose corresponding integer value should be returned.
NPN_InvalidateRect - Archive of obsolete content
syntax #include <npapi.h> void npn_invalidaterect(npp instance, nprect *invalidrect); parameters the function has the following parameters: instance pointer to the plug-in instance to invalidate a portion of.
NPN_InvalidateRegion - Archive of obsolete content
syntax #include <npapi.h> void npn_invalidateregion(npp instance, npregion invalidregion); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPN_Invoke - Archive of obsolete content
syntax #include <npruntime.h> bool npn_invoke(npp npp, npobject *npobj, npidentifier methodname, const npvariant *args, uint32_t argcount, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin wants to call the method on the object.
NPN_InvokeDefault - Archive of obsolete content
syntax #include <npruntime.h> bool npn_invokedefault(npp npp, npobject *npobj, const npvariant *args, uint32_t argcount, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin wants to call the default method on the object.
NPN_MemAlloc - Archive of obsolete content
syntax #include <npapi.h> void *npn_memalloc (uint32 size); parameters the function has the following parameters: size size of memory, in bytes, to allocate in the browser's memory space.
NPN_MemFlush - Archive of obsolete content
syntax #include <npapi.h> uint32 npn_memflush(uint32 size); parameters the function has the following parameters: size size of memory, in bytes, to free in the browser's memory space.
NPN_MemFree - Archive of obsolete content
syntax #include <npapi.h> void npn_memfree (void* ptr); parameters the function has the following parameters: ptr block of memory previously allocated using npn_memalloc.
NPN NewStream - Archive of obsolete content
syntax #include <npapi.h> nperror npn_newstream(npp instance, npmimetype type, const char* target, npstream** stream); parameters the function has the following parameters: instance pointer to current plug-in instance.
NPN_PluginThreadAsyncCall - Archive of obsolete content
syntax #include <npapi.h> void npn_pluginthreadasynccall(npp plugin, void (*func)(void *), void *userdata); parameters the function has the following parameters: plugin pointer to the current plug-in instance.
NPN_PostURL - Archive of obsolete content
syntax #include <npapi.h> nperror npn_posturl(npp instance, const char *url, const char *target, uint32 len, const char *buf, npbool file); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPN_PostURLNotify - Archive of obsolete content
syntax #include <npapi.h> nperror npn_posturlnotify(npp instance, const char* url, const char* target, uint32 len, const char* buf, npbool file, void* notifydata); parameters the function has the following parameters: instance current plug-in instance, specified by the plug-in.
NPN_ReleaseObject - Archive of obsolete content
syntax #include <npruntime.h> void npn_releaseobject(npobject *npobj); parameters the function has the following parameter: <tt>npobj</tt> the npobject whose reference count should be decremented.
NPN_ReleaseVariantValue - Archive of obsolete content
syntax #include <npruntime.h> void npn_releasevariantvalue(npvariant *variant); parameters the function has the following parameters: <tt>variant</tt> the variant whose value is to be released.
NPN_ReloadPlugins - Archive of obsolete content
syntax #include <npapi.h> void npn_reloadplugins(npbool reloadpages);code parameters the function has the following parameter: reloadpages whether to reload pages.
NPN_RemoveProperty - Archive of obsolete content
syntax #include <npruntime.h> bool npn_removeproperty(npp npp, npobject *npobj, npidentifier propertyname); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request.
NPN_RequestRead - Archive of obsolete content
syntax #include <npapi.h> nperror npn_requestread(npstream* stream, npbyterange* rangelist); parameters the function has the following parameters: stream stream of type np_seek from which to read bytes.
NPN_RetainObject - Archive of obsolete content
syntax #include <npruntime.h> npobject *npn_retainobject(npobject *npobj); parameters the function has the following parameter: npobj the npobject to retain.
NPN_SetException - Archive of obsolete content
syntax #include <npruntime.h> void npn_setexception(npobject *npobj, const nputf8 *message); parameters the function has the following parameters: <tt>npobj</tt> the object on which the exception occurred.
NPN_SetProperty - Archive of obsolete content
syntax #include <npruntime.h> bool npn_setproperty(npp npp, npobject *npobj, npidentifier propertyname, const npvariant *value); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin instance's is making the request.
NPN_SetValue - Archive of obsolete content
syntax #include <npapi.h> nperror npn_setvalue(npp instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the plugin instance setting the variable.
NPN_SetValueForURL - Archive of obsolete content
s are configured, and is not supported.) syntax #include <npapi.h> typedef enum { npnurlvcookie = 501, npnurlvproxy } npnurlvariable; nperror npn_setvalueforurl(npp instance, npnurlvariable variable, const char *url, const char *value, uint32_t len); parameters this function has the following parameters: instance pointer to the current plug-in instance.
NPN_Status - Archive of obsolete content
syntax #include <npapi.h> void npn_status(npp instance, const char* message); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPN_UTF8FromIdentifier - Archive of obsolete content
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.
NPN_UserAgent - Archive of obsolete content
syntax #include <npapi.h> const char* npn_useragent(npp instance); parameters the function has the following parameter: instance pointer to the current plug-in instance.
NPN_Version - Archive of obsolete content
syntax #include <npapi.h> void npn_version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor); parameters the function has the following parameters: plugin_major pointer to a plug-in's major version number; changes with major code release number.
NPN_Write - Archive of obsolete content
syntax #include <npapi.h> int32 npn_write(npp instance, npstream* stream, int32 len, void* buf); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPP - Archive of obsolete content
syntax typedef struct _npp { void* pdata; /* plug-in private data */ void* ndata; /* mozilla private data */ } npp_t; typedef npp_t* npp; fields the data structure has the following fields: pdata a value, whose definition is up to the plug-in, that the plug-in can use to store a pointer to an internal data structure associated with the instance; this field isn't modified by the browser.
NPP_Destroy - Archive of obsolete content
syntax #include <npapi.h> nperror npp_destroy(npp instance, npsaveddata **save); parameters the function has the following parameters: instance pointer to the plug-in instance to delete.
NPP_DestroyStream - Archive of obsolete content
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.
NPP_GetValue - Archive of obsolete content
syntax #include <npapi.h> nperror npp_getvalue(void *instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the plugin instance from which the value should come.
NPP_HandleEvent - Archive of obsolete content
syntax #include <npapi.h> int16 npp_handleevent(npp instance, void* event); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPP_New - Archive of obsolete content
syntax #include <npapi.h> nperror npp_new(npmimetype plugintype, npp instance, uint16 mode, int16 argc, char *argn[], char *argv[], npsaveddata *saved); parameters the function has the following parameters: plugintype pointer to the mime type for new plug-in instance.
NPP_NewStream - Archive of obsolete content
syntax #include <npapi.h> nperror npp_newstream(npp instance, npmimetype type, npstream* stream, npbool seekable, uint16* stype); parameters the function has the following parameters: instance pointer to current plug-in instance.
NPP_Print - Archive of obsolete content
syntax #include <npapi.h> void npp_print(npp instance, npprint* printinfo); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPP_SetValue - Archive of obsolete content
syntax #include <npapi.h> nperror npp_setvalue(void *instance, npnvariable variable, void *value); parameters the function has the following parameters: instance pointer to plugin instance on which to set the variable.
NPP_SetWindow - Archive of obsolete content
syntax #include <npapi.h> nperror npp_setwindow(npp instance, npwindow *window); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPP_StreamAsFile - Archive of obsolete content
syntax #include <npapi.h> void npp_streamasfile(npp instance, npstream* stream, const char* fname); parameters the function has the following parameters: instance pointer to current plug-in instance.
NPP_URLNotify - Archive of obsolete content
syntax #include <npapi.h> void npp_urlnotify(npp instance, const char* url, npreason reason, void* notifydata); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPP_Write - Archive of obsolete content
(remark: hence the name "npp_write" is misleading - just think of:"data_arrived") syntax #include <npapi.h> int32 npp_write(npp instance, npstream* stream, int32 offset, int32 len, void* buf); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPP_WriteReady - Archive of obsolete content
syntax #include <npapi.h> int32 npp_writeready(npp instance, npstream* stream); parameters the function has the following parameters: instance pointer to the current plug-in instance.
NPPrint - Archive of obsolete content
syntax typedef struct _npprint { uint16 mode; /* np_full or np_embed */ union { npfullprint fullprint; /* if mode is np_full */ npembedprint embedprint; /* if mode is np_embed */ } print; } npprint; fields the data structure has the following fields: mode determines whether plug-in prints in full-page or embedded mode.
NPPrintCallbackStruct - Archive of obsolete content
syntax typedef struct { int32 type; file* fp; } npprintcallbackstruct; fields the data structure has the following fields: type always contains np_print.
NPRect - Archive of obsolete content
syntax typedef struct _nprect { uint16 top; uint16 left; uint16 bottom; uint16 right; } nprect; fields the data structure has the following fields: top, left, bottom, right the top, left, bottom, and right sides of the rectangle.
NPSavedData - Archive of obsolete content
syntax typedef struct _npsaveddata { int32 len; void* buf; } npsaveddata; fields the data structure has the following fields: len length in bytes of the buffer pointed to by buf; set by the plug-in.
NPSetWindowCallbackStruct - Archive of obsolete content
syntax typedef struct { int32 type; display* display; visual* visual; colormap colormap; unsigned int depth; } npsetwindowcallbackstruct; fields the data structure has the following fields: type always contains np_setwindow.
NPStream - Archive of obsolete content
syntax typedef struct _npstream { void* pdata; /* plug-in private data */ void* ndata; /* netscape private data */ const char* url; uint32 end; uint32 lastmodified; void* notifydata; const char *headers; } npstream; fields the data structure has the following fields: plug-in-private value that the plug-in can use to store a pointer to private data associated with the instance; not modified by the browser.
NPString - Archive of obsolete content
syntax typedef struct _npstring { const nputf8 *utf8characters; uint32_t utf8length; } npstring; fields the data structure has the following fields: utf8characters an array of the utf-8 characters comprising the string.
NPWindow - Archive of obsolete content
int32_t y; /* relative to a netscape page */ uint32_t width; /* maximum window size */ uint32_t height; nprect cliprect; /* clipping rectangle coordinates */ #ifdef xp_unix void * ws_info; /* platform-dependent additional data */ #endif /* xp_unix */ npwindowtype type; /* window or drawable target */ } npwindow; fields the data structure has the following fields: window platform-specific handle to a native window element in the netscape window hierarchy on windows (hwnd) and unix (x window id).
NP_GetValue - Archive of obsolete content
syntax #include <npapi.h> nperror np_getvalue(void *instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the current plug-in instance.
Adobe Flash - Archive of obsolete content
the following code snippet illustrates the ideas behind the use of fscommands demonstrated in example 3: <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" id="myflash" width="250" height="150" viewastext> <param name="movie" value="js2flash.swf" /> <param name="quality" value="high"></param> <embed ...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
please use the following diagram as a reference: as you can see from the diagram above, it's pretty easy to set up a plugin using gtk2.
Syndicating content with RSS - Archive of obsolete content
the icon looks like the following: you can get more icons like this from feed icons.
0.90 - Archive of obsolete content
ArchiveRSSVersion0.90
specification the original rss 0.90 specification has disappeared from its original location: http://my.netscape.com/publish/help/quickstart.html copies of it have been saved, and can be viewed at the following locations: http://www.purplepages.ie/rss/netscape/rss0.90.html http://web.archive.org/web/*/http://...uickstart.html ...
Digital Signatures - Archive of obsolete content
a one-way hash is a number of fixed length with the following characteristics: the value of the hash is unique for the hashed data.
NSPR Release Engineering Guide - Archive of obsolete content
elease candidate checkout a whole new tree using tag (including fixes) tag the treey with nsprpub_release_x_y_z build all targets, debug and optimized on all platforms using the command: gmake release mdist=<dir>/mdist build_number=vx.y.z [build_opt=1 | use_debug_rtl=1] copy the bits from mdist to /share/builds/components/nspr20/.vx.y.z in /share/builds/components/nspr20/ run the following scripts: explode.pl rename.sh symlink.sh rtm bits rename the .vx.y.z directory to vx.y.z (remove the hidden directory 'dot').
SSL and TLS - Archive of obsolete content
supported cipher suites for rsa cipher suites with the rsa key exchange that are commonly supported include the following: aes and sha message authentication.
TCP/IP Security - Archive of obsolete content
depending on how ssl is implemented and configured, it can provide any combination of the following types of protection: confidentiality.
Threats - Archive of obsolete content
threats against network traffic include the following: eavesdropping.
contents.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "contents.rdf": <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <!-- list all the skins being supplied by this theme --> <rdf:seq about="urn:mozilla:skin:root"> <rdf:li resource="urn:mozilla:skin:my_theme"/> </rdf:seq> <rdf:description about="urn:mozilla:skin:my_theme" chrome:displayname="my theme" chrome:accesskey="n" chrome:author="" chrome:authorurl="" chrome:description="" chrome:name="my_theme" chrome:image="preview.png"> <chrome:packages> <rdf:seq about="urn:mozilla:skin:my_theme:packages"> <rdf:li resource="urn:mozilla:skin:my_theme:...
install.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "install.rdf": <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> <!-- target application this extension can install into, with minimum and maximum supported versions.
Making sure your theme works with RTL locales - Archive of obsolete content
instead, you should use the following start/end rules instead to ensure rtl compatibility: -moz-padding-start -moz-padding-end -moz-margin-start -moz-margin-end -moz-border-start -moz-border-start-color -moz-border-start-style -moz-border-start-width -moz-border-end -moz-border-end-color -moz-border-end-style -moz-border-end-width #urlbar-search-splitter { min-width: 8px; -moz-margin-start: -4px; border: none; ...
Browser Feature Detection - Archive of obsolete content
browser sniffing via api name detection the following tables list the api names defined for specific w3c dom apis and lists the percentage of names that your browser actually defines followed by a list of each of the api names tested along with an indication of whether the name was defined for your browser.
-ms-content-zoom-limit - Archive of obsolete content
smaller values zoom out.computed valueas each of the properties of the shorthand:-ms-content-zoom-limit-max: as specified-ms-content-zoom-limit-min: as specifiedanimation typediscrete syntax the -ms-content-zoom-limit shorthand property is specified as one or both of the following content zoom limit values, in order, separated by spaces.
-ms-content-zoom-snap - Archive of obsolete content
none-ms-content-zoom-snap-points: snapinterval(0%, 100%)applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas each of the properties of the shorthand:-ms-content-zoom-snap-type: as specified-ms-content-zoom-snap-points: as specifiedanimation typediscrete syntax the -ms-content-zoom-snap shorthand property is specified as one or both of the following content zoom snap values, in order, separated by spaces.
-ms-scroll-chaining - Archive of obsolete content
formal syntax chained | none examples the following example illustrates the -ms-scroll-chaining property in use.
-ms-scroll-limit - Archive of obsolete content
max: autoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas each of the properties of the shorthand:-ms-scroll-limit-x-min: as specified-ms-scroll-limit-y-min: as specified-ms-scroll-limit-x-max: as specified-ms-scroll-limit-y-max: as specifiedanimation typediscrete syntax the -ms-scroll-limit property is specified as one or more of the following scroll limit values, in the order listed, separated by spaces.
-ms-scrollbar-3dlight-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-3dlight-color property for a <textarea> element.
-ms-scrollbar-base-color - Archive of obsolete content
</div> </body> the following image shows the result.
-ms-scrollbar-darkshadow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-darkshadow-color property for a <textarea> element.
-ms-scrollbar-shadow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-shadow-color property for a <textarea> element.
-ms-scrollbar-track-color - Archive of obsolete content
</div> </body> the following image shows the result.
:-moz-system-metric(windows-default-theme) - Archive of obsolete content
the :-moz-system-metric(windows-default-theme) css pseudo-class matches an element if the user is currently using one of the following themes in windows: luna, royale, zune, or aero (i.e., vista basic, vista standard, or aero glass).
:-moz-system-metric() - Archive of obsolete content
ible area of the document.:-moz-system-metric(touch-enabled)the :-moz-system-metric(touch-enabled) css pseudo-class will match an element if the device on which the content is being rendered offers a supported touch-screen interface.:-moz-system-metric(windows-default-theme)the :-moz-system-metric(windows-default-theme) css pseudo-class matches an element if the user is currently using one of the following themes in windows: luna, royale, zune, or aero (i.e., vista basic, vista standard, or aero glass).
::-ms-browse - Archive of obsolete content
permitted properties only the following css properties can be used in a rule with ::-ms-browse in its selector.
::-ms-check - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-check in its selector.
::-ms-expand - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-expand in its selector.
::-ms-fill-lower - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-fill-lower in its selector.
::-ms-fill-upper - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-fill-upper in its selector.
::-ms-fill - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-fill in its selector.
::-ms-reveal - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-reveal in its selector.
::-ms-thumb - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-thumb in its selector.
::-ms-ticks-after - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-ticks-after in its selector.
::-ms-ticks-before - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-ticks-before in its selector.
::-ms-tooltip - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-tooltip in its selector.
::-ms-track - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-track in its selector.
::-ms-value - Archive of obsolete content
allowable properties only the following css properties can be used in a rule with ::-ms-value in its selector.
The global XML object - Archive of obsolete content
the following example defines the foocount() method, which returns the amount of <foo> elements in the xml: xml.prototype.function::foocount = function foocount() { return this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.foocount() // returns 3 ignorecomments true by default.
Array.observe() - Archive of obsolete content
callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change.
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
(may 2019) the following features are already implemented, but only available in the firefox nightly channel and not yet included in a draft edition of an ecmascript specification.
Date.getVarDate() - Archive of obsolete content
requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
Debug.msUpdateAsyncCallbackRelation - Archive of obsolete content
not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards.
Debug.write - Archive of obsolete content
var counter = 42; debug.write("the value of counter is " + counter); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
Debug.writeln - Archive of obsolete content
var counter = 42; debug.writeln("the value of counter is " + counter); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
Debug - Archive of obsolete content
var counter = 42; debug.write("the value of counter is " + counter); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
Enumerator.item - Archive of obsolete content
sready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; s += totalgb.tofixed(3) + " gb"; } else { s += "not ready"; } s += "<br />"; e.movenext(); } return(s); } requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
Error.stackTraceLimit - Archive of obsolete content
example the following example shows how to set and then get the stack trace limit.
ScriptEngine() - Archive of obsolete content
example the following example illustrates the use of the scriptengine function: if (window.scriptengine) { console.log(window.scriptengine()); } // output: jscript requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
ScriptEngineBuildVersion - Archive of obsolete content
example the following example illustrates the use of the scriptenginebuildversion function: if(window.scriptenginebuildversion) { console.log(window.scriptenginebuildversion()); } // output: <current build version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet e...
ScriptEngineMajorVersion - Archive of obsolete content
example the following example illustrates the use of the scriptenginemajorversion function: if (window.scriptenginemajorversion) { console.log(window.scriptengine()); } output: <current major version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 st...
@cc_on - Archive of obsolete content
example the following example illustrates the use of the @cc_on statement.
@if - Archive of obsolete content
example the following example illustrates the use of the @if...@elif...@else...@end statement.
@set - Archive of obsolete content
examples of variable declarations look like this: @set @myvar1 = 12 @set @myvar2 = (@myvar1 * 20) @set @myvar3 = @_jscript_version the following operators are supported in parenthesized expressions: !
New in JavaScript 1.1 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 2.0 to 3.0.
New in JavaScript 1.2 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 3.0 to 4.0.
New in JavaScript 1.4 - Archive of obsolete content
the following is a changelog for javascript 1.4, which was only used for netscape's server side javascript released in 1999.
New in JavaScript 1.5 - Archive of obsolete content
the following is a changelog for javascript 1.5.
New in JavaScript 1.6 - Archive of obsolete content
the following is a changelog for javascript 1.6.
New in JavaScript 1.8.1 - Archive of obsolete content
the following is a changelog for javascript 1.8.1.
New in JavaScript 1.8.5 - Archive of obsolete content
the following is a changelog for javascript 1.8.5.
New in JavaScript 1.8 - Archive of obsolete content
the following is a changelog for javascript 1.8.
Object.observe() - Archive of obsolete content
callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change.
arguments.caller - Archive of obsolete content
function whocalled() { if (whocalled.caller == null) console.log('i was called from the global scope.'); else console.log(whocalled.caller + ' called me!'); } examples the following code was used to check the value of arguments.caller in a function, but doesn't work anymore.
for each...in - Archive of obsolete content
the following snippet iterates over an object's properties, calculating their sum: var sum = 0; var obj = {prop1: 5, prop2: 13, prop3: 8}; for each (var item in obj) { sum += item; } console.log(sum); // logs "26", which is 5+13+8 specifications not part of any standard.
LiveConnect - Archive of obsolete content
liveconnect use by applets is enabled via the use of the "mayscript" attribute in applet tags on an html page, following which the applet may refer to classes in the netscape.javascript package to access javascript objects, and scripts may directly call applet methods (using the syntax document.applets.name.methodname()).
JavaPackage - Archive of obsolete content
the following code creates the javapackage red: var red = packages.redwood; see also javaarray, javaclass, javaobject, packages ...
Packages - Archive of obsolete content
examples example: javascript function to create a java dialog box the following javascript function creates a java dialog box: function createwindow() { var theowner = new packages.java.awt.frame(); var thewindow = new packages.java.awt.dialog(theowner); thewindow.setsize(350, 200); thewindow.settitle("hello, world"); thewindow.setvisible(true); } in the previous example, the function instantiates thewindow as a new packages object.
Examples - Archive of obsolete content
back to the article stylesheet /* * if you try to view the results of these examples, * you will need to put a file named style.css with * the following content in the same directory as * the examples.
Standards-Compliant Authoring Tools - Archive of obsolete content
the following authoring tools adhere to the w3 standards.
Writing JavaScript for XHTML - Archive of obsolete content
(note that xhtml documents which behave correctly in both application/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.) to test the following examples locally, use firefox's extension switch.
XForms API Reference - Archive of obsolete content
note the word beginning :-) naming convention the xforms interfaces has the following naming convention: nsixforms...element interfaces implemented by the c++ part of a control nsixformsns...element interfaces extending xforms specification interfaces nsixforms...uielement interfaces implemented by the js part of a control nsixforms...accessors interface exposing states about the bound instance node for a given control frozen interfaces nsixformsmodelelement the model interface experimental interfaces nsixformsdelegate the delegate interface for xforms:custom_controls nsixformsaccessors the accessors interface for xforms:custom_...
Mozilla XForms Specials - Archive of obsolete content
instead you will have to use the following normal classes instead: xf-value xf-repeat-item xf-repeat-index for example, to target the value element of an input control use: @namespace xf url("http://www.w3.org/2002/xforms"); xf|input .xf-value { ...
RFE to the Custom Controls - Archive of obsolete content
this page could be of particular interest to people using custom controls in xul documents for the following reason.
RFE to the Custom Controls Interfaces - Archive of obsolete content
in short, we have the following interfaces: nsixformsaccessors - serves to get/set the value of the instance data node that the xforms element is bound to as well as getting the various states of that node nsixformsdelegate - used to obtain the nsixformsaccessors interface nsixformsuiwidget - used by the xforms processor to update the value/state of an xforms element when its bound node's value/state is changed our current mechanism that allows authors to build custom controls assumes that the controls will be bound to instance nodes of simple content type.
XForms Message Element - Archive of obsolete content
representations it may be represented in the following ways: modal window - if level attribute value is modal modeless window - if level attribute value is modeless tooltip window - if level attribute value is ephemeral note: message element doesn't define a default presentation.
XForms Repeat Element - Archive of obsolete content
to accommodate this, xforms 1.0 defines an alternative syntax that is functionally equivalent to the repeat element, using the following attributes: repeat-model repeat-bind repeat-nodeset repeat-startindex repeat-number additionally, when using xforms action setindex, its repeat attribute (which contains an idref) can point to any element carrying these repeat attributes.
XForms Select Element - Archive of obsolete content
representations the xforms select element can be represented by the following widgets for the specified appearance attribute values: list - default representation (xhtml/xul) check group- used when appearance = 'full' (xhtml/xul) list displaying a listbox is the default representation (xhtml/xul).
XForms Select1 Element - Archive of obsolete content
representations the xforms select1 element can be represented by the following widgets for the specified appearance attribute values: combobox - default representation (xhtml/xul) listbox - used when appearance = 'compact' (xhtml/xul) radio group - used when appearance = 'full' (xhtml/xul) combobox displaying a combobox is the default representation (xhtml/xul).
XForms Submit Element - Archive of obsolete content
representations the xforms submit element can be represented by the following widgets for the specified appearance attribute values: button - default representation (xhtml/xul) link/clickable text - used when appearance = 'minimal' (xhtml only) button displaying a button is the default presentation (xhtml/xul).
XForms Trigger Element - Archive of obsolete content
representations the xforms trigger element can be represented by the following widgets for the specified appearance attribute values: button - default representation (xhtml/xul) link/clickable text - used when appearance = 'minimal' (xhtml only) button displaying a button is the default presentation (xhtml/xul).
Archived open Web documentation - Archive of obsolete content
the following authoring tools adhere to the w3 standards.
Describing microformats in JavaScript - Archive of obsolete content
microformat definition format the microformat definition must contain the following entries: mfversion specifies the version number of the microformat api to which the definition was written.
Displaying a graphic with audio samples - Archive of obsolete content
the following example shows how to take samples from an audio stream and display them behind an image (in this case, the mozilla logo), giving the impression that the image is built from the samples.
Fixing Incorrectly Sized List Item Markers - Archive of obsolete content
the following rule is derived from mozilla's html.css file: *|*:-moz-list-bullet, *|*:-moz-list-number {font-size: 1em;} this rule tells gecko-based browsers to use the computed value of font-size for the marker's parent, which is the list item itself.
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
to do this, the gecko rendering engine uses the following rule in the quirk.css user agent file: /* quirk: cut off all font inheritance in tables and captions except for family.
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
consider the effects of the following rule: a:hover {color: red;} in a document with an unclosed named anchor, any text that follows the anchor's open tag will be colored red (unless another css rule intervenes).
Popup Window Controls - Archive of obsolete content
mozilla will attempt to suppress all calls to window.open() which occur in the following circumstances: global script which is executed as the document is loading script executed as part of a onload event handler script executed in settimeout() or setinterval() what popup windows are not suppressed?
Styling Abbreviations and Acronyms - Archive of obsolete content
nd according to guideline 4 of the web content accessibility guidelines, both elements should be given a title attribute to improve "readability of the web for all people, including those with learning disabilities, cognitive disabilities, or people who are deaf." the problem authors have discovered that any abbr or acronym that has a title attribute is rendered with a dotted underline, per the following rule in resource://gre-resources/html.css abbr[title], acronym[title] { text-decoration: dotted underline; } the solution if authors wish to remove the underline from abbr and acronym elements, this can be done with the following rule: abbr[title], acronym[title] { text-decoration: none; } it may be better to lessen the visual weight of the border without actually removing it.
Using the Right Markup to Invoke Plugins - Archive of obsolete content
thus, in the following example, instead of stopping at the activex control, ie will display the same animation twice since it also understands the mime type for flash: <!-- usage will not work as intended --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myflash"> <param name=...
3D collision detection - Game development
if we assume that px, py and pz are the point's coordinates, and bminx–bmaxx, bminy–bmaxy, and bminz–bmaxz are the ranges of each axis of the aabb, we can calculate whether a collision has occurred between the two using the following formula: f(p,b)=(px>=bminx∧px<=bmaxx)∧(py>=bminy∧py<=bmaxy)∧(pz>=bminz∧pz<=bmaxz)f(p,b)= (p_x >= b_{minx} \wedge p_x <= b_{maxx}) \wedge (p_y >= b_{miny} \wedge p_y <= b_{maxy}) \wedge (p_z >= b_{minz} \wedge p_z <= b_{maxz}) or in javascript: function ispointinsideaabb(point, box) { return (point.x >= box.minx && point.x <= box.maxx) && (point.y >= box.miny && point.y <= ...
Desktop gamepad controls - Game development
the connect() and disconnect() functions are bound to the following events: window.addeventlistener("gamepadconnected", gamepadapi.connect); window.addeventlistener("gamepaddisconnected", gamepadapi.disconnect); they are fired when the gamepad is connected and disconnected respectively.
Unconventional controls - Game development
to get the leap motion working on your computer you have to first install it by following the steps at leapmotion.com/setup.
Crisp pixel art look with image-rendering - Game development
s; } and some javascript to set up the canvas and load the image: // get canvas context var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image = new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note: you can check out the original code on github (and a live example.) ...
Efficient animation for web games - Game development
} var drawpending = false; function requestredraw() { if (!drawpending) { drawpending = true; requestanimationframe(redraw); } } following this pattern — or something similar — means that no matter how many times you call requestredraw, your drawing function will only be called once per frame.
Tiles and tilemaps overview - Game development
the following screenshot shows an example of both points: a character appearing behind a tile (the knight appearing behind the top of a tree) and a tile (the bush) being rendered over different terrain types.
Bounce off the walls - Game development
add the following line below the previous one: ball.body.bounce.set(1); try reloading index.html again — now you should see the ball bouncing off all the walls and moving inside the canvas area.
Game over - Game development
add the following lines just below the previous new one: ball.checkworldbounds = true; ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event.
Initialize the framework - Game development
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 phaser workshop - lesson 01: initialize the framework</title> <style>* { padding: 0; margin: 0; }</style> <script src="js/phaser.min.js"></script> </head> <body> <script> var game = new phaser.game(480, 320, phaser.canvas, null, { preload: preload, create: create, update: update }); ...
Move the ball - Game development
add the following new lines of the code inside update(), as shown: function update() { ball.x += 1; ball.y += 1; } the code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame.
Scaling - Game development
add the following line below the other three you added earlier: game.stage.backgroundcolor = '#eee'; compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now we've set up the scaling for our game, let's continue to the third lesson and work out how to load the assets and print them on screen.
Win the game - Game development
add the following new code into your ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); var count_alive = 0; for (i = 0; i < bricks.children.length; i++) { if (bricks.children[i].alive == true) { count_alive++; } } if (count_alive == 0) { alert('you won the game, congratulations!'); location.reload(); } } we loop thr...
Block (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
underneath the preceding element in a horizontal writing mode, and above the following element (commonly known as a block-level element).
Block - MDN Web Docs Glossary: Definitions of Web-related terms
underneath the preceding element in a horizontal writing mode, and above the following element (commonly known as a block-level element).
CORS-safelisted response header - MDN Web Docs Glossary: Definitions of Web-related terms
by default, the safelist includes the following response headers: cache-control content-language content-type expires last-modified pragma examples extending the safelist you can extend the list of cors-safelisted response headers by using the access-control-expose-headers header: access-control-expose-headers: x-custom-header, content-length ...
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
its sole purpose is to prevent a browser from switching into so-called “quirks mode” when rendering a document; that is, the "<!doctype html>" doctype ensures that the browser makes a best-effort attempt at following the relevant specifications, rather than using a different rendering mode that is incompatible with some specifications.
Effective connection type - MDN Web Docs Glossary: Definitions of Web-related terms
to see your effective connection type, open the console of the developer tools of a supporting browser and enter the following: navigator.connection.effectivetype; see also: network information api networkinformation networkinformation.effectivetype ...
Entity - MDN Web Docs Glossary: Definitions of Web-related terms
to display these characters as text, replace them with their corresponding character entities, as shown in the following table.
Entity header - MDN Web Docs Glossary: Definitions of Web-related terms
a few request headers after a get request: in the following example, content-length is an entity header, while host and user-agent are requests headers: post /myform.html http/1.1 host: developer.mozilla.org user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 content-length: 128 learn more technical knowledge list of all http headers ...
Fetch metadata request header - MDN Web Docs Glossary: Definitions of Web-related terms
the following are fetch metadata request headers: sec-fetch-site sec-fetch-mode sec-fetch-user sec-fetch-dest ...
Forbidden header name - MDN Web Docs Glossary: Definitions of Web-related terms
forbidden header names start with proxy- or sec-, or are one of the following names: accept-charset accept-encoding access-control-request-headers access-control-request-method connection content-length cookie cookie2 date dnt expect feature-policy host keep-alive origin proxy- sec- referer te trailer transfer-encoding upgrade via note: the user-agent header is no longer forbidden, as per spec — see forbidden header name list (this was impleme...
HTML - MDN Web Docs Glossary: Definitions of Web-related terms
brief history in 1990, as part of his vision of the web, tim berners-lee defined the concept of hypertext, which berners-lee formalized the following year through a markup mainly based on sgml.
Localization - MDN Web Docs Glossary: Definitions of Web-related terms
the following are common factors to consider: language unit of measure (e.g., kilometers in europe, miles in u.s.) text direction (e.g., european languages are left-to-right, arabic right-to-left) capitalization in latin script (e.g., english uses capitals for weekdays, spanish uses lowercase) adaptation of idioms (e.g., "raining cats and dogs" makes no sense when translated literally) use of register (e.g., in japanese respectful speech differs exceptionally from casual speech) number format (e.g., 10 000,00 in germany vs.
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
on appending the "immutablestring" with a string value, following events occur: existing value of "immutablestring" is retrieved "world" is appended to the existing value of "immutablestring" the resultant value is then allocated to a new block of memory "immutablestring" object now points to the newly created memory space previously created memory space is now available for garbage collection.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
another example [ step-by-step ] the following example will help you go through how javascript deals with primitives.
Quality values - MDN Web Docs Glossary: Definitions of Web-related terms
examples the following syntax text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 indicates the order of priority: value priority text/html and application/xhtml+xml 1.0 application/xml 0.9 */* 0.8 if there is no priority defined for the first two values, the order in the list is irrelevant.
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
examples recursive function calls itself until condition met the following python code defines a function that takes a number, prints it, and then calls itself again with the number's value -1.
Response header - MDN Web Docs Glossary: Definitions of Web-related terms
the following shows a few response headers after a get request.
SEO - MDN Web Docs Glossary: Definitions of Web-related terms
search engines crawl the web, following links from page to page, and index the content found.
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
how to prevent before executing the queries for the user credentials, make some changes like the following: $id = $_get['id'] (1) $id = stripslashes($id) (2) $id = mysql_real_escape_string($id) so due to (1) each single quote (') in the input string is replaced with double quotes ("), and due to (2) before every (') it adds (/).
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
for instance, the following is invalid: function examplefunction() { var x = "declared inside function"; // x can only be used in examplefunction console.log("inside function"); console.log(x); } console.log(x); // causes error however, the following code is valid due to the variable being declared outside the function, making it global: var x = "declared outside function"; examplefunction(); function ex...
Search engine - MDN Web Docs Glossary: Definitions of Web-related terms
a search engine conducts the following processes: web crawling: searching web sites by navigating hyperlinks on web pages, both within a site, and from one site to another.
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
consider the following: <span style="font-size: 32px; margin: 21px 0;">is this a top level heading?</span> this will render it to look like a top level heading, but it has no semantic value, so it will not get any extra benefits as described above.
Slug - MDN Web Docs Glossary: Definitions of Web-related terms
in the context of mdn, it is the portion of the url following "<locale>/docs/".
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
the method symbol.for(tokenstring) returns a symbol value from the registry, and symbol.keyfor(symbolvalue) returns a token string from the registry; each is the other's inverse, so the following is true: symbol.keyfor(symbol.for("tokenstring")) === "tokenstring" // true learn more general knowledge symbol (programming) on wikipedia javascript data types and data structures symbols in ecmascript 6 symbol in the mdn js reference object.getownpropertysymbols() ...
TLD - MDN Web Docs Glossary: Definitions of Web-related terms
iana today distinguishes the following groups of top-level domains: country-code top-level domains (cctld) two-character domains established for countries or territories.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
css prefixes the major browsers use the following prefixes: -webkit- (chrome, safari, newer versions of opera, almost all ios browsers including firefox for ios; basically, any webkit based browser) -moz- (firefox) -o- (old pre-webkit versions of opera) -ms- (internet explorer and microsoft edge) sample usage: -webkit-transition: all 4s ease; -moz-transition: all 4s ease; -ms-transition: all 4s ease; -o-transition: all 4s ease; transiti...
Character encoding - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in html we normally declare a character encoding of utf-8, using the following line: <meta charset="utf-8"> this ensures that you can use characters from just about any human language in your html document, and they will display reliably.
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
$(document).ready(function(){ alert("hello world!"); $("#blackbox").hide(); }); the above code carries out the same function as the following code: window.onload = function() { alert("hello world!"); document.getelementbyid("blackbox").style.display = "none"; }; or: window.addeventlistener("load", () => { alert("hello world!"); document.getelementbyid("blackbox").style.display = "none"; }); learn more general knowledge jquery on wikipedia jquery official website technical information offical api reference document...
Mobile accessibility - Learn web development
this occurs because we are using code such as the following: div.onmousedown = function() { initialboxx = div.offsetleft; initialboxy = div.offsettop; movepanel(); } document.onmouseup = stopmove; to enable other forms of control, you need to use different, yet equivalent events — for example, touch events work on touchscreen devices: div.ontouchstart = function(e) { initialboxx = div.offsetleft; initialboxy = div.offsettop; positionhand...
Creating fancy letterheaded paper - Learn web development
example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
Test your skills: Images and Form elements - Learn web development
your task is to make the following changes to the way this form looks: use attribute selectors to target the search field and button inside .myform.
Combinators - Learn web development
for example if we want to select list items with a class of "a", which are direct children of a <ul>, i could use the following.
Pseudo-classes and pseudo-elements - Learn web development
try editing the previous live example so it uses the following css.
Test your skills: tables - Learn web development
there are a number of ways that you can achieve this, but i suggest following similar patterns as used in the tutorial to do the following things.
Test your skills: Writing Modes and Logical Properties - Learn web development
task three use logical versions of the margin, border, and padding properties so that the edges of the box relate to the text rather than following top, left, bottom and right.
Test your skills: floats - Learn web development
then we want the first line of text to display next to that element, but the following line of text (which has a class of .below) to display underneath it.
Multiple-column layout - Learn web development
the column-count property will create as many columns as the value you give it, so if you add the following css to your stylesheet and reload the page, you will get three columns: .container { column-count: 3; } the columns that you create have flexible widths — the browser works out how much space to assign each column.
Using your new knowledge - Learn web development
working with css the following live example shows a biography, which has been styled using css.
CSS first steps - Learn web development
guides this module contains the following articles, which will take you through all the basic theory of css, and provide opportunities for you to test out some skills.
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
modern browsers have two main rendering modes: quirks mode: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers.
create fancy boxes - Learn web development
all of the following: its box model properties: width, height, padding, border, etc.
Use CSS to solve common problems - Learn web development
LearnCSSHowto
the following links provide solutions to common problems you may face when working with css.
Typesetting a community school homepage - Learn web development
example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
How can we design for all types of users? - Learn web development
we would advise the following: describe fonts in rem units, most browsers will be very happy with them; let older browsers display fonts with their own internal engine.
What HTML features promote accessibility? - Learn web development
the following content describes specific features of html that can be used to make a web page more accessible to people with different disabilities.
How do I start to design my website? - Learn web development
to do this, you need only pen and paper and some time to answer at least the following questions.
How do you upload your files to a web server? - Learn web development
your account is: demozilla your website will be visible at demozilla.examplehostingprovider.net to publish to this account, please connect through sftp with the following credentials: sftp server: sftp://demozilla.examplehostingprovider.net username: demozilla password: quickbrownfox port: 5548 to publish on the web, put your files into the public/htdocs directory.
What software do I need to build a website? - Learn web development
there are dozens of browser options for your personal use, but when you're developing a website you should test it at least with the following major browsers, to make sure your site works for most people: mozilla firefox google chrome microsoft internet explorer apple safari if you're targeting a specific group (e.g., technical platform or country), you may have to test the site with additional browsers, like opera, konqueror, or uc browser.
How do you set up a local testing server? - Learn web development
to check python is installed, enter the following command: python -v # or you might have the py command available, # in which case try py -v this should return a version number.
Common questions - Learn web development
html, css and javascript questions for common solutions to html/css/javascript problems, try the following articles: use html to solve common problems use css to solve common problems use javascript to solve common problems ...
HTML forms in legacy browsers - Learn web development
here is an example: modernizr.load({ // this tests if your browser supports the html5 form validation api test : modernizr.formvalidation, // if the browser does not support it, the following polyfill is loaded nope : form-validation-api-polyfill.js, // in any case, your core app file that depends on that api is loaded both : app.js, // once both files are loaded, this function is called in order to initialize the app.
CSS property compatibility table for form controls - Learn web development
the following compatibility tables try to summarize the state of css support for html forms.
Sending forms through JavaScript - Learn web development
in the following example, we use the filereader api to access binary data and then build the multi-part form data request by hand: <form id="theform"> <p> <label for="thetext">text data:</label> <input id="thetext" name="mytext" value="some text data" type="text"> </p> <p> <label for="thefile">file data:</label> <input id="thefile" name="myfile" type="file"> </p> <button>send me!</butto...
Test your skills: Styling basics - Learn web development
but your css should aim to fulfill the following requirements: add some kind of lightweight "reset" to make fonts, padding, margin, and sizing more consistent to begin with.
Web forms — Working with user data - Learn web development
advanced articles the following articles aren't essential to the learning pathway, but they'll prove interesting and useful when you've mastered the above techniques and want to know more.
Dealing with files - Learn web development
open up your index.html file, and insert the following code into the file exactly as shown.
Add a hitmap on top of an image - Learn web development
try following links with your keyboard alone.
Define terms with HTML - Learn web development
if two or more terms occur in a row, the following description applies to all of them.
Use HTML to solve common problems - Learn web development
LearnHTMLHowto
the following links point to solutions to common everyday problems you'll need to solve with html.
Advanced text formatting - Learn web development
for example, the following markup is taken from the mdn <blockquote> element page: <p>the <strong>html <code>&lt;blockquote&gt;</code> element</strong> (or <em>html block quotation element</em>) indicates that the enclosed text is an extended quotation.</p> to turn this into a block quote, we would just do this: <p>here below is a blockquote...</p> <blockquote cite="/docs/web/html/element/blockquote"> <p>the <strong>...
Document and website structure - Learn web development
active learning: exploring the code for our example our example seen above is represented by the following code (you can also find the example in our github repository).
Structuring a page of content - Learn web development
example the following screenshot shows an example of what the homepage might look like after being marked up.
Test your skills: Links - Learn web development
links 3 the following links link to an info page about narwhals, a support email address, and a pdf factfile that is 4mb in size.
Adding vector graphics to the Web - Learn web development
more advanced svg features include <fecolormatrix> (transform colors using a transformation matrix,) <animate> (animate parts of your vector graphic,) and <mask> (apply a mask over the top of your image.) as a simple example, the following code creates a circle and a rectangle: <svg version="1.1" baseprofile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="black" /> <circle cx="150" cy="100" r="90" fill="blue" /> </svg> this creates the following output: from the example above, you may get the impression that svg is easy to handcode.
Responsive images - Learn web development
you can find an example of what this looks like in srcset-resolutions.html (see also the source code): <img srcset="elva-fairy-320w.jpg, elva-fairy-480w.jpg 1.5x, elva-fairy-640w.jpg 2x" src="elva-fairy-640w.jpg" alt="elva dressed as a fairy"> in this example, the following css is applied to the image so that it will have a width of 320 pixels on the screen (also called css pixels): img { width: 320px; } in this case, sizes is not needed — the browser simply works out what resolution the display is that it is being shown on, and serves the most appropriate image referenced in the srcset.
HTML Tables - Learn web development
LearnHTMLTables
guides this module contains the following articles: html table basics this article gets you started with html tables, covering the very basics such as rows and cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes.
Structuring the web with HTML - Learn web development
add borders and drop shadows, layout your page with multiple columns, add animations and other visual effects.) javascript, and how to use it to add dynamic functionality to web pages (for example find your location and plot it on a map, make ui elements appear/disappear when you toggle a button, save users' data locally on their computers, and much much more.) modules this topic contains the following modules, in a suggested order for working through them.
General asynchronous programming concepts - Learn web development
consider the following thread diagrams: main thread: task a --> task b in this case, let's say task a is doing something like fetching an image from the server and task b then does something to the image like applying a filter to it.
Test your skills: Loops - Learn web development
loops 3 in this final task, you are provided with the following: i — starts off with a value of 500; intended to be used as an iterator.
JavaScript building blocks - Learn web development
assessments the following assessment will test your understanding of the javascript basics covered in the guides above.
Test your skills: Object basics - Learn web development
each array item should be an object containing the following members: name: a string representing the name of the album.
Measuring performance - Learn web development
at the time of writing, mdn's performance report summary looks similar to the following: a performance report contains information about things like how long a user has to wait before anything is displayed on the page, how many bytes need to be downloaded to display a page, and much more.
Web performance resources - Learn web development
the following snippet includes an onload attribute, requiring javascript, so it is important to include a noscript tag with a traditional fallback.
What is web performance? - Learn web development
this includes the following major areas: reducing overall load time: how long does it take the files required to render the web site to download on to the user's computer?
Learning area release notes - Learn web development
march 2020 you'll now find "test your skills" assessments accompanying the articles in the following modules: css building blocks javascript first steps javascript building blocks introducing javascript objects january 2020 the html forms module has been significantly updated: it has been retitled web forms, and moved out of the html topic area to recognise that it covers more than just html form elements — it also covers styling, validation, the basics of how to send data and proc...
Properly configuring server MIME types - Learn web development
why browsers should not guess mime types apart from violating the http specification, it is a bad strategy for browsers to guess mime types for the following reasons: loss of control if the browser ignores the reported mime type, web administrators and authors no longer have control over how their content is to be processed.
Server-side website programming first steps - Learn web development
we recommend that you first read the following topics: what is a web server?
Using Vue computed properties - Learn web development
adding a summary counter add the following code to your app component object, below the methods property.
Chrome Worker Modules
that is, the following will not show human-readable stacks: try { mymodule.foo(); } catch (ex) { log("exception raised at " + ex.filename) log("stack: " + ex.stack); } rather, you should use properties modulename and modulestack, as follows: try { mymodule.foo(); } catch (ex) { log("exception raised at " + ex.modulename) log("stack: " + ex.modulestack); } subtleties you shouldn’t mix both ...
Accessibility information for UI designers and developers
text spacing users should be able to make the following changes to their text spacing: set line height (leading) to at least 1.5 times the font size set spacing following paragraphs to at least 2 times the font size set letter spacing (tracking) to at least 0.12 times the font size set word spacing to at least 0.16 times the font size this does not mean that your page needs to offer controls to make such changes, merely that if someone does th...
CSUN Firefox Materials
in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a new piece of software.
Mozilla's Section 508 Compliance
the following is provided for informational purposes only and is not a legally binding voluntary product accessibility template (vpat).
Software accessibility: Where are we today?
otherwise, screen magnification programs may be used, which allow zooming in to portions of the screen, while following the mouse or the current focus.
Accessibility and Mozilla
in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a new piece of software.
Index
680 resources for publishers add-ons, extensions, distribution, publication now your add-on is published on amo, check out the following resources: 681 retiring your extension extensions, webextension, end-of-life, publication there may be occasions where you want to retire one of your extensions.
Benchmarking
add the following to your mozconfig in order to build with level 2: ac_add_options rustc_opt_level=2 gc poisoning many firefox builds have a diagnostic tool that causes crashes to happen sooner and produce much more actionable information, but also slow down regular usage substantially.
Browser chrome tests
for example, to run the tests in browser/base/content/test the command would be: ./mach mochitest -f browser browser/base/content/test/ or without mach test_path=<path_to_the_tests> make -c <objdir> mochitest-browser-chrome to run tests in debugger the following should work ./mach mochitest -f browser --debugger gdb browser/base/content/test/ run ./mach help mochitest-browser for more options.
Building SpiderMonkey with UBSan
save the following bash script, fixing llvm_root to point to your installation.
Creating JavaScript callbacks in components
so we could convert the example above to accept javascript functions in place of the stringparserobserver by making the following changes: [scriptable, function, uuid(...)] interface stringparserobserver : nsisupports { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data); void addobserver(stringparserobserver observer); }; note the only change was adding function to the interface attributes of the callback interface.
Creating a Login Manager storage module
sample javascript implementation the following code snippet is a javascript component that implements a dummy nsiloginmanagerstorage interface.
Creating a spell check dictionary add-on
to create a dictionary add-on, simply create a zip file which contains the following files and folders: my-dictionary.xpi install.rdf dictionaries/ locale-code.dic locale-code.aff the .dic and .aff files must be placed in a subfolder named dictionaries within the zip file.
Debugging OpenGL
if you start up firefox with this variable defined, the following behavior changes occur: each time you issue an opengl call, a check is performed to ensure that the gl context is current, using a thread-local static variable to keep track of this.
Debugging Safari
to enable the very useful debug menu in safari use the following: defaults write com.apple.safari includeinternaldebugmenu 1 it is often useful to switch into single process mode by turning off "use multi-process windows" ...
Debugging update problems
useful preferences enabling the following preferences in about:config can help troubleshoot problems with updates: app.update.log - for application updates; extensions.logging.enabled - for add-on updates.
OS TARGET
the following list is not complete as any platform could have its own os_target.
Simple Instantbird build
so firstly complete the instructions for your os and then continue following these build instructions.
Simple Sunbird build
c:\ ) before doing the following steps.
Updating NSPR or NSS in mozilla-central
for example, in the following, "3.16.1" would be replaced with the new nss version.
Windows SDK versions
try the following things in order: run the windows sdk configuration tool (if available) and make sure the right sdk is selected.
pymake
type touch .profile using any appropriate text editor open .profile and add the following line in the file (assuming your mozilla-central is at c:/mozilla-central, if not, adjust your path accordingly.) alias pymake=c:/mozilla-central/build/pymake/make.py save your .profile edit and close the shell, then restart the shell.
ESLint
you'll need to include the following just above it: /* import-globals-from relative/path/to/file.js */ do_check_eq, add_task not defined in a test directory.
Gecko Logging
set moz_log="example_logger:3" in the windows command prompt (cmd.exe), don't use quotes: set moz_log=example_logger:3 if you want this on geckoview example, use the following adb command to launch process: adb shell am start -n org.mozilla.geckoview_example/.geckoviewactivity --es env0 "moz_log=example_logger:3" there are special module names to change logging behavior.
Reviewer Checklist
following these best practices will lead to a smoother, more rapid process of review and acceptance.
Experimental features in Firefox
nightly 73 no developer edition 73 no beta 73 no release 73 no preference name layout.css.constructable-stylesheets.enabled webrtc and media the following experimental features include those found in the webrtc api, the web audio api, the media session api, the media source extensions api, the encrypted media extensions api, and the media capture and streams api.
Index
141 index firefox, index, mozilla found 168 pages: 142 linux compatibility matrix the following table lists the available library versions for the mozilla.org-distributed firefox builds dependencies, and/or to build firefox.
Linux compatibility matrix
the following table lists the available library versions for the mozilla.org-distributed firefox builds dependencies, and/or to build firefox.
Multiple Firefox profiles
the following tutorial will help get you going overall: gnome 3 custom application launcher.
Cross Process Object Wrappers
one of these shims provides the following behavior: whenever chrome code tries to access content directly (for example, through window.content or browser.contentdocument), it is given back a cpow that wraps the content object.
Communicating with frame scripts
the message passed to the listener is an object containing the following properties: name string containing the message name.
Performance
the following examples omit some boilerplate code for the sake of brevity the "better" examples also omit some best practices and only demonstrate how to fix the problem described in their respective subtopics.
Process scripts
the following code uses the global parent process message manager, which will load the script into the the chrome process and any child processes: // chrome code let ppmm = cc["@mozilla.org/parentprocessmessagemanager;1"] .getservice(ci.nsiprocessscriptloader); ppmm.loadprocessscript("chrome://whatever/process-script.js", true); ppmm.addmessagelistener("hello", function(msg) { ...
Performance best practices for Firefox front-end engineers
the rendering process goes through the following steps: the above image is used under creative commons attribution 3.0, courtesy of this page from our friends at google, which itself is well worth the read.
Security best practices for Firefox front-end engineers
we use our built-in sanitizer with the following flags: sanitizerallowstyle sanitizerallowcomments sanitizerdropforms sanitizerlogremovals the sanitizer removes all scripts (script tags, event handlers) and form elements (form, input, keygen, option, optgroup, select, button, datalist).
Firefox
linux compatibility matrixthe following table lists the available library versions for the mozilla.org-distributed firefox builds dependencies, and/or to build firefox.multiple firefox profilesa profile in firefox is the collection of settings, customizations, add-ons, and other personalizations that a user has made or installed into their copy of firefox.
HTMLIFrameElement.clearMatch()
examples the following function is taken from our browser api demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active.
HTMLIFrameElement.findAll()
casesensitivity a string to declare whether you want the search to be case sensitive (case-sensitive) or insensitive (case-insensitive.) example the following function is taken from our browser api demo, and executes a search when a search form is submitted.
HTMLIFrameElement.findNext()
examples the following functions are taken from our browser api demo, and cycle through the available search results.
mozbrowseractivitydone
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).
mozbrowserasyncscroll
details the details property returns an anonymous javascript object with the following properties: top the scroll top position in css pixels of the document within the browser <iframe>.
mozbrowsercaretstatechanged
details the details property returns an anonymous javascript object with the following properties: rect an object that defines information about the bounding rectangle of the current selection.
mozbrowsercontextmenu
details the details property returns an anonymous javascript object with the following properties: clientx the x value of the coordinate that was clicked inside the browser <iframe>'s viewport.
mozbrowsererror
detail the detail property returns an anonymous javascript object with the following properties: type a domstring representing the type of error that occurred.
mozbrowserfindchange
details the details property returns an anonymous javascript object with the following properties: active a boolean indicating whether a search is currently active (true), or not (false.) searchstring a domstring representing the string that is currently being searched for.
mozbrowsericonchange
details the details property returns an anonymous javascript object with the following properties: href a domstring representing the path to the new icon.
mozbrowserloadend
detail the detail property returns an anonymous javascript object with the following properties: backgroundcolor a domstring representing the main background color of the browser <iframe> content, expressed as an rgb value.
mozbrowserlocationchange
detail the detail property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new location.
mozbrowsermanifestchange
details the details property returns an anonymous javascript object with the following properties: href the url of the new app manifest.
mozbrowsermetachange
details the details property returns an anonymous javascript object with the following properties: name a domstring representing the <meta> name attribute value.
mozbrowseropensearch
details the details property returns an anonymous javascript object with the following properties: title a domstring representing the title of the search engine.
mozbrowseropentab
details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded.
mozbrowseropenwindow
details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the document loaded within the frameelement property.
mozbrowserresize
details the details property returns an anonymous javascript object with the following properties: width a number representing the new width of the <iframe> viewport, in device pixels.
mozbrowserscroll
details the details property returns an anonymous javascript object with the following properties: top a number representing the new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport.
mozbrowserscrollareachanged
details the details property returns an anonymous javascript object with the following properties: width a number representing the new scroll area width of the <iframe> viewport, in css pixels.
mozbrowserscrollviewchange
details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of scrolling in the viewport — available values are started and stopped.
mozbrowsersecuritychange
details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of ssl security.
mozbrowserselectionstatechanged
details the details property returns an anonymous javascript object with the following properties: rect an object that represents the bounding rectangle of the selection.
mozbrowsershowmodalprompt
details the details property is an anonymous javascript object with the following properties: prompttype a domstring defining the type of the prompt.
mozbrowserusernameandpasswordrequired
details the details property returns an anonymous javascript object with the following members: host a domstring representing the host requesting the http authentification.
mozbrowservisibilitychange
details the details property returns an anonymous javascript object with the following properties: visible a boolean that indicates whether the browser iframe is visible (true) or not (false).
CSS <display-xul> component
firefox supports the following -moz- prefixed xul display values: syntax -moz-box obsolete since gecko 64 xul box, mostly equivalent to flex -moz-inline-box obsolete since gecko 64 xul inline box, mostly equivalent to inline-flex -moz-grid obsolete since gecko 62 xul grid -moz-inline-grid obsolete since gecko 62 xul inline grid -moz-grid-group obsolete since gecko 62 xul grid group -moz-grid-line obsolete since gecko 62 xul grid line -moz-stack obsolete since gecko 62 xul stack -moz-inline-stack obsolete since gecko 62 xul inline stack -moz-deck obsolete since gecko 62 xul deck -moz-popup obsolete since gecko 62 xul popup all xul display values, with the exception of -moz-box and -moz-inline-box, have been removed in bug 1288572.
Chrome-only CSS reference
MozillaGeckoChromeCSS
mouse cursor is presently hovering over a tree row.::-moz-tree-separatoractivated by the properties attribute.::-moz-tree-twistyactivated by the properties attribute.css -moz-bool-pref() @supports functionthe -moz-bool-pref() @supports condition is available to gecko chrome and ua stylesheets to check if a boolean preference is enabled.css <display-xul> component</display-xul>firefox supports the following -moz- prefixed xul display values:overflow-clip-boxthe overflow-clip-box css property specifies relative to which box the clipping happens when there is an overflow.
Gecko versions and application versions
the following table shows the various versions of gecko and what versions of common applications are based on them.
Gecko's "Almost Standards" Mode
for example, consider the following doctype: <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> the parts are as follows: public identifier: "-//w3c//dtd html 4.01 transitional//en" system identifier: "http://www.w3.org/tr/html4/loose.dtd" thus any html 4.01 transitional or frameset doctype with a uri (system identifier) will trigger "almost standards" mode, as will any...
Getting from Content to Layout
the frame constructor takes these notifications and does the following: dispatches "restyle events" which trigger the reprocessing of relevant css selectors and any restyling that needs to occur.
How Mozilla determines MIME Types
it does the following: checks the start of the file for "magic numbers"; this can currently detect pdf and postscript.
PBackground
ipdl protocols are used to specify how the chrome and content processes talk to each other and verify that a content process is "following the rules".
Infallible memory allocation
explicitly infallible memory allocators the following memory allocators are explicitly infallible, and will remain so; they are guaranteed to return a valid memory pointer.
AddonListener
only applies to the following properties: applybackgroundupdates void onpropertychanged( in addon addon, in string properties[] ) parameters addon the addon that has had its properties changed properties an array of the names of properties that changed.
AddonManager
the existing add-on types are defined in xpiprovider.jsm and are, at this time, the following: extension, theme, locale, multipackage, dictionary and experiment.
AddonScreenshot
a screenshot object for an add-on can have following attributes.
Code Samples
getting the directory where your add-on is located if you need to determine the directory in which your add-on is installed, code like the following will do the trick.
UpdateListener
for each individual update check, the following methods will be called on the listener: either oncompatibilityupdateavailable() or onnocompatibilityupdateavailable(), depending on whether compatibility information for the requested application version was seen.
AsyncShutdown.jsm
please make sure that the name respects the following model: "some service: some action in progress" - for instance "os.file: flushing all pending i/o".
DownloadList
the following methods may be defined: ondownloadadded: optional this function is called with a single download argument, after the download is added to the end of the list.
DownloadSummary
the following methods may be defined: onsummarychanged: optional called after any property of the summary has changed.
Http.jsm
httprequest supports the following parameters: name meaning headers an array of headers postdata this can be: a string: send it as is an array of parameters: encode as form values null/undefined: no post data.
Log.jsm
ream reset(); structuredformatter(); length: 0 keys of prototype: format(); method overview enumerateinterfaces(); length: 0 enumerateproperties(); length: 2 member fields variable type description level object contains the following fields: field name value all 0 config 30 debug 20 desc { 0: "all", 10: "trace", 20: "debug", 30: "config", 40: "info", 50: "warn", 60: "error", 70: "fatal" } error 30 fatal 70 in...
NetUtil.jsm
options the aoptions parameter is a javascript object which can have any or all of the following fields: field name description charset the character encoding to use when interpreting the input stream.
OS.File.Error
} catch (ex) { if (ex instanceof os.file.error && ex.becausenosuchfile) { // the file does not exist } } global object os.file.error methods overview the following functions are utility functions that may be used to construct instances of os.file.error, setting the platform-specific error number.
OS.File.Info
using os.file.info example: determining if a file is a regular file the following snippet uses the main thread api to determine (asynchronously) whether some path is a regular file, or a directory, or a symbolic link: let promise = os.file.stat(somepath); promise.then( function onsuccess(info) { // |info| is an instance of |os.file.info| if (info.isdir) { // |somepath| represents a directory } else if (info.issymlink) { // |somepath| represents a symboli...
Promise
promise catch( function onreject ); the following calls are therefore identical: p.then(undefined, logerror); p.catch(logerror); debugging by design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the then() method.
Using JavaScript code modules
just call the following: const { require } = cu.import("resource://gre/modules/commonjs/toolkit/require.js", {}) this will import require() into your scope.
Encodings for localization files
browser/installer/installer.inc utf-8 toolkit/installer/unix/install.it utf-8 native windows encodings the following table lists native windows encodings, and the win_installer_charset and charset= values for each: encoding name win_installer_charset (charset.mk) charset= (windows/install.it) ansi_charset cp1252 0 baltic_charset cp1257 186 chinesebig5_charset cp950 136 easteurope_charset cp1250 238 gb2312_charset cp936 13...
Mozilla Content Localized in Your Language
formal and informal forms, and separators (, or .) date format what are the date formats for weeks and months are expressed in the following forms: 1)fully spelled out, 2).
L10n testing with xcode
to view these strings, you'll need to start the accessibility inspector within the ios simulator by doing the following.
Localizing XLIFF files for iOS
keep in mind the following sets of characters that need to remain untranslated: $(some_text_here) is a variable format, %1$@ is another variable format.
Localizing with Mozilla Translator
see the following example.
Localizing with Pontoon
only the toolbar on top belongs to pontoon, containing the following items (from left to right): list of strings opens a sidebar with a list of all strings to localize.
Patching a Localization
start bash and do the following: create a clean directory for your work.
Initial setup
you can install either by searching for them in firefox's add-ons manager or following these links.
Localization sign-off reviews
this article presents an overview of why we do sign-off reviews of localizations, the details on the criteria used for the sign-off reviews, and the process for requesting a review and for following its progress.
Web Localizability
the following list contains links to pages that highlight steps that can be taken to make web content localizable.
What every Mozilla translator should know
bugzilla, the bug-tracking system you do need an account in bugzilla you should configure the account to watch the following addresses: firefoxl10n@hotmail.com calendar-l10n@mozilla.bugs (specific for calendar related bugs) this way you will receive mail for bugs affecting many or even all locales.
Fonts for Mozilla's MathML engine
on debian/ubuntu/mint and other debian-based distributions, use the following command: sudo apt-get install fonts-lmodern fonts-stix on fedora and other fedora-based distributions, use the following command (stix-math-fonts is often already installed): sudo dnf install texlive-lm-math stix-math-fonts on opensuse and other opensuse-based distributions, use the following command: sudo zypper install texlive-lm-math stix-fonts on other linux distributions, consider inst...
MathML Torture Test
addeventlistener("change", updatemathfont, false) } window.addeventlistener("load", load, false); the following test contains sample tex formulas from knuth's tex book and equivalent mathml representations.
Mozilla Port Blocking
if a user attempts to access a uri on a blocked port, mozilla shows one of the following alerts to the user or in the error console.
Mozilla Web Developer FAQ
mathml svg (in svg-enabled builds only) xul (please note that xul is mozilla-specific and, therefore, using it on the public web causes interoperabilty problems.) xml:base is observed when following links.
Mozilla Web Services Security Model
the type attribute the type attribute of the allow element can take the following values: any means that the allow element applies to all services that use web-scripts-access.xml for security checks.
Mozilla Quirks Mode Behavior
the following is a rough list of the differences that exist between mozilla's standards mode and quirks mode behavior.
Mozilla Style System Documentation
for example, suppose we had the css stylesheet: /* rule 1 */ doc { display: block; text-indent: 1em; } /* rule 2 */ title { display: block; font-size: 3em; } /* rule 3 */ para { display: block; } /* rule 4 */ [class="emph"] { font-style: italic; } and the following document: <doc> <title>a few quotes</title> <para class="emph">benjamin franklin said that <quote>"a penny saved is a penny earned."</quote></para> <para>franklin d.
Profiling with Xperf
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.
dtrace
a good starting command for profiling wakeups is the following.
Phishing: a short definition
the following is a non-exhaustive list of the most common approaches.
A brief guide to Mozilla preferences
preferences loading and resolution on application launch, the application loads preferences in the following order: load all default pref files.
Productization guide
the following (and last) page will cover the technical steps to creating and submitting productization patches.
L20n HTML Bindings
consider the following source html: <p data-l10n-id="save"> <input type="submit"> <a href="/main" class="btn-cancel"></a> </p> assume the following malicious translation: <save """ <input value="save" type="text"> or <a href="http://myevilwebsite.com" onclick="alert('pwnd!')" title="back to the homepage">cancel</a>.
NSPR Contributor Guide
the following are some general guidelines to use when implementing new features: don't export global variables your code must be thread safe you must provide test cases that test all apis you are adding.
NSPR Poll Method
otherwise ((new_flags & out_flags) is 0), you should do the following.
NSPR build instructions
on mac os x, they can be executed with the following: /bin/sh: $ cd pr/tests $ dyld_library_path=../../dist/lib ./accept pass $ $ # to run all the nspr tests...
Programs Using NSPR
the following programs are known to use nspr, or portions of it: gecko using programs (mozilla application suite, firefox, thunderbird, camino, etc.) many fedora/red hat and sun server applications.
Dynamic Library Linking
for example, link your executable program a.out without the +s option, then execute the following: chatr +s enable a.out on rhapsody, the environment variable is dyld_library_path.
Introduction to NSPR
nspr naming conventions naming of nspr types, functions, and macros follows the following conventions: types exported by nspr begin with pr and are followed by intercap-style declarations, like this: print, prfiledesc function definitions begin with pr_ and are followed by intercap-style declarations, like this: pr_read, pr_jointhread preprocessor macros begin with the letters pr and are followed by all uppercase characters separated with the underscore character (_), like this: ...
Logging
of logging at execution time: nspr_log_modules nspr_log_file logging functions and macros the functions and macros for logging are: pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_static_assert (new in nspr 4.6.6xxx this hasn't been released yet; the number is a logical guess) pr_not_reached use example the following sample code fragment demonstrates use of the logging and debugging aids.
NSPR LOG MODULES
level is a numeric value between 0 and 5, with the values having the following meanings: 0 = pr_log_none: nothing should be logged 1 = pr_log_always: important; intended to always be logged 2 = pr_log_error: errors 3 = pr_log_warning: warnings 4 = pr_log_debug: debug messages, notices 5: everything!
NSPR Types
here are some simple examples of the use of these types: in dowhim.h: pr_extern( void ) dowhatimean( void ); static void pr_callback rootfunction(void *arg); in dowhim.c: pr_implement( void ) dowhatimean( void ) { return; }; prthread *thread = pr_createthread(..., rootfunction, ...); algebraic types nspr provides the following type definitions with unambiguous bit widths for algebraic operations: 8-, 16-, and 32-bit integer types 64-bit integer types floating-point number type for convenience, nspr also provides type definitions with platform-dependent bit widths: native os integer types 8-, 16-, and 32-bit integer types signed integers print8 print16 print32 unsigned integers pruint8 pruint16 ...
PLHashEntry
an entry has a key and a value, represented by the following fields in the plhashentry structure.
PL_HashString
syntax #include <plhash.h> plhashnumber pl_hashstring(const void *key); parameter the function has the following parameter: key a pointer to a character string.
PL_HashTableAdd
syntax #include <plhash.h> plhashentry *pl_hashtableadd( plhashtable *ht, const void *key, void *value); parameters the function has the following parameters: ht a pointer to the the hash table to which to add the entry.
PL_HashTableDestroy
syntax #include <plhash.h> void pl_hashtabledestroy(plhashtable *ht); parameter the function has the following parameter: ht a pointer to the hash table to be destroyed.
PL_HashTableEnumerateEntries
syntax #include <plhash.h> printn pl_hashtableenumerateentries( plhashtable *ht, plhashenumerator f, void *arg); parameters the function has the following parameters: ht a pointer to the hash table whose entries are to be enumerated.
PL_HashTableLookup
syntax #include <plhash.h> void *pl_hashtablelookup( plhashtable *ht, const void *key); parameters the function has the following parameters: ht a pointer to the hash table in which to look up the entry specified by key.
PL_HashTableRemove
syntax #include <plhash.h> prbool pl_hashtableremove( plhashtable *ht, const void *key); parameters the function has the following parameters: ht a pointer to the hash table from which to remove the entry.
PL_NewHashTable
syntax #include <plhash.h> plhashtable *pl_newhashtable( pruint32 numbuckets, plhashfunction keyhash, plhashcomparator keycompare, plhashcomparator valuecompare, const plhashallocops *allocops, void *allocpriv ); parameters the function has the following parameters: numbuckets the number of buckets in the hash table.
PRFileInfo
syntax #include <prio.h> struct prfileinfo { prfiletype type; pruint32 size; prtime creationtime; prtime modifytime; }; typedef struct prfileinfo prfileinfo; fields the structure has the following fields: type type of file.
PRFileInfo64
syntax #include <prio.h> struct prfileinfo64 { prfiletype type; pruint64 size; prtime creationtime; prtime modifytime; }; typedef struct prfileinfo64 prfileinfo64; fields the structure has the following fields: type type of file.
PRFileType
syntax #include <prio.h> typedef enum prfiletype{ pr_file_file = 1, pr_file_directory = 2, pr_file_other = 3 } prfiletype; enumerators the enumeration has the following enumerators: pr_file_file the information in the structure describes a file.
PRHostEnt
syntax #include <prnetdb.h> typedef struct prhostent { char *h_name; char **h_aliases; #if defined(_win32) print16 h_addrtype; print16 h_length; #else print32 h_addrtype; print32 h_length; #endif char **h_addr_list; } prhostent; fields the structure has the following fields: h_name pointer to the official name of host.
PRLinger
syntax #include <prio.h> typedef struct prlinger { prbool polarity; printervaltime linger; } prlinger; fields the structure has the following fields: polarity polarity of the option's setting: pr_false means the option is off, in which case the value of linger is ignored.
PRMcastRequest
syntax #include <prio.h> struct prmcastrequest { prnetaddr mcaddr; prnetaddr ifaddr; }; typedef struct prmcastrequest prmcastrequest; fields the structure has the following fields: mcaddr ip multicast address of group.
PRNetAddr
ddr { struct { pruint16 family; char data[14]; } raw; struct { pruint16 family; pruint16 port; pruint32 ip; char pad[8]; } inet; #if defined(_pr_inet6) struct { pruint16 family; pruint16 port; pruint32 flowinfo; pripv6addr ip; } ipv6; #endif /* defined(_pr_inet6) */ }; typedef union prnetaddr prnetaddr; fields the structure has the following fields: family address family: pr_af_inet|pr_af_inet6 for raw.family, pr_af_inet for inet.family, pr_af_inet6 for ipv6.family.
PRProtoEnt
syntax #include <prnetdb.h> typedef struct prprotoent { char *p_name; char **p_aliases; #if defined(_win32) print16 p_num; #else print32 p_num; #endif } prprotoent; fields the structure has the following fields: p_name pointer to official protocol name.
PRSeekWhence
syntax #include <prio.h> typedef prseekwhence { pr_seek_set = 0, pr_seek_cur = 1, pr_seek_end = 2 } prseekwhence; enumerators the enumeration has the following enumerators: pr_seek_set sets the file pointer to the value of the offset parameter.
PRSockOption
ddr, pr_sockopt_keepalive, pr_sockopt_recvbuffersize, pr_sockopt_sendbuffersize, pr_sockopt_iptimetolive, pr_sockopt_iptypeofservice, pr_sockopt_addmember, pr_sockopt_dropmember, pr_sockopt_mcastinterface, pr_sockopt_mcasttimetolive, pr_sockopt_mcastloopback, pr_sockopt_nodelay, pr_sockopt_maxsegment, pr_sockopt_last } prsockoption; enumerators the enumeration has the following enumerators: pr_sockopt_nonblocking nonblocking i/o.
PRSocketOptionData
pruintn tos; prbool non_blocking; prbool reuse_addr; prbool keep_alive; prbool mcast_loopback; prbool no_delay; prsize max_segment; prsize recv_buffer_size; prsize send_buffer_size; prlinger linger; prmcastrequest add_member; prmcastrequest drop_member; prnetaddr mcast_if; } value; } prsocketoptiondata; fields the structure has the following fields: ip_ttl ip time-to-live.
PR_AcceptRead
syntax #include <prio.h> print32 pr_acceptread( prfiledesc *listensock, prfiledesc **acceptedsock, prnetaddr **peeraddr, void *buf, print32 amount, printervaltime timeout); parameters the function has the following parameters: listensock a pointer to a prfiledesc object representing a socket descriptor that has been called with the pr_listen function, also known as the rendezvous socket.
PR_AtomicAdd
syntax #include <pratom.h> print32 pr_atomicadd( print32 *ptr, print32 val); parameter the function has the following parameters: ptr a pointer to the value to increment.
PR_AtomicDecrement
syntax #include <pratom.h> print32 pr_atomicdecrement(print32 *val); parameter the function has the following parameter: val a pointer to the value to decrement.
PR_AtomicIncrement
syntax #include <pratom.h> print32 pr_atomicincrement(print32 *val); parameter the function has the following parameter: val a pointer to the value to increment.
PR_AtomicSet
syntax #include <pratom.h> print32 pr_atomicset( print32 *val, print32 newval); parameters the function has the following parameter: val a pointer to the value to be set.
PR_AttachThread
syntax #include <pprthread.h> prthread* pr_attachthread( prthreadtype type, prthreadpriority priority, prthreadstack *stack); parameters pr_attachthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread).
PR_CNotify
syntax #include <prcmon.h> prstatus pr_cnotify(void *address); parameter the function has the following parameter: address the address of the monitored object.
PR_CNotifyAll
syntax #include <prcmon.h> prstatus pr_cnotifyall(void *address); parameter the function has the following parameter: address the address of the monitored object.
PR_CancelJob
syntax #include <prtpool.h> nspr_api(prstatus) pr_canceljob(prjob *job); parameter the function has the following parameter: job a pointer to a prjob structure returned by a pr_queuejob function representing the job to be cancelled.
PR_Cleanup
syntax #include <prinit.h> prstatus pr_cleanup(void); returns the function returns one of the following values: if nspr has been shut down successfully, pr_success.
PR_CloseDir
syntax #include <prio.h> prstatus pr_closedir(prdir *dir); parameter the function has the following parameter: dir a pointer to a prdir structure representing the directory to be closed.
PR_CloseSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_closesemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure returned from a call to pr_opensemaphore.
PR_ConnectContinue
syntax #include <prio.h> prstatus pr_connectcontinue( prfiledesc *fd, print16 out_flags); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
PR ConvertIPv4AddrToIPv6
syntax #include <prnetdb.h> void pr_convertipv4addrtoipv6( pruint32 v4addr, pripv6addr *v6addr ); parameters the function has the following parameters: v4addr the ipv4 address to convert into an ipv4-mapped ipv6 address.
PR_CreateIOLayerStub
syntax #include <prio.h> prfiledesc* pr_createiolayerstub( prdescidentity ident priomethods const *methods); parameters the function has the following parameters: ident the identity to be associated with the new layer.
PR_CreatePipe
syntax #include <prio.h> prstatus pr_createpipe( prfiledesc **readpipe, prfiledesc **writepipe); parameters the function has the following parameters: readpipe a pointer to a prfiledesc pointer.
PR_CreateThreadPool
syntax #include <prtpool.h> nspr_api(prthreadpool *) pr_createthreadpool( print32 initial_threads, print32 max_threads, pruint32 stacksize ); parameters the function has the following parameters: initial_threads the number of threads to be created within this thread pool.
PR_DeleteSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_deletesemaphore(const char *name); parameter the function has the following parameter: name the name of a semaphore that was previously created via a call to pr_opensemaphore.
PR_DestroyMonitor
syntax #include <prmon.h> void pr_destroymonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor.
PR_EnterMonitor
syntax #include <prmon.h> void pr_entermonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor.
PR EnumerateAddrInfo
syntax #include <prnetdb.h> void *pr_enumerateaddrinfo( void *enumptr, const praddrinfo *addrinfo, pruint16 port, prnetaddr *result); parameters the function has the following parameters: enumptr the index pointer of the enumeration.
PR_ExportFileMapAsString
syntax #include <prshma.h> nspr_api( prstatus ) pr_exportfilemapasstring( prfilemap *fm, prsize bufsize, char *buf ); define pr_filemap_string_bufsize 128 parameters the function has the following parameters: fm a pointer to the prfilemap to be represented as a string.
PR FreeAddrInfo
syntax #include <prnetdb.h> void pr_enumerateaddrinfo(praddrinfo *addrinfo); parameters the function has the following parameters: addrinfo a pointer to a praddrinfo structure returned by a successful call to pr_getaddrinfobyname.
PR GetCanonNameFromAddrInfo
syntax #include <prnetdb.h> const char *pr_getcanonnamefromaddrinfo(const praddrinfo *addrinfo); parameters the function has the following parameters: addrinfo a pointer to a praddrinfo structure returned by a successful call to pr_getaddrinfobyname.
PR_GetConnectStatus
syntax prstatus pr_getconnectstatus(const prpolldesc *pd); parameter the function has the following parameter: pd a pointer to a prpolldesc satructure whose fd field is the socket and whose in_flags field must contain pr_poll_write and pr_poll_except.
PR_GetInheritedFileMap
syntax #include <prshma.h> nspr_api( prfilemap *) pr_getinheritedfilemap( const char *shmname ); parameter the function has the following parameter: shmname the name provided to pr_processattrsetinheritablefilemap.
PR_GetLayersIdentity
syntax #include <prio.h> prdescidentity pr_getlayersidentity(prfiledesc* fd); parameter the function has the following parameter: fd a pointer to a file descriptor.
PR_GetPeerName
syntax #include <prio.h> prstatus pr_getpeername( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket.
PR_GetSockName
syntax #include <prio.h> prstatus pr_getsockname( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the socket.
PR_GetSocketOption
syntax #include <prio.h> prstatus pr_getsocketoption( prfiledesc *fd, prsocketoptiondata *data); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the socket whose options are to be retrieved.
PR_GetSpecialFD
syntax #include <prio.h> prfiledesc* pr_getspecialfd(prspecialfd id); parameter the function has the following parameter: id a pointer to an enumerator of type prspecialfd, indicating the type of i/o stream desired: pr_standardinput, pr_standardoutput, or pr_standarderror.
PR_GetThreadPriority
syntax #include <prthread.h> prthreadpriority pr_getthreadpriority(prthread *thread); parameter pr_getthreadpriority has the following parameter: thread a valid identifier for the thread whose priority you want to know.
PR_GetThreadPrivate
syntax #include <prthread.h> void* pr_getthreadprivate(pruintn index); parameter pr_getthreadprivate has the following parameters: index the index into the per-thread private data table.
PR_ImportFileMapFromString
syntax #include <prshma.h> nspr_api( prfilemap * ) pr_importfilemapfromstring( const char *fmstring ); parameter the function has the following parameter: fmstring a pointer to string created by pr_exportfilemapasstring.
PR_Init
syntax #include <prinit.h> void pr_init( prthreadtype type, prthreadpriority priority, pruintn maxptds); parameters pr_init has the following parameters: type this parameter is ignored.
PR_Initialize
syntax #include <prinit.h> printn pr_initialize( prprimordialfn prmain, printn argc, char **argv, pruintn maxptds); parameters pr_initialize has the following parameters: prmain the function that becomes the primordial thread's root function.
PR_Initialized
syntax #include <prinit.h> prbool pr_initialized(void); returns the function returns one of the following values: if pr_init has already been called, pr_true.
PR_JoinJob
syntax #include <prtpool.h> nspr_api(prstatus) pr_joinjob(prjob *job); parameter the function has the following parameter: job a pointer to a prjob structure returned by a pr_queuejob function representing the job to be cancelled.
PR_JoinThreadPool
syntax #include <prtpool.h> nspr_api(prstatus) pr_jointhreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_MemMap
syntax #include <prio.h> void* pr_memmap( prfilemap *fmap, print64 offset, pruint32 len); parameters the function has the following parameters: fmap a pointer to the file-mapping object representing the file to be memory-mapped.
PR_MicrosecondsToInterval
syntax #include <prinrval.h> printervaltime pr_microsecondstointerval(pruint32 milli); parameter the function has the following parameter: micro the number of microseconds to convert to interval form.
PR_MillisecondsToInterval
syntax #include <prinrval.h> printervaltime pr_millisecondstointerval(pruint32 milli); parameter the function has the following parameter: milli the number of milliseconds to convert to interval form.
PR_NewCondVar
returns the function returns one of the following values: if successful, a pointer to the new condition variable object.
PR_NewLock
syntax #include <prlock.h> prlock* pr_newlock(void); returns the function returns one of the following values: if successful, a pointer to the new lock object.
PR_NewMonitor
syntax #include <prmon.h> prmonitor* pr_newmonitor(void); returns the function returns one of the following values: if successful, a pointer to a prmonitor object.
PR_NewTCPSocket
syntax #include <prio.h> prfiledesc* pr_newtcpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened ipv4 tcp socket.
PR_NewUDPSocket
syntax #include <prio.h> prfiledesc* pr_newudpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
PR_NotifyAllCondVar
syntax #include <prcvar.h> prstatus pr_notifyallcondvar(prcondvar *cvar); returns the function returns one of the following values: if successful, pr_success.
PR_NotifyCondVar
returns the function returns one of the following values: if successful, pr_success.
PR_OpenAnonFileMap
creates or opens a named semaphore with the specified name syntax #include <prshma.h> nspr_api( prfilemap *) pr_openanonfilemap( const char *dirname, prsize size, prfilemapprotect prot ); parameters the function has the following parameters: dirname a pointer to a directory name that will contain the anonymous file.
PR_OpenDir
syntax #include <prio.h> prdir* pr_opendir(const char *name); parameter the function has the following parameter: name the pathname of the directory to be opened.
PR_OpenSemaphore
syntax #include <pripcsem.h> #define pr_sem_create 0x1 /* create if not exist */ #define pr_sem_excl 0x2 /* fail if already exists */ nspr_api(prsem *) pr_opensemaphore( const char *name, printn flags, printn mode, pruintn value ); parameters the function has the following parameters: name the name to be given the semaphore.
PR_OpenSharedMemory
#include <prshm.h> nspr_api( prsharedmemory * ) pr_opensharedmemory( const char *name, prsize size, printn flags, printn mode ); /* define values for pr_opensharememory(...,create) */ #define pr_shm_create 0x1 /* create if not exist */ #define pr_shm_excl 0x2 /* fail if already exists */ parameters the function has the following parameters: name the name of the shared memory segment.
PR_PostSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_postsemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure returned from a call to pr_opensemaphore.
PR_ProcessAttrSetInheritableFileMap
syntax #include <prshma.h> nspr_api(prstatus) pr_processattrsetinheritablefilemap( prprocessattr *attr, prfilemap *fm, const char *shmname ); parameters the function has the following parameters: attr pointer to a prprocessattr structure used to pass data to pr_createprocess.
PR_QueueJob
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob( prthreadpool *tpool, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Accept
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_accept( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Connect
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_connect( prthreadpool *tpool, prjobiodesc *iod, const prnetaddr *addr, prjobfn fn, void * arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Read
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_read( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Timer
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_timer( prthreadpool *tpool, printervaltime timeout, prjobfn fn, void * arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Write
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_write( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_RmDir
syntax #include <prio.h> prstatus pr_rmdir(const char *name); parameter the function has the following parameter: name the name of the directory to be removed.
PR_SecondsToInterval
syntax #include <prinrval.h> printervaltime pr_secondstointerval(pruint32 seconds); parameter the function has the following parameter: seconds the number of seconds to convert to interval form.
PR_SetLibraryPath
returns the function returns one of the following values: if successful, pr_success.
PR_SetSocketOption
syntax #include <prio.h> prstatus pr_setsocketoption( prfiledesc *fd, prsocketoptiondata *data); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the socket whose options are to be set.
PR_SetThreadPriority
syntax #include <prthread.h> void pr_setthreadpriority( prthread *thread, prthreadpriority priority); parameters pr_setthreadpriority has the following parameters: thread a valid identifier for the thread whose priority you want to set.
PR_ShutdownThreadPool
syntax #include <prtpool.h> nspr_api(prstatus) pr_shutdownthreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_Sleep
syntax #include <prthread.h> prstatus pr_sleep(printervaltime ticks); parameter pr_sleep has the following parameter: ticks the number of ticks you want the thread to sleep for (see printervaltime).
PR_UnloadLibrary
returns the function returns one of the following values: if successful, pr_success.
PR_Unlock
returns the function returns one of the following values: if successful, pr_success.
PR_VersionCheck
returns the function returns one of the following values: if the version of the shared library is compatible with that expected by the caller, pr_true.
PR_WaitSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_waitsemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure returned from a call to pr_opensemaphore.
PR_htonl
syntax #include <prnetdb.h> pruint32 pr_htonl(pruint32 conversion); parameter the function has the following parameter: conversion the 32-bit unsigned integer, in host byte order, to be converted.
PR_htons
syntax #include <prnetdb.h> pruint16 pr_htons(pruint16 conversion); parameter the function has the following parameter: conversion the 16-bit unsigned integer, in host byte order, to be converted.
PR_ntohl
syntax #include <prnetdb.h> pruint32 pr_ntohl(pruint32 conversion); parameter the function has the following parameter: conversion the 32-bit unsigned integer, in network byte order, to be converted.
PR_ntohs
syntax #include <prnetdb.h> pruint16 pr_ntohs(pruint16 conversion); parameter the function has the following parameter: conversion the 16-bit unsigned integer, in network byte order, to be converted.
NSPR
opensuse linux: install one or more of the following via yast or zypper : mozilla-nspr : binary libraries for your platform mozilla-nspr-32bit : binary libraries needed to run 32-bit programs on a 64-bit os mozilla-nspr-devel : files needed (in addition to the above libraries) to compile programs using nspr mozilla-nspr-debuginfo : debug information (including build symbols) for package mozilla-nspr mozilla-nspr-debuginfo-32bit : ...
An overview of NSS Internals
the public keys that are exchanged between parties are transported using a container; the container is called a certificate, following standard x.509 version 3.
Function_Name
see also copy of the mxr link, with the following text occurrences of function_name in the current nss source code (generated by mxr).
Building NSS
to check out the latest sources for nss and nspr--which may not be part of a stable release--use the following commands: hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss to get the source of a specific release, see nss releases.
Deprecated SSL functions
the following ssl functions have been replaced with newer versions.
Build instructions for JSS 4.3.x
build instructions for jss 4.3.x newsgroup: mozilla.dev.tech.crypto before building jss, you need to set up your system as follows: build nspr/nss by following the nspr/nss build instructions, to check that nss built correctly, run all.sh (in mozilla/security/nss/tests) and examine the results (in mozilla/test_results/security/computername.#/results.html.
Using JSS
MozillaProjectsNSSJSSUsing JSS
the following table gives the core names of the libraries, omitting the platform-specific prefix and suffix.
NSS 3.14.1 release notes
bugs fixed in nss 3.14.1 the following bugzilla query returns all of the bugs fixed in nss 3.14.1: https://bugzilla.mozilla.org/buglist.cgi?list_id=5216669;resolution=fixed;query_format=advanced;bug_status=resolved;bug_status=verified;target_milestone=3.14.1;product=nss compatability nss 3.14.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.14.4 release notes
nss 3.14.4 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_4_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.14.4.
NSS 3.14.5 release notes
nss 3.14.5 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_5_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.14.5.
NSS 3.15.1 release notes
note the following limitations.
NSS 3.15.3.1 release notes
nss 3.15.3.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_3_1_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.3.1.
NSS 3.15.3 release notes
nss 3.15.3 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_3_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.3.
NSS 3.15.4 release notes
nss 3.15.4 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_4_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.4.
NSS 3.16.2.1 release notes
nss 3.16.2.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_1_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.16.2.1.
NSS 3.16.4 release notes
notable changes in nss 3.16.4 the following 1024-bit root ca certificate was restored to allow more time to develop a better transition strategy for affected sites.
NSS 3.16.5 release notes
nss 3.16.5 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_5_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.16.5.
NSS 3.17.1 release notes
nss 3.17.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_1_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.17.1.
NSS 3.19.2.4 release notes
security fixes in nss 3.19.2.4 the following security fixes from nss 3.21 have been backported to nss 3.19.2.4: bug 1185033 / cve-2016-1979 - use-after-free during processing of der encoded keys in nss bug 1209546 / cve-2016-1978 - use-after-free in nss during ssl connections in low memory bug 1190248 / cve-2016-1938 - errors in mp_div and mp_exptmod cryptographic functions in nss compatibility nss 3.19.2.4 shared libraries are back...
NSS 3.20 release notes
support for the following ciphersuites has been added: tls_dhe_dss_with_aes_128_gcm_sha256 tls_dhe_dss_with_aes_128_cbc_sha256 tls_dhe_dss_with_aes_256_cbc_sha256 by default, the server side tls implementation will use dhe parameters with a size of 2048 bits when using dhe ciphersuites.
NSS 3.22 release notes
in ssl.h ssl_peersignedcerttimestamps - get signed_certificate_timestamp tls extension data ssl_setsignedcerttimestamps - set signed_certificate_timestamp tls extension data new types in secoidt.h the following are added to secoidtag: sec_oid_aes_128_gcm sec_oid_aes_192_gcm sec_oid_aes_256_gcm sec_oid_idea_cbc sec_oid_rc2_40_cbc sec_oid_des_40_cbc sec_oid_rc4_40 sec_oid_rc4_56 sec_oid_null_cipher sec_oid_hmac_md5 sec_oid_tls_rsa sec_oid_tls_dhe_rsa sec_oid_tls_dhe_dss sec_oid_tls_dh_rsa sec_oid_tls_dh_dss sec_oid_tls_dh...
NSS 3.24 release notes
deprecate the following functions.
NSS 3.25.1 release notes
bugs fixed in nss 3.25.1 the following bug has been fixed in nss 3.25.1: ignore md5 signature algorithms in certificate requests compatibility nss 3.25.1 shared libraries are backwards compatible with all older nss 3.x shared libraries.
NSS 3.26.2 release notes
bugs fixed in nss 3.26.2 the following bug has been fixed in nss 3.26.2: ignore md5 signature algorithms in certificate requests compatibility nss 3.26.2 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.26 release notes
tm/src/ new in nss 3.26 new functionality the selfserv test utility has been enhanced to support alpn (http/1.1) and 0-rtt added support for the system-wide crypto policy available on fedora linux, see http://fedoraproject.org/wiki/changes/cryptopolicy introduced build flag nss_disable_libpkix which allows compilation of nss without the libpkix library notable changes in nss 3.26 the following ca certificate was added cn = isrg root x1 sha-256 fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 npn is disabled, and alpn is enabled by default the nss test suite now completes with the experimental tls 1.3 code enabled several test improvements and additions, including a nist known answer test bug...
NSS 3.27.1 release notes
bugs fixed in nss 3.27.1 the following bug has been fixed in nss 3.27.1: re-disable tls 1.3 by default compatibility nss 3.27.1 shared libraries are backwards compatible with all older nss 3.x shared libraries.
NSS 3.27.2 Release Notes
bugs fixed in nss 3.27.2 the following bug has been fixed in nss 3.27.2: bug 1318561 - ssl_settrustanchors leaks compatibility nss 3.27.2 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.27 release notes
the following ca certificates were removed cn = igc/a, o = pm/sgdn, ou = dcssi sha256 fingerprint: b9:be:a7:86:0a:96:2e:a3:61:1d:ab:97:ab:6d:a3:e2:1c:10:68:b9:7d:55:57:5e:d0:e1:12:79:c1:1c:89:32 cn = juur-sk, o = as sertifitseerimiskeskus sha256 fingerprint: ec:c3:e9:c3:40:75:03:be:e0:91:aa:95:2f:41:34:8f:f8:8b:aa:86:3b:22:64:be:fa:c8:07:90:15:74:e9:39 cn = ebg...
NSS 3.34.1 release notes
nss 3.34.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_34_1_rtm/src/ notable changes in nss 3.34.1 the following ca certificate was re-added.
NSS 3.37 release notes
the following ca certificates were removed: cn = s-trust universal root ca sha-256 fingerprint: d8:0f:ef:91:0a:e3:f1:04:72:3b:04:5c:ec:2d:01:9f:44:1c:e6:21:3a:df:15:67:91:e7:0c:17:90:11:0a:31 cn = tc trustcenter class 3 ca ii sha-256 fingerprint: 8d:a0:84:fc:f9:9c:e0:77:22:f8:9b:32:05:93:98:06:fa:5c:b8:11:e1:c8:13:f6:a1:08:c7:d3:36:b3:40:8e cn = tÜrktrust elek...
NSS 3.40 release notes
the following ca certificates were removed: cn = visa ecommerce root sha-256 fingerprint: 69fac9bd55fb0ac78d53bbee5cf1d597989fd0aaab20a25151bdf1733ee7d122 bugs fixed in nss 3.40 bug 1478698 - ffdhe key exchange sometimes fails with decryption failure this bugzilla query returns all the bugs fixed in nss 3.40: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&clas...
NSS 3.42 release notes
new in nss 3.42 new functionality bug 818686 - support xdg basedir specification new functions none notable changes in nss 3.42 the following ca certificates were added: none the following ca certificates were removed: none added support for some of the testcases from the wycheproof project: bug 1508666 - added aes-gcm test cases bug 1508673 - added chacha20-poly1305 test cases bug 1514999 - added the curve25519 test cases thanks to jonas ...
NSS 3.45 release notes
certificate authority changes the following ca certificates were removed: bug 1552374 - cn = certinomis - root ca sha-256 fingerprint: 2a99f5bc1174b73cbb1d620884e01c34e51ccb3978da125f0e33268883bf4158 bugs fixed in nss 3.45 bug 1540541 - don't unnecessarily strip leading 0's from key material during pkcs11 import (cve-2019-11719) bug 1515342 - more thorough input checking (cve-2019-11729) bug 155220...
NSS 3.46 release notes
notable changes in nss 3.46 certificate authority changes the following ca certificates were removed: bug 1574670 - remove expired class 2 primary root certificate sha-256 fingerprint: 0f993c8aef97baaf5687140ed59ad1821bb4afacf0aa9a58b5d57a338a3afbcb bug 1574670 - remove expired utn-userfirst-client root certificate sha-256 fingerprint: 43f257412d440d627476974f877da8f1fc2444565a367ae60eddc27a412531ae bug 1574670 - re...
NSS 3.48 release notes
certificate authority changes the following ca certificates were added: bug 1591178 - entrust root certification authority - g4 cert sha-256 fingerprint: db3517d1f6732a2d5ab97c533ec70779ee3270a62fb4ac4238372460e6f01e88 upcoming changes in nss 3.49 the legacy dbm database, libnssdbm, will no longer be built by default.
NSS Config Options
flags: turn on the following flags: ssl-lock: turn off the ability for applications to change policy with the ssl_setcipherpolicy (or ssl_setpolicy).
NSS Sample Code Sample1
this program shows the following: rsa key pair generation naming rsa key pairs looking up a previously generated key pair by name creating aes and mac keys (or encryption and mac keys in general) wrapping symmetric keys using your own rsa key pair so that they can be stored on disk or in a database.
NSS Sample Code Utilities_1
this code shows the following: extract seed from noise file read der encoding from a file extract the password from a text file get the module password print as ascii or hexadecimal sample code #include <prlog.h> #include <termios.h> #include <base64.h> #include <unistd.h> #include <sys/stat.h> #include <prprf.h> #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications.
Utilities for nss samples
it shows the following: read der from a file.
nss tech note3
the following table shows the oids recognized in the extended key usage extension, and how they map to cert types and key usages for ca and non-ca certs.
nss tech note8
every ssl socket has two function pointers, ss->sec.cache and ss->sec.uncache, which have the following types: typedef void (*sslsessionidcachefunc) (sslsessionid *sid); typedef void (*sslsessioniduncachefunc)(sslsessionid *sid); there are two separate implementations of each function, one for clients and one for servers.
Notes on TLS - SSL 3.0 Intolerant Servers
servers currently known to exhibit this intolerant behavior as of this writing, this problem has been reported for the following servers: (wherever there is an upgraded version which fixes the problem, it is indicated by an asterisked remark in the parentheses.
Build instructions
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).
FC_GetInfo
on return, the ck_info structure that pinfo points to has the following information: cryptokiversion: pkcs #11 interface version number implemented by the pkcs #11 library.
FC_GetSessionInfo
otherwise, it fills in the ck_session_info structure with the following information: state: the state of the session, i.e., no role is assumed, the user role is assumed, or the crypto officer role is assumed flags: bit flags that define the type of session ckf_rw_session (0x00000002): true if the session is read/write; false if the session is read-only.
FC_GetTokenInfo
on return, the ck_token_info structure that pinfo points to has the following information: label: the label of the token, assigned during token initialization, padded with spaces to 32 bytes and not null-terminated.
FC_InitPIN
return value fc_initpin() returns the following return codes.
FC_Login
return value fc_login() returns the following return codes.
FC_OpenSession
syntax ck_rv fc_opensession( ck_slot_id slotid, ck_flags flags, ck_void_ptr papplication, ck_notify notify, ck_session_handle_ptr phsession ); parameters fc_opensession has the following parameters: slotid [in] the id of the token's slot.
NSC_Login
return value nsc_login() returns the following return codes.
NSPR functions
the following nspr functions allow you to create your own nspr i/o layer and manipulate it.
NSS Key Functions
syntax include <key.h> include <keyt.h> void seckey_destroyprivatekey(seckeyprivatekey *key); parameter this function has the following parameter: key a pointer to the private key structure to destroy.
NSS cryptographic module
the following sections document the data types and functions.
NSS functions
vealurl mxr 3.2 and later ssl_securitystatus mxr 3.2 and later ssl_setmaxservercachelocks mxr 3.4 and later ssl_setpkcs11pinarg mxr 3.2 and later ssl_setsockpeerid mxr 3.2 and later ssl_seturl mxr 3.2 and later ssl_shutdownserversessionidcache mxr 3.7.4 and later deprecated ssl functions the following ssl functions have been replaced with newer versions.
NSS tools : cmsutil
to run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section.
sslkey.html
syntax #include <key.h> #include <keyt.h> void seckey_destroyprivatekey(seckeyprivatekey *key); parameter this function has the following parameter: key a pointer to the private key structure to destroy.
NSS Tools cmsutil
syntax to run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section.
certutil
the contexts are the following: o c (as an ssl client) o v (as an ssl server) o s (as an email signer) o r (as an email recipient) o o (as an ocsp status responder) o j (as an object signer) -v valid-months set the number of months a new certificate will be valid.
NSS tools : cmsutil
MozillaProjectsNSStoolscmsutil
to run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section.
Installing Pork
hg clone http://hg.mozilla.org/rewriting-and-analysis/pork/ cd pork hg clone http://hg.mozilla.org/rewriting-and-analysis/elsa ./configure make building mozilla with mcpp to build mozilla with mcpp to generate annotated .ii files, use the following configure command: ac_cv_visibility_hidden=no cc="gcc34 -save-temps -wp,-w0,-k" cxx="g++ -save-temps -wp,-w0,-k" cppflags=-dns_disable_literal_template $srcdir/configure --enable-debug --disable-optimize --disable-accessibility --enable-application=browser --disable-crashreporter building will probably require disabling warnings_as_errors: make warnings_as_errors= "-wp,-w0,-k" are options t...
Pork Tools
then nuke the declaration // nsresult rv; // move outparam to lhs var = getter(); // detect ns_ensure_success immediately following // and change it to an equivalent ns_ensure_true ns_ensure_true(var, ns_error_failure); // case 2 var = getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = getter(); ns_ensure_true(var, ns_error_failure) } outparamdel also support rewriting getters such that they return already_addrefed<nsifoo>.
Rhino downloads archive
if you are looking for js.jar for xslt or for ibm's bean scripting framework (bsf), please read the following note and then download one of the zip files above and unzip it.
Tutorial: Embedding Rhino
f("my args") = my arg using javascript variables to print out the value of x, we add the following code: object x = scope.get("x", scope); if (x == scriptable.not_found) { system.out.println("x is not defined."); } else { system.out.println("x = " + context.tostring(x)); } calling javascript functions to get the function f, call it, and print the result, we add this code: object fobj = scope.get("f", scope); if (!(fobj instanceof function)) { system.out.println("f is undefined...
Small Footprint
to build such minimalist jar without debug information, run the following command from the top directory of rhino distribution: ant clean ant -ddebug=off -dno-regexp=true -dno-e4x=true smalljar if you omit -dno-regexp=true, then the resulting smalljs.jar will include regular expression support.
Rhino overview
when javascript code attempts a restricted action, the security domain can be retrieved in the following manner.
The JavaScript Runtime
these types are implemented with the following java types and values: javascript fundamental type java type undefined a singleton object defined by context.getundefinedtype() null null boolean java.lang.boolean number java.lang.number, that is, any of java.lang.byte, java.lang.short, java.lang.integer, java.lang.float, or java.lang.double.
Rhino scopes and contexts
for a more concrete example, let's consider the following script: var g = 7; function f(a) { var v = 8; x = v + a; } f(6); we have a top-level variable g, and the call to f will create a new top-level variable x.
Rhino serialization
if you are using rhino serialization in an environment where you always define, say, a constructor foo, you should add the following code before calling writeobject: out.addexcludedname("foo"); out.addexcludedname("foo.prototype"); this code will prevent foo and foo.prototype from being serialized and will cause references to foo or foo.prototype to be resolved to the objects in the new scope upon deserialization.
Statistics API
the following adds an observer using the jetpack framework.
Property cache
entry value words for the .vword member of a non-adding property cache entry, one of the following is true: vword.isshape() vword.toshape() points to the js::shape that describes the property in question.
JSAPI Cookbook
getpropfunc, null, jsprop_shared | jsprop_native_accessors | jsprop_enumerate)) { return false; } working with the prototype chain defining a native read-only property on the string.prototype // javascript object.defineproperty(string.prototype, "md5sum", {get: getmd5func, enumerable: true}); the following trick couldn't work if someone has replaced the global string object with something.
JSAPI User Guide
*/ js_clearpendingexception(cx); return false; more sample code the following examples illustrate how to achieve a few different effects using the jsapi.
INT_FITS_IN_JSVAL
example the following code snippet illustrates how a c variable, item, is conditionally tested in an if statement to see if it is a legal jsval integer value.
JS::PersistentRooted
persistentrooted<jsid> persistentrootedid; typedef persistentrooted<jsobject*> persistentrootedobject; typedef persistentrooted<jsscript*> persistentrootedscript; typedef persistentrooted<jsstring*> persistentrootedstring; typedef persistentrooted<js::symbol*> persistentrootedsymbol; // added in spidermonkey 38 typedef persistentrooted<value> persistentrootedvalue; } example following example allocates persistentrootedvalue, and provides two functions for setting and getting it from javascript.
JSCheckAccessOp
jsclass hooks jsclass offers the following hook: the jsclass.checkaccess callback is called when a script attempts to access an object property.
JSConstDoubleSpec
obsolete since jsapi 35 currently these can be 0 or more of the following values or'd: jsprop_enumerate: property is visible in for loops.
JSConvertOp
jsclass hooks jsclass offers the following hook: the jsclass.convert callback implements the [[defaultvalue]] behavior for objects having that class.
JSDeletePropertyOp
jsclass hooks jsclass offers the following hook: jsclass.delproperty is called during most property deletions, even when obj has no property named id.
JSEnumerateOp
jsclass hooks jsclass offers following hook: the jsclass.enumerate hook is for classes that implement lazy properties using jsclass.resolve.
JSErrorReport
flags unsigned the logical or of zero or more of the following flags: jsreport_warning this "error" is really only a warning.
JSFastNative
description the callback should use the following macros to access the fields of vp: macro name description js_callee(cx, vp) returns the function object that was called, as a jsval.
JSFinalizeOp
jsclass hooks jsclass offers the following hook: the jsclass.finalize callback is a hook for destructor code.
JSGetObjectOps
jsclass hooks jsclass offerd following hook: the jsclass.getobjectops hook is called each time an object is created.
JSHasInstanceOp
jsclass hooks jsclass offers the following hook: the jsclass.hasinstance callback implements js_hasinstance and the javascript instanceof keyword.
JSMarkOp
jsclass hooks jsclass offers the following hook: the javascript engine calls the jsclass.mark callback during the mark phase of garbage collection.
JSNewResolveOp
flags the flags argument is the logical or of zero or more of the following flags.
JSObject
objects are made up of the following parts: most objects have a prototype.
JSObjectOps.dropProperty
description the following contract governs jsobjectops callers and implementations: whenever jsobjectops.lookupproperty returns a jsproperty pointer, the property is locked.
JSPropertyOp
jsclass hooks jsclass offers following hooks: jspropertyop jsclass.addproperty is called just after a new property is added to an object.
JSReserveSlotsOp
jsclass hooks jsclass offers the following hook: the jsclass.reserveslots callback is called each time a new object is created.
JSResolveOp
jsclass hooks jsclass offers the following hook: jsclass.resolve callback is called when a property is not found on an object.
JSTraceOp
jsclass hooks jsclass offers the following hook: the jsclass.trace callback is called to enumerate all traceable things reachable.
JSVAL_IS_DOUBLE
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js double data type.
JSVAL_IS_INT
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer data type.
JSVAL_IS_NULL
(note: jsval_is_object(jsval_null) is also true.) example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it contains a null value.
JSVAL_IS_NUMBER
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer or double value.
JSVAL_IS_STRING
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a string.
JSVAL_IS_VOID
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is void.
JSVersion
description the jsversion enumerated type includes the following values.
JSXDRObjectOp
jsclass hooks jsclass offers the following hook: jsxdr calls the jsclass.xdrobject callback to serialize and deserialize objects.
JS_CheckAccess
it is one of the following values: value description jsacc_proto check for permission to read to obj's prototype.
JS_ContextIterator
example the following code snippet illustrates how to cycle through the contexts for a given runtime: jscontext *acx; jscontext *iterp = null; int i = 0; while ((acx = js_contextiterator(rt, &iterp)) != null) { printf("%d ", ++i); } see also mxr id search for js_contextiterator ...
JS_ConvertArguments
format can contain one or more instances of the following characters, as appropriate: character c type description b bool boolean c uint16_t ecma uint16_t, unicode character i int32_t ecma int32_t j int32_t ecma int32_t (used to be different, behaves like i now) obsolete since jsapi 28 u uint32_t ecma uint32_t d double ieee double i doub...
JS_DeleteProperty
then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then obj's jsclass.delproperty hook is called.
JS_DeleteProperty2
then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded).
JS_DumpHeap
jstrace_outofline = 0x07, // the following kinds do not have an exposed c++ idiom.
JS_GetInstancePrivate
obsolete since jsapi 32 this must be one of the following: an argv pointer created by the javascript engine and passed to a jsnative callback; js_argv(cx, vp) where vp is a pointer created by the engine and passed to a jsfastnative callback; or null.
JS_GetProperty
if the lookup proceeds without error, exactly one of the following cases applies: if the property is not found, then *vp is set to undefined.
JS_GetTypeName
the following table lists jstypes and the string literals reported by js_gettypename: type literal jstype_void "undefined" jstype_object "object" jstype_function "function" jstype_string "string" jstype_number "number" jstype_boolean "boolean" any other value null see also js_convertvalue js_typeofvalue js_va...
JS_IsConstructing_PossiblyWithGivenThisObject
in such cases, the following example would provide the additional information of whether a special this was supplied.
JS_LookupProperty
otherwise, flags must be the logical or of one or more of the following bits: jsresolve_qualified behave as though the property name appeared to the right of a dot, as in alert(obj.name).
JS_SameValue
the samevalue algorithm is equivalent to the following javascript: function samevalue(v1, v2) { if (v1 === 0 && v2 === 0) return 1 / v1 === 1 / v2; if (v1 !== v1 && v2 !== v2) return true; return v1 === v2; } syntax // added in spidermonkey 45 bool js_samevalue(jscontext *cx, js::handle<js::value> v1, js::handle<js::value> v2, bool *same); // obsolete since jsapi 39 bool js_samevalue(jscontext *cx, jsval v1, jsval v2, bool *same); name type des...
JS_SetOptions
to turn individual options on or off, use js_setoptions with js_getoptions: // turn on warnings for dubious practices js_setoptions(cx, js_getoptions(cx) | jsoption_extra_warnings); // turn off those extra warnings js_setoptions(cx, js_getoptions(cx) & ~jsoption_extra_warnings); the options parameter and the return value are the logical or of zero or more constants from the following table: option description jsoption_extra_warnings warn on dubious practice.
JS_SetPropertyAttributes
it is the bitwise or of zero or more of the following values: flag purpose jsprop_enumerate property is visible in for and in loops.
JS_StringToVersion
js_stringtoversion may return any of the following values: string enumeration "1.0" jsversion_1_0 obsolete since jsapi 24 "1.1" jsversion_1_1 obsolete since jsapi 24 "1.2" jsversion_1_2 obsolete since jsapi 24 "1.3" jsversion_1_3 obsolete since jsapi 24 "1.4" jsversion_1_4 obsolete since jsapi 24 "ecmav3" jsversion_ecma_3 "1.5" jsversion_1_5 obsolete since jsapi 24 "1.6" jsversion_...
JS_ValueToNumber
js_valuetonumber carries out the following steps to convert it to a number.
JS_VersionToString
js_versiontostring may return any of the following values: enumeration string jsversion_1_0 "1.0" obsolete since jsapi 24 jsversion_1_1 "1.1" obsolete since jsapi 24 jsversion_1_2 "1.2" obsolete since jsapi 24 jsversion_1_3 "1.3" obsolete since jsapi 24 jsversion_1_4 "1.4" obsolete since jsapi 24 jsversion_ecma_3 "ecmav3" jsversion_1_5 "1.5" obsolete since jsapi 24 jsversion_1_6...
jsint
uintn; // following types are still provides in js/public/legacyinttypes.h, // but should not use them.
JSDBGAPI
js_connectshark js_disconnectshark js_startchudremote js_stopchudremote the following jsnative functions can be used to expose the above four apis to scripts.
SpiderMonkey 31
the following features in earlier versions of spidermonkey have been dropped.
SpiderMonkey 38
the following features in earlier versions of spidermonkey have been dropped.
Running Automated JavaScript Tests
running jstest in a browser jstests also runs on browser, with the following command: ./mach jstestbrowser to run specific test, you can use --filter=pattern command-line argument, where pattern is a regexp pattern that is tested against file:///{path_to_obj_dir}/dist/test-stage/jsreftest/tests/jsreftest.html?test={relative_path_to_test_from_js/src/tests} string: ./mach jstestbrowser --filter=pattern running jstests on treeherder when viewing treeherder after a pus...
SavedFrame
including and excluding chrome frames consider the following savedframe stack.
Setting up CDT to work on SpiderMonkey
step 2 - installing eclipse and setting up the project the following run-down is a condensed and updated version of what is explained in much more detail for the entire mozilla codebase.
Thread Sanitizer
adjusting the build configuration create the build configuration file .mozconfig with the following content in your mozilla-central directory: mk_add_options moz_objdir=@topsrcdir@/objdir-ff-tsan mk_add_options moz_make_flags=-j12 # enable llvm specific code and build workarounds ac_add_options --enable-thread-sanitizer # if clang is already in your $path, then these can simply be: # export cc=clang # export cxx=clang++ export cc="/path/to/clang" export cxx="/path/to/clang++" # llvm-symb...
Zest runtimes
the following runtimes are available: java https://github.com/mozilla/zest - this is the reference implementation the following runtimes are planned or an an early stage of implementation: https://github.com/mozilla/zest/tree/master/js javascript https://github.com/darkowlzz/zest-runner https://github.com/darkowlzz/zest-cli - this is the zest-cli of js based runner.
Zest tools
the following tools currently support zest: owasp zed attack proxy the zap add-on allows the user to create, edit and run zest scripts.
Exploitable crashes
next steps once you've determined that a crash is potentially exploitable, take the following steps.
Browser security
secure development guidelinesthe following content will likely see significant revision, though can be used as a reference for security best practices to follow when developing code for mozilla.security and the jar protocolthis article discusses security concerns with the jar: protocol, which only firefox has ever implemented for web content.
Setting up an update server
if you've built your own mar, you can obtain its sha512 checksum by running the following command, which should work in linux, macos, or windows in the mozillabuild environment: shasum --algorithm 512 <filename> on windows, you can get the exact file size in bytes for your mar by right clicking on it in the file explorer and selecting properties.
Signing Mozilla apps for Mac OS X
once you have that you can do the following to create your id: open the developer certificate utility.
ROLE_TABLE
also refer to the following roles: role_columnheader, role_rowheader, role_column, role_row, role_cell.
The Places database
periodically at runtime, the following happens to expire pages: expire visits that are older than the history expiration threshold.
The Publicity Stream API
this spawns a doorhanger which allows the user to specify which users can view the activity, and (following successful login and authorization with the stream server) registers the activity in a stream at [address].
Toolkit API
xtension packaging: specific information about how to package extensions theme packaging: specific information about how to package themes multiple-item extension packaging: specific information about multiple-item extension xpis xul application packaging: specific information about how to package xulrunner applications chrome registration printing in xul apps see also the following developer pages contain examples and discussions of particular topics: xul xul overlays developing extensions xulrunner developing themes dom rdf storage ...
XML Extras
if you'd like to help out with qa, you can do one of the following: sign up as the qa owner for any of the implemented components.
Creating a Python XPCOM component
for example: % cd c:\mozilla\bin\python\xpcom % python xpt.py nsisample class nsisample: _com_interfaces_ = xpcom.components.interfaces.nsisample # if this object needs to be registered, the following 2 are also needed.
How to build an XPCOM component in JavaScript
"); then implement your interface the same way you did above, except with a few modifications so that xpcomutils can set it up properly: /*********************************************************** class definition ***********************************************************/ //class constructor function helloworld() { // if you only need to access your component from javascript, uncomment the following line: //this.wrappedjsobject = this; } // class definition helloworld.prototype = { // properties required for xpcom registration: classdescription: "my hello world javascript xpcom component", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@dietrich.ganx4.com/helloworld;1", // [optional] custom factory (an object implementing nsifactory...
Using XPCOM Components
in the following code fragment from the cookie manager dialog in mozilla, you can see a singleton of the cookiemanager component being created with the getservice() method and used to provide the functionality that lets users load and remove cookies from the user interface.
Creating XPCOM components
preface who should read this book organization of the tutorial following along with the examples conventions acknowledgements an overview of xpcom the xpcom solution gecko components interfaces interfaces and encapsulation the nsisupports base interface xpcom identifiers cid contract id factories xpidl and type libraries xpcom services xpcom types method types reference counting status codes variable mappings commo...
Detailed XPCOM hashtable guide
they provide the following features: hashtable operations can be completed without using an entry class, making code easier to read; optional thread-safety: the hashtable can manage a read-write lock around the table; predefined key classes provide automatic cleanup of strings/interfaces nsinterfacehashtable and nsclasshashtable automatically release/delete objects to avoid leaks.
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
the following stream types are known to implement nsiseekablestream: nsstorageinputstream nsstringinputstream nsmultiplexinputstream nspipeinputstream nsfileinputstream nsbufferedinputstream nsfileoutputstream nsbufferedoutputstream complex stream types several stream types leverage primitive stream types to do specialized work.
How to build a binary XPCOM component using Visual Studio
then make the following tweaks: add "..\gecko-sdk\include" to additional include directories add "..\gecko-sdk\lib" to additional library directories add "nspr4.lib xpcom.lib xpcomglue_s.lib" to additional dependencies add "xp_win;xp_win32″ to preprocessor definitions turn off precompiled headers (just to keep it simple) use a custom build step for the xpcom idl file (spawns xpidl-build.bat to process the idl w...
Components.Constructor
it is equivalent to the following javascript function: function components_constructor(contractid, interfacename, initializer) { var ccargs = arguments; function ctor() { var instance = components.classes[contractid] .createinstance(components.interfaces.nsisupports); if (ccargs.length > 1) { instance.queryinterface(components.interfaces[interfacename]); if (ccargs.le...
Components.interfaces
for example, assume we have the following interface declaration: interface nsifoo : nsisupports { const pruint32 myflag = 5; }; the constant myflag can then be accessed using var myflag = components.interfaces.nsifoo.myflag; ...
Components.lastResult
example in the following example, the local variable i contains the actual result returned by bar() (assuming that bar() is called via xpconnect), and components.lastresult contains the success code returned by bar().
Components.utils.cloneInto
options : object this optional parameter is an object with the following optional properties: clonefunctions: a boolean value that determines if functions should be cloned.
Components.utils.exportFunction
the following options are currently defined: defineas: determines the name of the function in targetscope.
Components.utils.importGlobalProperties
the following strings are supported: string/object xpcom component atob blob btoa crypto css fetch file nsidomfile indexeddb nodefilter firefox 60 nsidomnodefilter obsolete since gecko 60 rtcidentityprovider textdecoder textencoder...
Components.utils
the object currently has the following members: editors!
Components.utils.unload
example you can unload a module called mymodule.jsm using the following line of code: components.utils.unload("resource://myaddon/modules/mymodule.jsm"); note: currently components.utils.unload clears the global object of an unloaded module.
Components object
the components object has the following members: classes array of classes by contractid classesbyid array of classes by cid constructor constructor for constructor of components exception constructor for xpconnect exceptions id constructor for xpcom nsids interfaces array of interfaces by interface name interfacesbyid array of interfaces by iid issuccesscode function to d...
Language bindings
the following bridging layers are currently available: components objectthe components object is the object through which xpconnect functionality is reflected into javascript.
Observer Notifications
observer topics the following are topics that you can observe during the course of an application.
nsresult
because nsresult is strongly typed, code like the following will result in an error at compile time: bool foo() { ...
NS_OVERRIDE
a compiler with static-checking enabled will issue the following error: test.cpp:8: error: ns_override function b::getfoo(nsifoo**) does not override a base class method with the same name and signature.
RefPtr
xxx it's not clear that the details in the following paragraph are correct.
amIInstallTrigger
the value of the property should either be a string url, or an object with the following properties: url for the add-on's url iconurl for an icon for the add-on hash for a hash of the add-on.
imgICache
use the following snippet to obtain a relevant image cache for a given document or channel (where relevantdocument is a document object that contains images you care about, or relevantchannel is an nsichannel that is used for fetching images): var tools = components.classes["@mozilla.org/image/tools;1"].getservice(components.interfaces.imgitools); var cache = tools.getimgcachefordocument(relevantdocument); // alternatively, tools.getimgcacheforchannel(relevantchann...
mozIStorageAggregateFunction
sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection.
mozIStorageFunction
sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection.
nsIAccessibleRole
also refer to the following roles: role_columnheader, role_rowheader, role_column, role_row, role_cell.
nsIAlertsService
example simple usage the following code was used to display the above notification.
nsIChannel
once onstartrequest is called, all following method calls on alistener will get the request that was passed to onstartrequest.
nsIContentViewer
if it is non-null, the document will not be destroyed, and the following actions will happen when destroy() is called: sanitize() will be called on the viewer's document the content viewer will set the contentviewer property on the history entry, and release its reference (ownership reversal).
nsICookieService
var cookiesvc = components.classes["@mozilla.org/cookieservice;1"] .getservice(components.interfaces.nsicookieservice); notifications this service broadcasts the following notifications when the cookie list is changed, or a cookie is rejected: topic subject data cookie-changed broadcast whenever the cookie list changes in some way.
nsICryptoHash
the following example shows how to compute the sha256 hash of a file: // hardcoded here for convenience var path = "c:\\windows\\notepad.exe"; var f = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); f.initwithpath(path); var istream = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(com...
nsIDOMSimpleGestureEvent
the following events are generated: mozswipegesture - generated when the user completes a swipe across across the input device.
nsIDOMWindowUtils
uerycontentevent( in unsigned long atype, in unsigned long aoffset, in unsigned long alength, in long ax, in long ay, in unsigned long aadditionalflags optional ); nsiquerycontenteventresult sendquerycontentevent( in unsigned long atype, in unsigned long aoffset, in unsigned long alength, in long ax, in long ay ); obsolete since gecko 31.0 parameters atype on of the following const values.
nsIDownloadManager
exceptions thrown ns_error_failure if the download is not in the following states: download_canceled or download_failed.
nsIDragService
this was changed in gecko 43, see the following section.
nsIFeedResult
this value will be one of the following: atom, rss2, rss09, rss091, rss091userland, rss092, rss1, atom03, atomentry, rssitem methods registerextensionprefix() registers a prefix for a namespace used to access an extension in the feed or entry.
nsIFileInputStream
(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.
nsIFileOutputStream
the deferred open will be performed when one of the following is called: seek() tell() write() flush() 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.
nsIFrameMessageListener
called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name the name of the message.
nsIINIParserFactory
example obtaining a parser object to obtain a parser for an ini file, you can use code that looks like this: to get an nsiiniparser instance for an ini file, you may use the following code: // create an nsilocalfile var cl = "@mozilla.org/file/local;1"; var interf = components.interfaces.nsilocalfile; var file = components.classes[cl].createinstance(interf); // init the file with the path to your ini file var path = "c:\\temp\\example.ini"; file.initwithpath(path); // create the nsiiniparserfactory var cl = "@mozilla.org/xpcom/ini-parser-factory;1"; var interf = components.i...
nsIJSID
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the following methods return objects that implement this interface: components.interfaces.name components.classes[contract] components.interfacesbyid[uuid] components.classesbyid[cid] the first two cases create a named jsid while the last two cases create an unnamed jsid.
nsIJetpack
the first argument passed to it is the name of the message, and all arguments following it are either json-serializable types or handles.
nsILocalFile
a bitwise combination of the following open flags: pr_rdonly open for reading only.
nsIMemoryReporter
unit type constants requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) the amount reported by a memory reporter may use one of the following units.
nsIMessageListener
the received message is an object with the following properties: target the target of the message.
nsIMsgCompFields
ool emailaddressonly ); void convertbodytoplaintext ( ); attachment handling methods void addattachment ( in nsimsgattachment attachment ); void removeattachment ( in nsimsgattachment attachment ); void removeattachments ( ); header methods void setheader(char* name, char* value); references this interface is the type of the following properties: nsimsgcompose.compfields, nsimsgcomposeparams.composefields this interface is passed as an argument to the following methods: nsimsgcomposesecure.begincryptoencapsulation, nsimsgcomposesecure.requirescryptoencapsulation, nsimsgsend.createandsendmessage, nsimsgsend.sendmessagefile, nsismimejshelper.getnocertaddresses, nsismimejshelper.getrecipientcertsinfo ...
nsIObserver
example the following code is an implementation of nsiobserver that is registered to receive notifications for the "mytopicid" topic.
nsIParserUtils
in that case, <a> links (and similar) to other content are preserved, so an explicit user action (following a link) after the content has been loaded can still leak information.
nsIPermissionManager
remarks this service broadcasts the following notification when the permission list is changed: topic : "perm-changed" (perm_change_notification) broadcast whenever the permission list changes in some way.
nsIPluginHost
the result will be in the following format.
Component; nsIPrefBranch
on preference changes, the following arguments will be passed to nsiobserver.observe(): asubject - the nsiprefbranch object (this).
nsIPrefBranch2
on preference changes, the following arguments will be passed to nsiobserver.observe(): asubject - the nsiprefbranch object (this).
nsIPushSubscription
the following key names are supported: p256dh the ecdh public key, used as the input keying material in the hkdf invocation during encryption.
nsISHEntry
if either contentviewer or windowstate are null, then all of the following members are cleared/reset: contentviewer, sticky, windowstate, viewerbounds, childshells, refreshurilist.
nsISHistory
to access individual history entries of the enumerator, perform the following steps: call getshistoryenumerator() to obtain handle the nsisimpleenumerator object.
nsISupportsPriority
following unix conventions, smaller (and possibly negative) values have higher priority.
nsISupports proxies
the following interface is now obsolete: nsiproxyobjectmanager.
nsIToolkitProfileService
to access the service, you can use the following code: var toolkitprofileservice = components.classes["@mozilla.org/toolkit/profile-service;1"] .createinstance(components.interfaces.nsitoolkitprofileservice); prior to gecko 1.9.1 only the built-in profile manager was able to access the toolkit profile service.
nsITraceableChannel
implementing nsistreamlistener the nsistreamlistener passed to setnewlistener() should implement the following methods, which are called to notify it of events that occur on the http stream: onstartrequest: an http request is beginning.
nsIURI
inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) see the following rfcs for details: rfc3490: internationalizing domain names in applications (idna) rfc3986: uniform resource identifier (uri): generic syntax rfc3987: internationalized resource identifiers subclasses of nsiuri, such as nsiurl, impose further structure on the uri.
nsIURLFormatter
mozilla applications linking to mozilla websites are strongly encouraged to use urls of the following format: http[s]://%service%.mozilla.[com|org]/%locale%/ method overview astring formaturl(in astring aformat); astring formaturlpref(in astring apref); methods formaturl() formats a string url.
nsIVersionComparator
the service can be accessed directly via services.vc after loading services.jsm or with the following code: var versioncomparator = components.classes["@mozilla.org/xpcom/version-comparator;1"] .getservice(components.interfaces.nsiversioncomparator); method overview long compare(in acstring a, in acstring b); methods compare() compare two version strings.
nsIWebContentHandlerRegistrar
examples register a webmail service as mailto handler the following code aims to add "outlook.com live mail" to list of webservice handlers.
nsIWebNavigation
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is implemented by the following components: * @mozilla.org/browser/shistory-internal;1 * @mozilla.org/browser/shistory;1 * @mozilla.org/embedding/browser/nswebbrowser;1 * @mozilla.org/docshell;1 gecko 1.9.2 note in gecko 1.9.2 (firefox 3.6), the @mozilla.org/webshell;1 component no longer exists; you need to use @mozilla.org/docshell;1 instead.
nsIWebProgress
constants the following flags may be combined to form the anotifymask parameter for the addprogresslistener() method.
nsIWebSocketChannel
status codes the following values are permitted status codes.
nsIWinAppHelper
returns true only if all the following conditions are all true at once: the operating system is at least windows vista user account control is enabled the user is an administrator the application is not already running with elevated permissions otherwise it returns false.
nsIXULAppInfo
only the following characters are allowed: a-z a-z 0-9 - .
nsIXULTemplateQueryProcessor
for example, a query might have the following syntax: (?id, ?name, ?url) from bookmarks where parentfolder = ?start this query might generate a result for each bookmark within a given folder.
nsIZipReader
set this parameter to null (javascript) or emptycstring() (c++) to get all entries; otherwise, use the following syntax: * matches anything.
NS_IF_RELEASE
ns_if_release is exactly equivalent to the following function: inline void ns_if_release(nsisupports* foo) { if (foo) foo->release(); foo = 0; } syntax ns_if_release(foo); see also ns_addref, ns_release ...
NS_CStringContainerInit2
flag values the aflags parameter is a bit-wise combination of the following values: ns_cstring_container_init_depend data passed into ns_cstringcontainerinit2 is not copied.
nsIAbCard/Thunderbird3
the following types are supported: base64xml xml vcard autf8string translateto(in autf8string atype); parameters atype the type of item to translate the card into.
Setting HTTP request headers
while the previous version we showed before was good for learning, in an actual real-world application, you'd probably want to code it more like the following.
XPCOM Thread Synchronization
} am.wait(); pr_notifycondvar(mcvar); } new usage using namespace mozilla; concurrentmethod() { mutexautolock al(mlock); monitorautoenter am(mmonitor); if (needexpensivecomputation()) { mutexautounlock au(mlock); } am.wait(); mcvar->notify(); } mozilla synchronization api reference the mozilla:: namespace exports the following synchronization primitives.
Getting Started Guide
the following lists are good starting point, but by no means complete.
Using nsIPasswordManager
getting nsipasswordmanager to get a component implementing nsipasswordmanager, use the following: var passwordmanager = components.classes["@mozilla.org/passwordmanager;1"] .getservice(components.interfaces.nsipasswordmanager); storing a password to store a password in the password manager, you need three things: a hostname/url (you'll need this to retrieve the password again later), a username, and a password.
Working with Multiple Versions of Interfaces
out having to cut and paste) i followed the kind advice of mike shaver and did: #define nsiaccessibleretrieval nsiaccessibleretrieval_old #include "accessibility/nsiaccessibleretrieval_old.h" static const nsiid ns_iaccessibleretrieval_iid_old = ns_iaccessibleretrieval_iid; #undef nsiaccessibleretrieval #undef __gen_nsiaccessibleretrieval_h__ #include "accessibility/nsiaccessibleretrieval.h" and following the identical principle for the document interface: #define nsiaccessibledocument nsiaccessibledocument_old #include "accessibility/nsiaccessibledocument_old.h" static const nsiid ns_iaccessibledocument_iid_old = ns_iaccessibledocument_iid; #undef nsiaccessibledocument #undef __gen_nsiaccessibledocument_h__ #include "accessibility/nsiaccessibledocument.h" i even silenced my friend the compiler ...
Working with out parameters
when working with xpcom components, you might come across method declarations like the following one: [scriptable, uuid(8b5314bc-db01-11d2-96ce-0060b0fb9956)] interface nsitransferable : nsisupports { ...
XPCOM tasks
5.1 3rd party code that doesn't use any services from our tree should be below xpcom; particularly, code xpcom could exploit, e.g., expat berkeley db changes to apis, functionality, and implementations the following items are listed (very) roughly in their order of importance, i.e., fixing observers is the first thing i want to do.
already_AddRefed
// the following assignment doesn't perform an additional addref, // as it would do if getfoo() returned a raw pointer.
XPCOM
this guide provides some explanation and advice on how to choose between them.observer notificationsthe following are topics that you can observe during the course of an application.
XPIDL Syntax
MozillaTechXPIDLSyntax
the following is a list of potential features which are parseable but may not result in expected code: struct, union, and enumerated types array declarators (appears to be supported in xpidl_header.c but not xpidl_typelib.c) exception declarations module declarations variable arguments (that makes the abnf get more wonky) sequence types max-length strings fixed-point numbers "any" and "long double" t...
nsIMsgCloudFileProvider
constants the following constants are used for the status codes passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider.
Filelink Providers
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.
MailNews Protocols
those protocols all have the following, defined in the corresponding protocol subdirectory of mailnews (i.e., mailnews/imap, mailnews/local (for pop3), mailnews/news): an incoming server class, which implements nsimsgincomingserver and inherits from mailnews/base/util/nsmsgincomingserver, i.e.., nspop3incomingserver, nsimapincomingserver, nsnntpincomingserver.
Mail client architecture overview
the base module consists of the following basic building blocks account management - the account manager is the root object of the server/folder/message hierarchy.
Mailnews and Mail code review requirements
rubber-stamp approvals for intermittently failing ("orange") test fixes/debugging in order to make it easier to debug and fix tests that fail intermittently ("intermittent orange" tests), we have created the following two rubber-stamps based on this proposal on the tb-planning mailing list.
Thunderbird Configuration Files
if you don't already have one, consider running the following code in a terminal.
Building a Thunderbird extension 1: introduction
the tutorial has the following pages: introduction (this page) the extension filesystem (setting up your local system) install manifest (the install.rdf file that contains meta-information about the extension) chrome manifest (list of packages and overlays) xul (the xml user interface language that is used to modify the thunderbird user interface) adding javascript (explains how to add some simple javascript to your th...
Building a Thunderbird extension 2: extension file layout
ed in step 4 /chrome/ /content/ /content/myhelloworld.xul //created in step 5 /content/overlay.js //created in step 6 /chrome/locale/* //building an extension# localization /chrome/skin/ /defaults/preferences/ //building an extension# defaults files the following tutorial pages will explain how to write each of these files (except locale/ and defaults/) and package them into an xpi (zippy) file.
Building a Thunderbird extension 5: XUL
example xul overlay document create a new file called myhelloworld.xul within the content folder you created earlier with the following content: <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myfirstext/content/overlay.js"/><!-- a reference to your javascript file --> <statusbar id="status-bar"> <statusbarpanel id="my-panel" label="date"/> </statusbar> </overlay> the <statusbar> widget named status-bar sp...
Building a Thunderbird extension 6: Adding JavaScript
depending on the installed theme the result will look something like this: modify xul elements with javascript save the following javascript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js.
Demo Addon
all three demos are explained in the following sections.
Finding the code for a feature
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?
Activity Manager examples
showing a user-defined activity in the activity manager window the following sample will show a process and an event for junk processing in the activity manager window.
Get Thunderbird version
on thunderbird version 3.0b3pre and later, you can use the following snippet to get the thunderbird version.
Tips and Tricks from the newsgroups
the following discussions on mozilla.dev.apps.thunderbird and mozilla.dev.extensions include useful tips for thunderbird add-on developers.
customDBHeaders Preference
in addition to the preference outlined in setting up extension development environment, you'll want to add the following preferences: // this allows you to add extra headers while composing messages user_pref("mail.compose.other.header", "x-superfluous,x-other,x-whatever"); // this enables the preservation of custom headers as incoming mail is processed user_pref( "mailnews.customdbheaders", "x-superfluous,x-other"); important: please pay careful attention to the case of the mailnews.customdbheaders preference.
Thunderbird extensions
the following documentation provides help for creating extensions for the thunderbird email client.
Using the Mozilla source server
the nightly debug builds are now also source indexed so that by following a couple of simple steps you can also have the source code served to you for debugging without a local build what you'll need windbg or visual studio (note: express editions will not work, but windbg is a free download) a nightly build that was created after april 15, 2008; go to the /pub/firefox/nightly/latest-mozilla-central/ folder and grab the installer for builds predating the switch to mercurial, you'll need cvs.exe, added to your path (the cvs.exe from mozillabuild has problems, use this one instead) note: do not use the cvs from mozillabuild, it will not work!
Using the Mozilla symbol server
to use only the mozilla symbol server, add the following entry to your symbol path (note: you can replace c:\symcache\ with any writable directory on your computer, if you'd prefer a different location for downloaded symbols): srv*c:\symcache\*https://symbols.mozilla.org/ set this string as _nt_symbol_path in the environment, using the windbg menus, or by typing the .sympath command.
Declaring and Using Callbacks
consider the following code: function myjscallback(foo, bar) { ....
Declaring types
{ fieldn: typen } ] example for example, to support the c tm structure using js-ctypes, you would use the following code: const struct_tm = new ctypes.structtype("tm", [ { "tm_sec": ctypes.int }, { "tm_min": ctypes.int }, { "tm_hour": ctypes.int }, { "tm_mday": ctypes.int }, { "tm_mon": ctypes.int }, { "tm_year": ctypes.int }, { "tm...
Memory Management
keeping objects alive the following js-ctypes objects will hold references to objects, keeping them alive.
Working with data
if type is an array type of unspecified length, the following steps are taken: if the value is a size value, a new array of that length is created, with its cells ready to accept values of the same type as those in the specified array.
CData
in theory, in other words, the following javascript expression should return a copy of the original cdata object: eval(dataobject.tosource()); tostring() returns a string identifying the data.
Initialization and Destruction - Plugins
for example, the following embed element has the standard attributes src, height, and width and the private attribute loop: <embed src="movie.avi" height="100" width="100" loop="true"> with the embed element in the example, the browser passes the values in argv to the plug-in instance: argc = 4 argn = { "src", "height", "width", "loop" } argv = { "movie.avi", "100", "100", "true" } the saved parameter allows an instan...
Memory - Plugins
the npn_memalloc method has the following syntax: void *npn_memalloc (uint32 size); the size parameter is an unsigned long integer that represents the amount of memory, in bytes, to allocate in the browser's memory space.
Scripting plugins - Plugins
the new npnvariable enumerations are defined in npapi.h as: npnvwindownpobject = 15, npnvpluginelementnpobject = 16 how to call plugin native methods the following html code will do the job: <embed type="application/plugin-mimetype"> <script> var embed = document.embeds[0]; embed.nativemethod(); alert(embed.nativeproperty); embed.nativeproperty.anothernativemethod(); </script> the api extensions the api extensions are based on four new structs: npstring npvariant npn_releasevariantvalue npn_getstringidentifier npn_getstringidenti...
DOM Inspector internals - Firefox Developer Tools
its contents should resemble the following: extensions/ … jsutil/ … prefs/ … res/ … tests/ … viewers/ … browseroverlay.xul commandoverlay.xul editingoverlay.xul flasher.js hooks.js inspector.css inspector.js inspectoroverlay.xul inspector.xml inspector.xul keysetoverlay.xul object.js object.xul popupoverlay.xul sidebar.js sidebar.xul sta...
Introduction to DOM Inspector - Firefox Developer Tools
the following descriptions provide an overview of what these viewers are about: the dom nodes viewer shows attributes of nodes that can take them, or the text content of text nodes, comments, and processing instructions.
DOM Inspector - Firefox Developer Tools
or, build thunderbird yourself with the following options: ac_add_options --enable-extensions="default inspector" ac_add_options --enable-inspector-apis mozilla suite and seamonkey select tools > web development > dom inspector.
Browser Toolbox - Firefox Developer Tools
altogether you will have access to the following developer tools: debugger (note: if you want to debug a specific add-on that is restartless or sdk-based then try the add-on debugger.) console style editor performance network monitor page inspector accessibility inspector you can debug chrome: and about: pages using the normal debugger, just as if they were ordinary content pages.
Access debugging in add-ons - Firefox Developer Tools
the following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.addeventlistener("debugger:editorloaded") - called when the read-only script panel loaded.
Search - Firefox Developer Tools
for example, if i enter "load" when viewing the above list, i get the following: only the functions with load in their name are shown.
Use watchpoints - Firefox Developer Tools
in the following screenshot, the debugger pauses at line 7, where obj.a is set.
Source map errors - Firefox Developer Tools
there are a few common ways that source maps can go wrong; they are detailed in the following sections.
The Firefox JavaScript Debugger - Firefox Developer Tools
how to to find out what you can do with the debugger, refer to the following how-to guides.
Deprecated tools - Firefox Developer Tools
you may see a warning message, as in the following image, when trying to activate a deprecated panel: in addition, if you open the panel for one of these tools, you will also see a warning message about its removal.
Migrating from Firebug - Firefox Developer Tools
the following list aims to help firebug users to find their way into the developer tools.
Performance Analysis - Firefox Developer Tools
network monitor features the following articles cover different aspects of using the network monitor: toolbar network request list network request details network traffic recording throttling ...
Throttling - Firefox Developer Tools
gprs 50 kbps 20 kbps 500 regular 2g 250 kbps 50 kbps 300 good 2g 450 kbps 150 kbps 150 regular 3g 750 kbps 250 kbps 100 good 3g 1.5 mbps 750 kbps 40 regular 4g/lte 4 mbps 3 mbps 20 dsl 2 mbps 1 mbps 5 wi-fi 30 mbps 15 mbps 2 network monitor features the following articles cover different aspects of using the network monitor: toolbar network request list network request details network traffic recording performance analysis ...
Network monitor toolbar - Firefox Developer Tools
network monitor features the following articles cover different aspects of using the network monitor: network request list network request details network traffic recording performance analysis throttling ...
Network monitor recording - Firefox Developer Tools
network monitor features the following articles cover different aspects of using the network monitor: toolbar network request list network request details performance analysis throttling ...
Network Monitor - Firefox Developer Tools
ui overview the ui is divided into four main pieces: the main screen contains the toolbar, the network request list, and the network request details pane: the performance analysis view is a separate screen: working with the network monitor the following articles cover different aspects of using the network monitor: toolbar network request list network request details network traffic recording performance analysis throttling ...
CSS Flexbox Inspector: Examine Flexbox layouts - Firefox Developer Tools
in the html pane in the html pane, an element laid out with flexbox has the word flex next to it as shown in the following image: click the word flex in the html pane to keep the overlay visible when you move the mouse away from the container.
Examine and edit HTML - Firefox Developer Tools
the menu contains the following items — click on the links to find the description of each command in the context menu reference: edit as html create new node duplicate node delete node attributes add attribute copy attribute value edit attribute remove attribute break on ...
Use the Inspector API - Firefox Developer Tools
firefox add-ons may access the following objects from the chrome://browser/content/devtools/inspector/inspector.xul context: window.inspector defined in inspector-panel.js.
Page Inspector - Firefox Developer Tools
how to to find out what you can do with the inspector, see the following how to guides: open the inspector examine and edit html examine and edit the box model inspect and select colors reposition elements in the page edit fonts visualize transforms use the inspector api select an element examine and edit css examine event listeners work with animations edit css filters edit css shapes view background images use the inspector from the web console e...
Allocations - Firefox Developer Tools
it includes the following columns: self count: the number of allocation-samples that were taken in this function (also shown as a percentage of the total) self bytes: the total number of bytes allocated in the allocation-samples in this function (also shown as a percentage of the total) rows are sorted by the "self bytes" column.
Sorting algorithms comparison - Firefox Developer Tools
this program compares the performance of three different sorting algorithms: bubble sort selection sort quicksort it consists of the following functions: sortall() top-level function.
Animating CSS properties - Firefox Developer Tools
the css rendering waterfall the process the browser uses to update the page when a css property has changed can be described as a waterfall consisting of the following steps: recalculate style: every time a css property for an element changes, the browser must recalculate computed styles.
Waterfall - Firefox Developer Tools
the following operations are recorded: name and description color detailed information dom event javascript code that's executed in response to a dom event.
Extension Storage - Firefox Developer Tools
this table contains the following columns: key — the name of the stored item.
Taking screenshots - Firefox Developer Tools
the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard.
Web Console UI Tour - Firefox Developer Tools
settings ("gear" menu): new in firefox 71, you can click the gear icon to access the new settings menu, where you can toggle the following features on and off: persist logs: when enabled, the console doesn't clear on page reload, or new page load.
AbortController.AbortController() - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
AbortController.abort() - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
AbortController.signal - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
AbortController - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
AbortSignal: abort event - Web APIs
bubbles no cancelable no interface event event handler onabort examples in the following snippets, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal.aborted - Web APIs
syntax var isaborted = abortsignal.aborted; value a boolean examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal.onabort - Web APIs
}; examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
AbsoluteOrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second.
AbstractWorker.onerror - Web APIs
}; example the following code snippet shows creation of a worker object using the worker() constructor and setting up of an onerror handler on the resulting object: var myworker = new worker('worker.js'); myworker.onerror = function() { console.log('there is an error with your worker!'); } specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification.
AesCtrParams - Web APIs
the counter must be big enough that it doesn't wrap: if the message is n blocks and the counter is m bits long, then the following must be true: n <= 2m.
AesGcmParams - Web APIs
according to the web crypto specification this must have one of the following values: 32, 64, 96, 104, 112, 120, or 128.
AnalyserNode.fftSize - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
AnalyserNode.frequencyBinCount - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.getByteFrequencyData() - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.getByteTimeDomainData() - Web APIs
return value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
AnalyserNode.getFloatFrequencyData() - Web APIs
example const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); // float32array should be the same length as the frequencybincount const mydataarray = new float32array(analyser.frequencybincount); // fill the float32array with data returned from getfloatfrequencydata() analyser.getfloatfrequencydata(mydataarray); drawing a spectrum the following example shows basic usage of an audiocontext to connect a mediaelementaudiosourcenode to an analysernode.
AnalyserNode.getFloatTimeDomainData() - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
AnalyserNode.maxDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.minDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.smoothingTimeConstant - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
Animation.finished - Web APIs
examples the following code waits until all animations running on the element elem have finished, then deletes the element from the dom tree: promise.all( elem.getanimations().map( function(animation) { return animation.finished } ) ).then( function() { return elem.remove(); } ); specifications specification status comment web animationsthe definition of 'animation.f...
Animation.onremove - Web APIs
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacest...
Animation.persist() - Web APIs
WebAPIAnimationpersist
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacestate); }); here we have a <div> e...
Animation.ready - Web APIs
WebAPIAnimationready
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.replaceState - Web APIs
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacest...
AnimationEvent.initAnimationEvent() - Web APIs
the following values are allowed: value meaning animationstart the animation has started.
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
eventinitdict optional an optional eventinit dictionary object containing the following fields: bubbles optional defaults to false, of type boolean, indicating if the event bubbles or not.
ArrayBufferView - Web APIs
arraybufferview is a helper type representing any of the following javascript typedarray types: int8array, uint8array, uint8clampedarray, int16array, uint16array, int32array, uint32array, float32array, float64array or dataview.
Attr.localName - Web APIs
WebAPIAttrlocalName
example the following example shows "id" in an alert dialog.
Attr.prefix - Web APIs
WebAPIAttrprefix
syntax string = attribute.prefix examples the following logs "x" to the console.
AudioBuffer.getChannelData() - Web APIs
example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
AudioBufferSourceNode.start() - Web APIs
examples the most simple example just starts the audio buffer playing from the beginning — you don't need to specify any parameters in this case: source.start(); the following more complex example will, 1 second from now, start playing 10 seconds worth of sound starting 3 seconds into the audio buffer.
AudioContext.close() - Web APIs
example the following snippet is taken from our audiocontext states demo (see it running live.) when the stop button is clicked, close() is called.
AudioContext.createJavaScriptNode() - Web APIs
example the following script illustrates the use of createjavascriptnode(): var sinewave = function(context) { var that = this; this.x = 0; // initial sample number this.context = context; this.node = context.createjavascriptnode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } sinewave.prototype.process = function(e) { var data = e.outputbuffer.getchanneldata(0); for (var i =...
AudioContext.createMediaStreamDestination() - Web APIs
examples in the following simple example, we create a mediastreamaudiodestinationnode, an oscillatornode and a mediarecorder (the example will therefore only work in firefox and chrome at this time.) the mediarecorder is set up to record information from the mediastreamdestinationnode.
AudioContext.createMediaStreamSource() - Web APIs
music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; note: as a consequence of calling createmediastreamsource(), audio playback from the media stream will be re-routed into the processing graph of the audiocontext.
AudioContext.resume() - Web APIs
example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called.
AudioContext.suspend() - Web APIs
example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called.
AudioDestinationNode.maxChannelCount - Web APIs
example the following would set up a simple audio graph, featuring an audiodestinationnode with maxchannelcount of 2: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); audioctx.destination.maxchannelcount = 2; gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as vo...
AudioListener.dopplerFactor - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.forwardX - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.forwardY - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.forwardZ - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.positionX - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.positionY - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.positionZ - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.setOrientation() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.setPosition() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.speedOfSound - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.upX - Web APIs
WebAPIAudioListenerupX
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.upY - Web APIs
WebAPIAudioListenerupY
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener.upZ - Web APIs
WebAPIAudioListenerupZ
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioListener - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
AudioNode.channelCountMode - Web APIs
the possible values of channelcountmode and their meanings are: value description the following audionode children default to this value max the number of channels is equal to the maximum number of channels of all connections.
AudioNode.channelInterpretation - Web APIs
when the number of channels doesn't match between an input and an output, up- or down-mixing happens according the following rules.
AudioParam.setTargetAtTime() - Web APIs
for more details, check the following table on how the value changes from 0% to 100% as the time progresses.
AudioParam.value - Web APIs
WebAPIAudioParamvalue
during each render quantum, the browser does the following things related to managing the value of a parameter: if the value setter has been used, the parameter's value is changed to the value given.
AudioParam - Web APIs
an audioparam can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.
AudioParamMap - Web APIs
in addition, there are the following properties available: size ?
AudioProcessingEvent - Web APIs
example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode.
AudioScheduledSourceNode - Web APIs
methods inherits methods from its parent interface, audionode, and adds the following methods: start() schedules the node to begin playing the constant sound at the specified time.
AuthenticatorAttestationResponse.attestationObject - Web APIs
syntax attestobj = authenticatorattestationresponse.attestationobject properties after decoding the cbor encoded arraybuffer, the resulting javascript object will contain the following properties: authdata the same as authenticatorassertionresponse.authenticatordata.
AuthenticatorResponse.clientDataJSON - Web APIs
properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created.
Background Tasks API - Web APIs
for each task in the queue that we have time to execute, we do the following: we remove the task object from the queue.
BaseAudioContext.createAnalyser() - Web APIs
example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
BaseAudioContext.createBiquadFilter() - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
BaseAudioContext.createChannelMerger() - Web APIs
example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
BaseAudioContext.createChannelSplitter() - Web APIs
example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
BaseAudioContext.createConvolver() - Web APIs
example the following example shows basic usage of an audiocontext to create a convolver node.
BaseAudioContext.createOscillator() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
BaseAudioContext.createPanner() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
BaseAudioContext.createPeriodicWave() - Web APIs
example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave.
BaseAudioContext.createWaveShaper() - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
BaseAudioContext.onstatechange - Web APIs
}; example the following snippet is taken from our audiocontext states demo (see it running live.) the onstatechange hander is used to log the current state to the console every time it changes.
BaseAudioContext.state - Web APIs
closed: the audio context has been closed (with the audiocontext.close() method.) example the following snippet is taken from our audiocontext states demo (see it running live.) the audiocontext.onstatechange hander is used to log the current state to the console every time it changes.
BasicCardRequest.supportedNetworks - Web APIs
legal values are defined in the w3c's document card network identifiers approved for use with payment request api, and are currently: amex cartebancaire diners discover jcb mastercard mir unionpay visa example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties.
BasicCardRequest.supportedTypes - Web APIs
legal values are defined in basiccardtype enum, and are currently: credit debit prepaid example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties.
BasicCardRequest - Web APIs
those are: amex cartebancaire diners discover jcb mastercard mir unionpay visa examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object that describes what data is needed to fullfil the payment (e.g., a shipping addre...
BasicCardResponse - Web APIs
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
BiquadFilterNode.Q - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
BiquadFilterNode.detune - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
BiquadFilterNode.frequency - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
BiquadFilterNode.gain - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
BiquadFilterNode.getFrequencyResponse() - Web APIs
example in the following example we are using a biquad filter on a media stream (for the full demo, see our stream-source-buffer demo live, or read the source.) as part of this demo, we get the frequency responses for this biquad filter, for five sample frequencies.
BiquadFilterNode.type - Web APIs
not used example the following example shows basic usage of an audiocontext to create a biquad filter node.
BiquadFilterNode - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
Blob() - Web APIs
WebAPIBlobBlob
options optional an optional object of type blobpropertybag which may specify any of the following properties: type optional the mime type of the data that will be stored into the blob.
Bluetooth.getAvailability() - Web APIs
examples the following snippet prints out a message in the console specifying wheter or not bluetooth is supported: navigator.bluetooth.getavailability().then(available => { if (available) console.log("this device supports bluetooth!"); else console.log("doh!
BluetoothCharacteristicProperties - Web APIs
examples the following example shows how tell if a gatt characteristic supports value change notifications.
CSS.paintWorklet (Static property) - Web APIs
WebAPICSSpaintWorklet
examples the following example demonstrates loading a paintworklet from its js file and does so by feature detection.
CSSCounterStyleRule - Web APIs
inheritance this interface inherits from the following parent interfaces: <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" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/cssrule" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">cssrule</text></a><polyline points="76,25 86,20 86,3...
CSSKeywordValue.CSSKeywordValue() - Web APIs
examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector.
CSSKeywordValue.value - Web APIs
examples the following example resets the css display property to its defaults.
CSSKeywordValue - Web APIs
examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector.
CSSMediaRule - Web APIs
it has the following specific property: cssmediarule.media read only specifies a medialist representing the intended destination medium for style information.
CSSNumericValue.equals() - Web APIs
some of the following examples illustrate what happens when they are not.
CSSNumericValue.max() - Web APIs
some of the following examples illustrate what happens when they are not.
CSSNumericValue.min() - Web APIs
some of the following examples illustrate what happens when they are not.
CSSNumericValue.parse() - Web APIs
exceptions syntaxerror tbd examples the following returns a cssunitvalue object with a unit property equal to "px" and a value property equal to 42.
CSSPageRule - Web APIs
it has the following specific properties: csspagerule.selectortext represents the text of the page selector associated with the at-rule.
CSSPositionValue.CSSPositionValue() - Web APIs
examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
CSSPositionValue.x - Web APIs
example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
CSSPositionValue.y - Web APIs
example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
CSSPositionValue - Web APIs
examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
CSSPseudoElement.type - Web APIs
syntax var typeofpseudoelement = csspseudoelement.type; value a cssomstring containing one of the following values: "::before" "::after" "::marker" examples the example below demonstrates the relationship between csspseudoelement.type and element.pseudo(): const myelement = document.queryselector('q'); const myselector = '::after'; const csspseudoelement = myelement.pseudo(myselector); const typeofpseudoelement = csspseudoelement.type; console.log(myselector === typeofpseudoelement); // outputs true specifications specification status comment css pseudo-elements level 4the definition of 'type' in tha...
CSSPseudoElement - Web APIs
methods csspseudoelement extends eventtarget, so it inherits the following methods: eventtarget.addeventlistener() registers an event handler of a specific event type on the pseudo-element.
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
example the following javascript code gets an object containing the computed rgb values of the color css property: var style = window.getcomputedstyle(elem, null); var rgbobj = style.getpropertycssvalue('color').getrgbcolorvalue(); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssstyledeclaration' in that specificat...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
example the following javascript code checks whether margin is marked as important in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var isimportant = declaration.getpropertypriority('margin') === 'important'; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertypriority()' in that specif...
CSSStyleDeclaration.getPropertyValue() - Web APIs
example the following javascript code queries the value of the margin property in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var value = declaration.getpropertyvalue('margin'); // "1px 2px" specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertyvalue()' in that specification.
CSSStyleDeclaration.length - Web APIs
example the following gets the number of explicitly set styles on the following html element: <div id="div1" style="margin: 0 10px; background-color: #ca1; font-family: monospace"></div> javascript code: var mydiv = document.getelementbyid('div1'); var divstyle = mydiv.style; var len = divstyle.length; // 6 specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.length' in that specification.
CSSStyleDeclaration.parentRule - Web APIs
example the following javascript code gets the parent css style rule from a cssstyledeclaration: var declaration = document.stylesheets[0].rules[0].style; var rule = declaration.parentrule; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.parentrule' in that specification.
CSSStyleDeclaration.removeProperty() - Web APIs
example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.removeproperty()' in that specification.
CSSStyleDeclaration.setProperty() - Web APIs
the following values are accepted: string value "important" keyword undefined string empty value "" return value undefined exceptions domexception (nomodificationallowederror): if the property or declaration block is read only.
CSSStyleSheet.addRule() - Web APIs
therefore, given existing code such as the following: cssstylesheet.addrule(selector, styles, 0); you can rewrite this to use the more standard insertrule() like this: cssstylesheet.insertrule(`${selector} {${styles}}`, 0); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.addrule()' in that specification.
CSSUnitValue.CSSUnitValue() - Web APIs
examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors.
CSSUnitValue.unit - Web APIs
WebAPICSSUnitValueunit
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.unit.
CSSUnitValue.value - Web APIs
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.value.
CSSUnitValue - Web APIs
examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors.
Managing screen orientation - Web APIs
let's have an example with the following html code <ul id="toolbar"> <li>a</li> <li>b</li> <li>c</li> </ul> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
Using dynamic styling information - Web APIs
to change a particular element's style, you can adapt the following example for the element(s) you want to style.
Using the CSS Painting API - Web APIs
.fancy { background-image: paint(headerhighlight); } putting it together we can then add the fancy class to any element on the page to add a yellow box as a background: <h1 class="fancy">my cool header</h1> the following example will look like the image above in browsers supporting the css painting api.
CSS Properties and Values API - Web APIs
examples the following uses css.registerproperty in javascript to type a css custom properties, --my-color, as a color, give it a default value, and not allow it to inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); the same registration can take place in css using the following @property: @property --my-color { syntax: '<...
Using the CSS Typed Object Model - Web APIs
we grab our stylepropertymapreadonly with the following javascript: const allcomputedstyles = document.queryselector('button').computedstylemap(); the following examples reference allcomputedstyles: cssunparsedvalue the cssunparsedvalue represents custom properties: // cssunparsedvalue let unit = allcomputedstyles.get('--unit'); console.log( unit ) // cssunparsedvalue {0: " 1.2rem", length: 1} console.log (unit[0] ) // " 1.2rem" when we inv...
Cache.add() - Web APIs
WebAPICacheadd
the add() method is functionally equivalent to the following: fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) for more complex operations, you'll need to use cache.put() directly.
CacheStorage.has() - Web APIs
WebAPICacheStoragehas
examples the following example first checks whether a cache called 'v1' exists.
CanvasCaptureMediaStreamTrack - Web APIs
the canvascapturemediastreamtrack interface represents the video track contained in a mediastream being generated from a <canvas> following a call to htmlcanvaselement.capturestream().
CanvasImageSource - Web APIs
the interfaces that it allows to be used as image sources are the following: htmlimageelement svgimageelement htmlvideoelement htmlcanvaselement imagebitmap offscreencanvas specifications specification status comment html living standardthe definition of 'canvasimagesource' in that specification.
CanvasPattern.setTransform() - Web APIs
es/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); }; note that newer browser versions started to support dommatrix as an input to settransform(), so for example you could replace the svgmatrix in the above example with the following: const matrix = new dommatrix([1, .2, .8, 1, 0, 0]); edit the code below and see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1" style="display:none"></svg> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div>...
CanvasRenderingContext2D.addHitRegion() - Web APIs
when provided, it is an object which can contain the following properties: path a path2d object describing the area of the hit region.
CanvasRenderingContext2D.createPattern() - Web APIs
it can be any of the following: htmlimageelement (<img>) svgimageelement (<image>) htmlvideoelement (<video>, by using the capture of the video) htmlcanvaselement (<canvas>) imagebitmap offscreencanvas repetition a domstring indicating how to repeat the pattern's image.
CanvasRenderingContext2D.filter - Web APIs
syntax ctx.filter = "<filter-function1> [<filter-function2>] [<filter-functionn>]"; ctx.filter = "none"; values the filter property accepts a value of "none" or one or more of the following filter functions in a domstring.
CanvasRenderingContext2D.getTransform() - Web APIs
examples in the following example, we have two <canvas> elements.
CanvasRenderingContext2D.measureText() - Web APIs
you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('hello world'); console.log(text.width); // 56; specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.measuretext' in that specification.
CanvasRenderingContext2D.rotate() - Web APIs
to do this, the following steps are applied to the matrix: first, translate() moves the matrix's origin to the shape's center.
CanvasRenderingContext2D.save() - Web APIs
the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled.
CanvasRenderingContext2D.setTransform() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.settransform(1, .2, .8, 1, 0, 0); ctx.fillrect(0, 0, 100, 100); result retrieving and passing a dommatrix object in the following example, we have two <canvas> elements.
Basic animations - Web APIs
<canvas id="canvas" width="800" height="200"></canvas> mouse following animation <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>document</title> <script> var cn; //= document.getelementbyid('cw'); var c; var u = 10; c...
Compositing and clipping - Web APIs
see compositing examples for the code of the following examples.
Optimizing canvas - Web APIs
performance tips the following is a collection of tips to improve canvas performance.
ChannelMergerNode - Web APIs
example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
ChannelSplitterNode - Web APIs
example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
Using channel messaging - Web APIs
receiving the port and message in the iframe over in the iframe, we have the following javascript: var list = document.queryselector('ul'); var port2; // listen for the initial port transfer message window.addeventlistener('message', initport); // setup the transferred port function initport(e) { port2 = e.ports[0]; port2.onmessage = onmessage; } // handle messages received on port2 function onmessage(e) { var listitem = document.createelement('li'); listitem.textconten...
CharacterData - Web APIs
nondocumenttypechildnode.nextelementsibling read only returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.
ChildNode.after() - Web APIs
WebAPIChildNodeafter
with(node) { after("foo"); } // referenceerror: after is not defined polyfill you can polyfill the after() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { return; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.call...
ChildNode.before() - Web APIs
WebAPIChildNodebefore
with(node) { before("foo"); } // referenceerror: before is not defined polyfill you can polyfill the before() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { return; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice...
ChildNode.remove() - Web APIs
WebAPIChildNoderemove
with(node) { remove(); } // referenceerror: remove is not defined polyfill you can polyfill the remove() method in internet explorer 9 and higher with the following code: // from:https://github.com/jserz/js_piece/blob/master/dom/childnode/remove()/remove().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('remove')) { return; } object.defineproperty(item, 'remove', { configurable: true, enumerable: true, writable: true, value: function remove() { this.parentnode.removechild(this); ...
ChildNode.replaceWith() - Web APIs
with(node) { replacewith("foo"); } // referenceerror: replacewith is not defined polyfill you can polyfill the replacewith() method in internet explorer 10+ and higher with the following code: function replacewithpolyfill() { 'use-strict'; // for safari, and ie > 10 var parent = this.parentnode, i = arguments.length, currentnode; if (!parent) return; if (!i) // if there are no arguments parent.removechild(this); while (i--) { // i-- decrements i and returns the value of i before the decrement currentnode = arguments[i]; if (typeof currentnode !== 'object'){...
Clients.claim() - Web APIs
WebAPIClientsclaim
example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker.
Clients - Web APIs
WebAPIClients
examples the following example shows an existing chat window or creates a new one when the user clicks a notification.
ClipboardItem.getType() - Web APIs
examples in the following example, we're returning all items on the clipboard via the clipboard.read() method.
CloseEvent() - Web APIs
closeeventinit optional is a closeeventinit dictionary, having the following fields: "wasclean", optional and defaulting to false, of type long, indicates if the connection has been closed cleanly or not.
CompositionEvent.CompositionEvent() - Web APIs
compositioneventinit optional a compositioneventinit dictionary object, which can contain the following members: data initializes the data attribute of the compositionevent object to the characters generated by the ime composition.
console.assert() - Web APIs
WebAPIConsoleassert
examples the following code example demonstrates the use of a javascript object following the assertion: const errormsg = 'the # is not even'; for (let number = 2; number <= 5; number += 1) { console.log('the # is ' + number); console.assert(number % 2 === 0, {number: number, errormsg: errormsg}); // or, using es2015 object property shorthand: // console.assert(number % 2 === 0, {number, errormsg}); } ...
Console.group() - Web APIs
WebAPIConsolegroup
this indents following console messages by an additional level, until console.groupend() is called.
console.trace() - Web APIs
WebAPIConsoletrace
example function foo() { function bar() { console.trace(); } bar(); } foo(); in the console, the following trace will be displayed: bar foo <anonymous> specifications specification status comment console apithe definition of 'console.trace()' in that specification.
ConstantSourceNode - Web APIs
properties inherits properties from its parent interface, audioscheduledsourcenode, and adds the following properties: offset an audioparam which specifies the value that this source continuously outputs.
ConstrainDOMString - Web APIs
properties the value of a constraindomstring can be any of the following: a single domstring an array of domstring objects an object with one or both of the following properties: exact either a single domstring which must be the value of the property, or an array of domstring objects one of which must be the property's value.
ConvolverNode - Web APIs
convolvernode example the following example shows basic usage of an audiocontext to create a convolver node.
CredentialsContainer.get() - Web APIs
it can contain the following properties: password: a boolean indicating that returned credential instances should include user (as opposed to federated) credentials.
CryptoKey - Web APIs
WebAPICryptoKey
properties cryptokey.type string which may take one of the following values: "secret": this key is a secret key for use with a symmetric algorithm.
CustomElementRegistry - Web APIs
examples the following code is taken from our word-count-web-component example (see it live also).
CustomEvent() - Web APIs
customeventinit optional a customeventinit dictionary, having the following fields: "detail", optional and defaulting to null, of type any, that is an event-dependent value associated with the event.
DOMImplementation.createHTMLDocument() - Web APIs
view live examples the returned document is pre-constructed with the following html: <!doctype html> <html> <head> <title>title</title> </head> <body> </body> </html> specifications specification status comment domthe definition of 'domimplementation.createhtmldocument' in that specification.
DOMMatrix - Web APIs
WebAPIDOMMatrix
2d 3d equivalent a m11 b m12 c m21 d m22 e m41 f m42 methods this interface includes the following methods, as well as the methods it inherits from dommatrixreadonly.
DOMMatrixReadOnly.translate() - Web APIs
examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which is then applied to the blue square as a transform.
DOMMatrixReadOnly - Web APIs
none of the following methods alter the original matrix.
DOMParser - Web APIs
WebAPIDOMParser
the possible values are the following: mimetype doc.constructor text/html document text/xml xmldocument application/xml xmldocument application/xhtml+xml xmldocument image/svg+xml xmldocument examples parsing xml once you have created a parser object, you can parse xml from a string using the parsefromstring() method...
DOMPoint - Web APIs
WebAPIDOMPoint
in the following snippet, the pose of the xr device (such as a vr headset or phone with ar capabilities) can be retrieved by calling using xrframe.getviewerpose() during an xrsession animation frame, then accessing the resulting xrpose's transform property, which contains two dompointreadonly attributes: position as a vector and orientation as a quaternion.
DOMPointReadOnly() - Web APIs
examples the following code demonstrates creating both 2d and 3d points.
DOMTokenList.add() - Web APIs
WebAPIDOMTokenListadd
return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.contains() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.entries() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.forEach() - Web APIs
example in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.item() - Web APIs
WebAPIDOMTokenListitem
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.keys() - Web APIs
WebAPIDOMTokenListkeys
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.length - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the length of the list to the <span>'s node.textcontent.
DOMTokenList.remove() - Web APIs
return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.toggle() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.value - Web APIs
syntax tokenlist.value; value a domstring examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the value of the list to the <span>'s node.textcontent.
DOMTokenList.values() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList - Web APIs
examples in the following simple example, we retrieve the list of classes set on a <p> element as a domtokenlist using element.classlist, add a class using domtokenlist.add(), and then update the node.textcontent of the <p> to equal the domtokenlist.
DataTransferItem.kind - Web APIs
it must be one of the following values: 'file' if the drag data item is a file.
DataTransferItem.webkitGetAsEntry() - Web APIs
in chromium-based browsers, the following example will only return a max of 100 entries.
DedicatedWorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope.
DedicatedWorkerGlobalScope.onmessage - Web APIs
}; example the following code snippet shows creation of a worker object using the worker() constructor.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
example the following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script.
DelayNode() - Web APIs
can contain the following members: delaytime: the initial delay time for the node, in seconds.
Detecting device orientation - Web APIs
for acceleration and accelerationincludinggravity, those axes correspond to the following: x: represents the axis from west to east y: represents the axis from south to north z: represents the axis perpendicular to the ground for rotationrate, the situation is a bit different; the information corresponds to the following in each case: alpha: represents a rotation rate along the axis perpendicular to the screen (or keyboard for desktop).
Document.anchors - Web APIs
WebAPIDocumentanchors
example if (document.anchors.length >= 5) { dump("found too many anchors"); } the following is an example that auto populates a table of contents with every anchor on the page: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>test</title> <script> function init() { var toc = document.getelementbyid("toc"); var i, li, newanchor; for (i = 0; i < document.anchors.length; i++) { li = document.createelement("li"); newanchor = document.createelement('a'); newanchor.href = "#" + document.anchors[i].name; newanchor.innerhtml = document.anchors[i].text; li.appendchild(newanch...
Document.caretRangeFromPoint() - Web APIs
returns one of the following: a range.
Document.createProcessingInstruction() - Web APIs
exceptions dom_invalid_character throws if either of the following are true: the processing instruction target is invalid — it should be a valid xml name that doesn't contain "xml", "xml", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>.
Document.createTouchList() - Web APIs
in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects.
Document.createTreeWalker() - Web APIs
example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.
Document.domain - Web APIs
WebAPIDocumentdomain
exceptions securityerror an attempt has been made to set domain under one of the following conditions: the document is inside a sandboxed <iframe> the document has no browsing context the document's effective domain is null the given value is not equal to the document's effective domain (or it is not a registerable domain suffix of it) the document-domain feature-policy is enabled examples getting the domain for the uri http://developer.mozilla.org/docs/web, this ex...
Document.getAnimations() - Web APIs
examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate.
Document.getElementsByTagName() - Web APIs
example in the following example, getelementsbytagname() starts from a particular parent element and searches top-down recursively through the dom from that parent element, building a collection of all descendant elements which match the tag name parameter.
Document.images - Web APIs
WebAPIDocumentimages
the following are equivalent: firstimage = imagecollection.item(0); firstimage = imagecollection[0]; example this example looks through the list of images and finds one whose name is "banner.gif".
Document.querySelector() - Web APIs
or('#foo:bar'); // does not match anything document.queryselector('#foo\\:bar'); // match the second div </script> examples finding the first element matching a class in this example, the first element in the document with the class "myclass" is returned: var el = document.queryselector(".myclass"); a more complex selector selectors can also be really powerful, as demonstrated in the following example.
Document.readyState - Web APIs
syntax var string = document.readystate; values the readystate of a document can be one of following: loading the document is still loading.
DocumentOrShadowRoot - Web APIs
the following features are included in both document and shadowroot.
Events and the DOM - Web APIs
the following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.
Locating DOM elements using selectors - Web APIs
for example, to select all paragraph (p) elements in a document whose css class is either warning or note, you can do the following: var special = document.queryselectorall( "p.warning, p.note" ); you can also query by id.
Document Object Model (DOM) - Web APIs
to achieve this, the following interfaces present in the different dom level 3 or earlier specifications have been removed.
DragEvent() - Web APIs
drageventinitoptional is a drageventinit dictionary, having the following fields: "datatransfer", optional and defaults to "null".
EXT_color_buffer_float - Web APIs
extended methods the following sized formats become color-renderable: gl.r16f, gl.rg16f, gl.rgba16f, gl.r32f, gl.rg32f, gl.rgba32f, gl.r11f_g11f_b10f.
EXT_sRGB - Web APIs
WebAPIEXT sRGB
constants this extension exposes the following constants, which can be used in the teximage2d(), texsubimage2d(), renderbufferstorage() and getframebufferattachmentparameter() methods.
EXT_shader_texture_lod - Web APIs
glsl built-in functions the following new functions can be used in glsl shader code, if this extension is enabled: vec4 texture2dlodext(sampler2d sampler, vec2 coord, float lod) vec4 texture2dprojlodext(sampler2d sampler, vec3 coord, float lod) vec4 texture2dprojlodext(sampler2d sampler, vec4 coord, float lod) vec4 texturecubelodext(samplercube sampler, vec3 coord, float lod) vec4 texture2dgradext(sampler2d sampler, vec2 p, vec2 dpd...
EcKeyGenParams - Web APIs
this may be any of the following names for nist-approved curves: p-256 p-384 p-521 examples see the examples for subtlecrypto.generatekey().
EcKeyImportParams - Web APIs
this may be any of the following names for nist-approved curves: p-256 p-384 p-521 examples see the examples for subtlecrypto.importkey().
EcdsaParams - Web APIs
this should be one of the following: sha-256: selects the sha-256 algorithm.
EffectTiming.direction - Web APIs
it can take one of the following values, with the default being "normal": "normal" the animation runs forwards, from beginning to end, in the way we experience the flow of time.
Element.attributes - Web APIs
the following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value.
Element.classList - Web APIs
WebAPIElementclassList
the following polyfill for both classlist and domtokenlist ensures full compliance (coverage) for all standard methods and properties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9.
Element: click event - Web APIs
safari mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug): <a> (but it must have an href) <area> (but it must have an href) <button> <img> <input> <label> (but it must be associated with a form control) <textarea> this list is incomplete; you can help mdn by doing further testing/research and expanding it.
Element.clientTop - Web APIs
WebAPIElementclientTop
syntax var top = element.clienttop; example in the following illustration, the client area is show in white.
Element.closest() - Web APIs
WebAPIElementclosest
ector || element.prototype.webkitmatchesselector; } if (!element.prototype.closest) { element.prototype.closest = function(s) { var el = this; do { if (element.prototype.matches.call(el, s)) return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually.
Element.getAttributeNS() - Web APIs
examples the following svg document reads the value of the foo attribute in a custom namespace.
Element.getElementsByClassName() - Web APIs
however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed.
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
css the following css styles our example content.
Element.insertAdjacentElement() - Web APIs
syntax targetelement.insertadjacentelement(position, element); parameters position a domstring representing the position relative to the targetelement; must match (case-insensitively) one of the following strings: 'beforebegin': before the targetelement itself.
Element.insertAdjacentHTML() - Web APIs
syntax element.insertadjacenthtml(position, text); parameters position a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself.
Element.matches() - Web APIs
WebAPIElementmatches
tchesselector || element.prototype.omatchesselector || element.prototype.webkitmatchesselector || function(s) { var matches = (this.document || this.ownerdocument).queryselectorall(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; } however, given the practicality of supporting older browsers, the following should suffice for most (if not all) practical cases (i.e.
Element: mousedown event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmousedown examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas.
Element: mouseenter event - Web APIs
mouseenter the following trivial example uses the mouseenter event to change the border on the div when the mouse enters the space alloted to it.
Element: mouseleave event - Web APIs
mouseleave the following trivial example uses the mouseenter event to change the border on the <div> when the mouse enters the space alloted to it.
Element: mousemove event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmousemove examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas.
Element: mouseover event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmouseover examples the following example illustrates the difference between mouseover and mouseenter events.
Element: mouseup event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmouseup examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas.
Element: mousewheel event - Web APIs
see following explanation for the detail.
Element.name - Web APIs
WebAPIElementname
it only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>.
Element.part - Web APIs
WebAPIElementpart
syntax let elementpartlist = element.part examples the following excerpt is from our shadow-part example.
Element.prefix - Web APIs
WebAPIElementprefix
syntax string = element.prefix examples the following logs "x" to the console.
Element.requestFullscreen() - Web APIs
the rejection handler receives one of the following exception values: typeerror the typeerror exception may be delivered in any of the following situations: the document containing the element isn't fully active; that is, it's not the current active document.
Element.scrollIntoView() - Web APIs
scrollintoviewoptions optional is an object with the following properties: behavior optional defines the transition animation.
Element.setAttribute() - Web APIs
example in the following example, setattribute() is used to set attributes on a <button>.
Element.shadowRoot - Web APIs
examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
Element.toggleAttribute() - Web APIs
example in the following example, toggleattribute() is used to toggle the readonly attribute of a <input>.
ElementCSSInlineStyle.style - Web APIs
the following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the getcomputedstyle() method: <!doctype html> <html> <body style="font-weight:bold;"> <div style="color:red" id="myelement">..</div> </body> </html> var element = document.getelementbyid("myelement"); var out = ""; var elementstyle = element.style; var comput...
Event() - Web APIs
WebAPIEventEvent
eventinit optional this is an eventinit dictionary, having the following optional fields: bubbles optional a boolean indicating whether the event bubbles.
Event.msConvertURL() - Web APIs
targettype [in] type: domstring one of the following values indicating the desired conversion type: "specified", "base64", or "unchanged".
Event.preventDefault() - Web APIs
<code>preventdefault()</code> won't let you check this!<br>"; event.preventdefault(); }, false); html <p>please click on the checkbox control.</p> <form> <label for="id-checkbox">checkbox:</label> <input type="checkbox" id="id-checkbox"/> </form> <div id="output-box"></div> result stopping keystrokes from reaching an edit field the following example demonstrates how invalid text input can be stopped from reaching the input field with preventdefault().
EventSource - Web APIs
const sse = new eventsource('/api/v1/sse'); /* this will listen only for events * similar to the following: * * event: notice * data: useful data * id: someid * */ sse.addeventlistener("notice", function(e) { console.log(e.data) }) /* similarly, this will listen for events * with the field `event: update` */ sse.addeventlistener("update", function(e) { console.log(e.data) }) /* the event "message" is a special case, as it * will capture events without a...
ExtendableMessageEvent() - Web APIs
init optional an initialisation object, which should contain the following parameters: data: the event's data — this can be any data type.
ExtendableMessageEvent.data - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.lastEventId - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.origin - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.ports - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.source - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
FeaturePolicy.allowsFeature() - Web APIs
example the following example queries whether or not the document is allowed to use camera api by the feature policy.
FetchEvent.navigationPreload - Web APIs
example the following example shows the implementation of a fetch event that uses a preloaded response.
Fetch API - Web APIs
WebAPIFetch API
the following browsers shipped and outdated native fetch, and were updated in these versions: firefox version 61.0b13.
Using files from web applications - Web APIs
example: showing file(s) size the following example shows a possible use of the size property: <!doctype html> <html> <head> <meta charset="utf-8"> <title>file(s) size</title> </head> <body> <form name="uploadform"> <div> <input id="uploadinput" type="file" name="myfiles" multiple> selected files: <span id="filenum">0</span>; total size: <span id="filesize">0</span> </div> <div><input type="submit" val...
File - Web APIs
WebAPIFile
file implements blob, so it also has the following properties available to it: file.prototype.size read only returns the size of the file in bytes.
FileList - Web APIs
WebAPIFileList
for example, if the html includes the following file input: <input id="fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicating the number of files in the list.
FileReader() - Web APIs
example the following code snippet shows creation of a filereader object using the filereader() constructor and subsequent usage of the object: function printfile(file) { var reader = new filereader(); reader.onload = function(evt) { console.log(evt.target.result); }; reader.readastext(file); } specifications specification status comment file api working draft initial definition ...
FileReader.readyState - Web APIs
a filereader exists in one of the following states: value state description 0 empty reader has been created.
FileReader - Web APIs
this is one of the following: empty 0 no data has been loaded yet.
FileSystemDirectoryEntry - Web APIs
example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes.
FileSystemDirectoryReader.readEntries() - Web APIs
in chromium-based browsers, the following example will only return a max of 100 entries.
FileSystemFileEntry - Web APIs
example the following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "meow".
FileHandle API - Web APIs
api overview this api is based on the following interfaces: idbdatabase.mozcreatefilehandle (was called idbdatabase.mozcreatefilehandle.) idbmutablefile (was previously filehandle.) lockedfile filerequest it also has connections with the file api, especially the file and blob interfaces.
File and Directory Entries API support in Firefox - Web APIs
to ensure your code will work in both chrome and other browsers, you can include code similar to the following: var filesystemdirectoryentry = window.filesystemdirectoryentry || window.directoryentry; var filesystementry = window.filesystementry || window.entry; limitations in firefox next, let's look at limitations of the firefox implementation of the api.
File and Directory Entries API - Web APIs
it includes the following interfaces: filesystem represents a file system.
FocusEvent() - Web APIs
focuseventinit optional is a focuseventinit dictionary, having the following fields: "relatedtarget", optional and defaulting to null, is an eventtarget representing the secondary target of a focusevent.
FontFace.FontFace() - Web APIs
WebAPIFontFaceFontFace
it can have the following keys: family: family style: style weight: weight stretch: stretch unicoderange: unicode range variant: variant featuresettings: feature settings example async function loadfonts() { const font = new fontface('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load(); // add font to document document.fonts.add(font); // enable font...
FontFace.display - Web APIs
WebAPIFontFacedisplay
syntax var display = fontface.display fontface.display = display value a cssomstring with one of the following values.
Force Touch events - Web APIs
event properties the following property is known to be available on the webkitmouseforcewillbegin, mousedown, webkitmouseforcechanged, webkitmouseforcedown, webkitmouseforceup, mousemove, and mouseup event objects: mouseevent.webkitforce read only the amount of pressure currently being applied to the trackpad/touchscreen constants these constants are useful for determining the relative intensity of the pressure indic...
FormData() - Web APIs
WebAPIFormDataFormData
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you could add a key/value pair to this using formdata.append: formdata.append('username', 'chris'); or you can specify the optional form argument when creating the formdata object, to prepopulate it with values from the specified form: <form id="myform" name="myform"> <div> <label for="username">e...
Using FormData Objects - Web APIs
ocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br /> <label>custom file label:</label> <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>file to stash:</label> <input type="file" name="file" required /> <input type="submit" value="stash the file!" /> </form> <div></div> then you can send it using code like the following: var form = document.forms.nameditem("fileinfo"); form.addeventlistener('submit', function(ev) { var ooutput = document.queryselector("div"), odata = new formdata(form); odata.append("customfield", "this is some extra data"); var oreq = new xmlhttprequest(); oreq.open("post", "stash.php", true); oreq.onload = function(oevent) { if (oreq.status == 200) { ooutput.inner...
FormData.append() - Web APIs
WebAPIFormDataappend
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can add key/value pairs to this using formdata.append: formdata.append('username', 'chris'); formdata.append('userpic', myfileinput.files[0], 'chris.jpg'); as with regular form data, you can append multiple values with the same name.
FormData.delete() - Web APIs
WebAPIFormDatadelete
example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata = new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification.
FormData.get() - Web APIs
WebAPIFormDataget
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following get() function will only return the first username value appended: formdata.get('username'); // returns "chris" specifications specification status comment x...
FormData.getAll() - Web APIs
WebAPIFormDatagetAll
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will return both username values in an array: formdata.getall('username'); // returns ["chris", "bob"] specifications specification status comment ...
FormData.has() - Web APIs
WebAPIFormDatahas
example the following line creates an empty formdata object: var formdata = new formdata(); the following snippet shows the results of testing for the existence of username in the formdata object, before and after appending a username value to it with formdata.append: formdata.has('username'); // returns false formdata.append('username', 'chris'); formdata.has('username'); // returns true specifications specification status comment xmlhttprequestthe definition of...
FormData.set() - Web APIs
WebAPIFormDataset
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can set key/value pairs on this using formdata.set: formdata.set('username', 'chris'); formdata.set('userpic', myfileinput.files[0], 'chris.jpg'); if the sent value is different than string or blob it will be automatically converted to string: formdata.set('name', 72); formdata.get('name'); // "72" ...
FormDataEvent() - Web APIs
formeventinit optional a formeventinit dictionary, which can take the following optional fields: bubbles: a boolean indicating whether the event bubbles.
Frame Timing API - Web APIs
performance frames the performanceframetiming interface extends the following performanceentry properties (for "frame" performance entry types) by qualifying and constrainting the properties as follows: performanceentry.entrytype set to "frame".
FullscreenOptions.navigationUI - Web APIs
syntax let fullscreenoptions = { navigationui: value }; value the value of the navigationui property must be one of the following strings.
Fullscreen API - Web APIs
these are listed in the following sections.
Gamepad.buttons - Web APIs
WebAPIGamepadbuttons
syntax readonly attribute gamepadbutton[] buttons; example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stores as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the ga...
Gamepad - Web APIs
WebAPIGamepad
experimental extensions to gamepad the following interfaces are defined in the gamepad extensions specification, and provide access to experimental features like haptic feedback and webvr controller pose information.
GamepadButton - Web APIs
example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stored as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the ga...
GeolocationPositionError.code - Web APIs
the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it.
GeolocationPositionError - Web APIs
the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it.
Using the Geolocation API - Web APIs
you could use it like so: function errorcallback(error) { alert(`error(${error.code}): ${error.message}`); }; examples in the following example the geolocation api is used to retrieve the user's latitude and longitude.
Geolocation API - Web APIs
examples in the following example the geolocation api is used to retrieve the user's latitude and longitude.
GlobalEventHandlers.onkeypress - Web APIs
mbers only: <input> </label> javascript function numbersonly(event) { return event.charcode === 0 || /\d/.test(string.fromcharcode(event.charcode)); } const input = document.queryselector('input'); input.onkeypress = numbersonly; // prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; result capture the typing of a hidden word the following javascript function will do something after the user types the word "exit" in any point of a page.
HTMLAudioElement - Web APIs
obsolete mozilla-only methods the following methods are non-standard and should not be used.
HTMLCanvasElement.getContext() - Web APIs
examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get a 2d context of the canvas with the following code: var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); console.log(ctx); // canvasrenderingcontext2d { ...
HTMLCanvasElement.height - Web APIs
syntax var pxl = canvas.height; canvas.height = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the height of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.height); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.height' in that specification.
HTMLCanvasElement.mozGetAsFile() - Web APIs
html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="link">click here to try out mozgetasfile()</a>.</p> javascript the following code uses mozgetasfile() to create a file object from the canvas and appends it as an image to the page by loading it as a data url using the readasdataurl() method.
HTMLCanvasElement.toDataURL() - Web APIs
examples given this <canvas> element: <canvas id="canvas" width="5" height="5"></canvas> you can get a data-url of the canvas with the following lines: var canvas = document.getelementbyid('canvas'); var dataurl = canvas.todataurl(); console.log(dataurl); // "data:image/png;base64,ivborw0kggoaaaansuheugaaaauaaaafcayaaacnby // blaaaadeleqvqimwngobmaaabpaafei8araaaaaelftksuqmcc" setting image quality with jpegs var fullquality = canvas.todataurl('image/jpeg', 1.0); // data:image/jpeg;base64,/9j/4aaqskzjrgabaq...9oadambaairaxeapwd/ad/6ap...
HTMLCanvasElement.width - Web APIs
syntax var pxl = canvas.width; canvas.width = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the width of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.width); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.width' in that specification.
HTMLDialogElement.close() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method.
HTMLDialogElement.open - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method.
HTMLDialogElement.returnValue - Web APIs
examples the following example displays a button to open a <dialog> containing a form via the showmodal() method.
HTMLDialogElement.show() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the show() method.
HTMLDialogElement.showModal() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method.
HTMLDialogElement - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the htmldialogelement.showmodal() function.
HTMLElement.contentEditable - Web APIs
this enumerated attribute can have the following values: 'true' indicates that the element is contenteditable.
inert - Web APIs
WebAPIHTMLElementinert
check out the following polyfills: inert ...
HTMLElement.offsetParent - Web APIs
note: offsetparent returns null in the following situations: the element or its parent element has the display property set to none.
HTMLElement: transitioncancel event - Web APIs
transition = document.queryselector('.transition'); transition.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): const transition = document.queryselector('.transition'); transition.ontransitioncancel = () => { console.log('transition canceled'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 2s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0...
HTMLElement: transitionend event - Web APIs
and adds a listener to the transitionend event: const transition = document.queryselector('.transition'); transition.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend: const transition = document.queryselector('.transition'); transition.ontransitionend = () => { console.log('transition ended'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); backgroun...
HTMLElement: transitionrun event - Web APIs
un event: el.addeventlistener('transitionrun', () => { console.log('transition is running but hasn\'t necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): el.ontransitionrun = () => { console.log('transition started running, and will start transitioning when the transition delay has expired'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); backgrou...
HTMLElement: transitionstart event - Web APIs
event handler property ontransitionstart examples this code adds a listener to the transitionstart event: element.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): element.ontransitionrun = () => { console.log('started transitioning'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); backgrou...
HTMLFontElement.color - Web APIs
the format of the string must follow one of the following html microsyntaxes: microsyntax description examples valid name color string nameofcolor (case insensitive) green green green valid hex color string in rgb format: #rrggbb #008000 rgb using decimal values rgb(x,x,x) (x in 0-255 range) rgb(0,128,0) syntax colorstring = fontobj.color; fontobj.color = colorstring; examples // assumes there is <font id="f"> element in the html var f = document.getelementbyid("f"); f.color = "green"; specifications the <font> tag ...
HTMLFontElement.face - Web APIs
the format of the string must follow one of the following html microsyntax: microsyntax description examples list of one or more valid font family names a list of font names, that have to be present on the local system courier,verdana syntax facestring = fontobj.face; fontobj.face = facestring; examples // assumes there is <font id="f"> element in the html var f = document.getelementbyid("f"); f.face = "ari...
HTMLFontElement.size - Web APIs
the format of the string must follow one of the following html microsyntaxes: microsyntax description examples valid size number string integer number in the range of 1-7 6 relative size string +x or -x, where x is the number relative to the value of the size attribute of the <basefont> element (the result should be in the same range of 1-7) +2 -1 syntax sizestring = fontobj.size; fontobj.size = sizestring; examples // assumes there is <font id="f"> element in the html v...
HTMLFormElement.length - Web APIs
the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms.
HTMLHRElement - Web APIs
recommendation following properties are now obsolete: align, noshade, size, and width.
HTMLHeadElement - Web APIs
recommendation the following property has been removed: profile.
HTMLHyperlinkElementUtils.origin - Web APIs
containing the unicode serialization of the origin of the represented url; that is: for url using the http or https, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified); for url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:.
Image() - Web APIs
examples var myimage = new image(100, 200); myimage.src = 'picture.jpg'; document.body.appendchild(myimage); this would be the equivalent of defining the following html tag inside the <body>: <img width="100" height="200" src="picture.jpg"> specifications specification status comment html living standardthe definition of 'image()' in that specification.
HTMLImageElement.border - Web APIs
for example, if you have the following html: <img src="image.png" border="2"> the following will provide the same appearance using css instead of this obsolete property: <img src="image.png" style="border: 2px;"> you can further provide additional information to change the color and other features of the border: <img src="image.png" style="border: dashed 2px #333388;"> specifications specification status comment ...
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.
HTMLImageElement.decode() - Web APIs
examples the following example shows how to use the decode() method to control when an image is appended to the dom.
HTMLImageElement.longDesc - Web APIs
consider the following older html: <img src="taco-tuesday.jpg" longdesc="image-descriptions/taco-tuesday.html"> here, the longdesc is used to indicate that the user should be able to access a detailed description of the image taco-tuesday.jpg in the html file image-descriptions/taco-tuesday.html.
HTMLImageElement.useMap - Web APIs
consider a <map> that looks like this: <map name="mainmenu-map"> <area shape="circle" coords="25, 25, 75, 75" href="/index.html" alt="return to home page"> <area shape="rect" coords="25, 25, 100, 150" href="/index.html" alt="shop"> </map> given the image map named mainmenu-map, the image which uses it should look something like the following: <img src="menubox.png" usemap="#mainmenu-map"> for additional examples (including interactive ones), see the articles about the <map> and <area> elements, as well as the guide to using image maps.
HTMLLIElement - Web APIs
recommendation the following property is now obsolete: type.
HTMLLabelElement - Web APIs
the following property has been added: control.
HTMLLegendElement - Web APIs
the following property is now obsolete: align.
HTMLMediaElement.canPlayType() - Web APIs
the string will be one of the following values: probably media of the type indicated by the mediatype parameter is probably playable on this device.
HTMLMetaElement - Web APIs
recommendation the following property is now obsolete: scheme.
HTMLOListElement - Web APIs
it can have the following values: '1' meaning that decimal numbers are used: 1, 2, 3, 4, 5, … 'a' meaning that the lowercase latin alphabet is used: a, b, c, d, e, … 'a' meaning that the uppercase latin alphabet is used: a, b, c, d, e, … 'i' meaning that the lowercase latin numerals are used: i, ii, iii, iv, v, … 'i' meaning that the uppercase latin numerals are used: i, ii, iii, iv, v, … htmlo...
Option() - Web APIs
examples just add new options /* assuming we have the following html <select id='s'> </select> */ var s = document.getelementbyid('s'); var options = [four, five, six]; options.foreach(function(element,key) { s[key] = new option(element,key); }); append options with different parameters /* assuming we have the following html <select id="s"> <option>first</option> <option>second</option> <option>third</option> </select> */ var s = docume...
HTMLElement.focus() - Web APIs
this object may contain the following property: preventscroll optional a boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view.
HTMLParagraphElement - Web APIs
recommendation the following property is now obsolete: align.
HTMLParamElement - Web APIs
recommendation the following properties are now obsolete: type, and valuetype.
HTMLPreElement - Web APIs
recommendation the following property is now obsolete: width.
HTMLScriptElement.referrerPolicy - Web APIs
syntax refstr = scriptelem.referrerpolicy; scriptelem.referrerpolicy = refstr; value a domstring; one of the following: no-referrer the referer header will be omitted entirely.
HTMLSelectElement.remove() - Web APIs
example var sel = document.getelementbyid("existinglist"); sel.remove(1); /* takes the existing following select object: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> and changes it to: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="3">option: value 3</option> </select> */ ...
HTMLSelectElement.selectedOptions - Web APIs
itself, looks like this: let orderbutton = document.getelementbyid("order"); let itemlist = document.getelementbyid("foods"); let outputbox = document.getelementbyid("output"); orderbutton.addeventlistener("click", function() { let collection = itemlist.selectedoptions; let output = ""; for (let i=0; i<collection.length; i++) { if (output === "") { output = "your order for the following items has been placed: "; } output += collection[i].label; if (i === (collection.length - 2) && (collection.length < 3)) { output += " and "; } else if (i < (collection.length - 2)) { output += ", "; } else if (i === (collection.length - 2)) { output += ", and "; } } if (output === "") { output = "you didn't order anything!"; } outputbox.i...
HTMLSelectElement - Web APIs
example get information about the selected option /* assuming we have the following html <select id='s'> <option>first</option> <option selected>second</option> <option>third</option> </select> */ var select = document.getelementbyid('s'); // return the index of the selected option console.log(select.selectedindex); // 1 // return the value of the selected option console.log(select.options[select.selectedindex].value) // second a better way to track changes to t...
HTMLSlotElement.assignedNodes() - Web APIs
examples the following snippet is taken from our slotchange example (see it live also).
HTMLSlotElement.name - Web APIs
examples the following snippet is taken from our slotchange example (see it live also).
HTMLSlotElement: slotchange event - Web APIs
examples element.setattribute('slot', slotname); // element.assignedslot = $slot element.removeattribute('slot'); // element.assignedslot = null the following snippet is taken from our slotchange example (see it live also).
HTMLSlotElement - Web APIs
examples the following snippet is taken from our slotchange example (see it live also).
HTMLStyleElement - Web APIs
recommendation the following property has been added: scoped.
HTMLTableElement.align - Web APIs
syntax htmltableelement.align = alignment; var alignment = htmltableelement.align; parameters alignment domstring with one of the following values: left center right example // set the alignmnet of a table var t = document.getelementbyid('tablea'); t.align = 'center'; specification w3c dom 2 html specification htmltableelement .align.
HTMLTableElement.frame - Web APIs
syntax htmltableelement.frame = framesides; var framesides = htmltableelement.frame; parameters framesides is a string whose value is one of the following values: void no sides.
HTMLTableElement.rules - Web APIs
syntax htmltableelement.rules = rules; var rules = htmltableelement.rules; parameters rules is a string with one of the following values: none no rules groups lines between groups only rows lines between rows cols lines between cols all lines between all cells example // turn on all the internal borders of a table var t = document.getelementbyid("tableid"); t.rules = "all"; specification w3c dom 2 html specification ...
HTMLTableRowElement - Web APIs
it reflects the valign attribute and can have one of the following values: "top", "middle", "bottom", or "baseline".
HTMLTableSectionElement - Web APIs
it reflects the valign attribute and can have one of the following values: "top", "middle", "bottom", or "baseline".
HTMLTimeElement.dateTime - Web APIs
the format of the string must follow one of the following html microsyntaxes: microsyntax description examples valid month string yyyy-mm 2011-11, 2013-05 valid date string yyyy-mm-dd 1887-12-01 valid yearless date string mm-dd 11-12 valid time string hh:mm hh:mm:ss hh:mm:ss.mmm 23:59 12:15:47 12:15:52.998 valid local date and time string yyyy-mm-dd hh:mm yyyy-mm-dd hh:mm:ss yyyy-mm-dd hh:mm:ss.mmm yyyy-mm-ddthh:mm yyyy-mm-ddthh:mm:ss yyyy-mm-ddthh:mm:ss.mmm 2013-12-25 11:12 1972-07-25 13:43:07 ...
HTMLTrackElement - Web APIs
events the following events may be fired on a <track> element, in addition to any that may be fired at its parent, htmlelement.
HTMLVideoElement.msIsLayoutOptimalForPlayback - Web APIs
for msislayoutoptimalforplayback to be true, avoid the following: video elements with cascading style sheets (css) outlines set.
msStereo3DPackingMode - Web APIs
syntax htmlvideoelement.msstereo3dpackingmode(topbottom, sidebyside, none); value the following values return, or set, the stereo 3-d content packing as "topbottom", "sidebyside", or "none" for regular 2-d video.
msStereo3DRenderMode - Web APIs
syntax htmlvideoelement.msstereo3drendermode(mono, stereo); value the following values set the stereo display to mono or stereo.
HashChangeEvent - Web APIs
examples syntax options for a hash change you can listen for the hashchange event using any of the following options: window.onhashchange = funcref; or <body onhashchange="funcref();"> or window.addeventlistener("hashchange", funcref, false); basic example function locationhashchanged() { if (location.hash === '#somecoolfeature') { somecoolfeature(); } } window.addeventlistener('hashchange', locationhashchanged); polyfill there are several fallback scripts listed on the moderniz...
Headers() - Web APIs
WebAPIHeadersHeaders
in the following snippet we create a new headers object, adding some headers by passing the constructor an init object as an argument: var httpheaders = { 'content-type' : 'image/jpeg', 'accept-charset' : 'utf-8', 'x-my-custom-header' : 'zeke are cool' }; var myheaders = new headers(httpheaders); you can now create another headers object, passing it the first headers object as its init object: var secondheader...
Headers.delete() - Web APIs
WebAPIHeadersdelete
this method throws a typeerror for the following reasons: the value of the name parameter is not the name of an http header.
Headers - Web APIs
WebAPIHeaders
examples in the following snippet, we create a new header using the headers() constructor, add a new header to it using append(), then return that header value using get(): var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.get('content-type') // should return 'text/xml' the same can be achieved by passing an array of arrays or an object literal to the constructor: var myheaders = ...
History.back() - Web APIs
WebAPIHistoryback
syntax history.back() examples the following short example causes a button on the page to navigate back one entry in the session history.
History.forward() - Web APIs
WebAPIHistoryforward
syntax history.forward() examples the following examples create a button that moves forward one step in the session history.
History.go() - Web APIs
WebAPIHistorygo
examples to move back one page (the equivalent of calling back()): history.go(-1) to move forward a page, just like calling forward(): history.go(1) to move forward two pages: history.go(2); to move backwards by two pages: history.go(-2); and, finally either of the following statements will reload the current page: history.go(); history.go(0); specifications specification status comment html living standardthe definition of 'history.go()' in that specification.
Ajax navigation example - Web APIs
to see how it works, please create the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): note: for fully integrating the <form> elements within this mechanism, please take a look at the paragraph submitting forms and uploading files.
IDBCursor.advance() - Web APIs
WebAPIIDBCursoradvance
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive.
IDBCursor.delete() - Web APIs
WebAPIIDBCursordelete
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive.
IDBCursor.update() - Web APIs
WebAPIIDBCursorupdate
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive.
IDBDatabase.deleteObjectStore() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction callback.
IDBDatabase - Web APIs
example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a new object store in the case that an upgrade is needed (idbdatabase).
IDBEnvironment - Web APIs
example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open("todolist"); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; }; } browser compatibility the compatibility table on this page is generated from structur...
IDBFactory.cmp() - Web APIs
WebAPIIDBFactorycmp
return value an integer that indicates the result of the comparison; the table below lists the possible values and their meanings: returned value description -1 1st key is less than the 2nd key 0 1st key is equal to the 2nd key 1 1st key is greater than the 2nd key exceptions this method may raise a domexception of the following types: attribute description dataerror one of the supplied keys was not a valid key.
databases - Web APIs
exceptions this method may raise a domexception of the following types: attribute description securityerror the method is called from an opaque origin.
IDBFactorySync - Web APIs
exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if the name parameter is not valid.
IDBIndex.getAll() - Web APIs
WebAPIIDBIndexgetAll
exceptions this method may raise a domexception of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive.
IDBIndex.getAllKeys() - Web APIs
exceptions this method may raise a domexception of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive.
IDBIndex.isAutoLocale - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.keyPath - Web APIs
WebAPIIDBIndexkeyPath
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.locale - Web APIs
WebAPIIDBIndexlocale
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.multiEntry - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.name - Web APIs
WebAPIIDBIndexname
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.objectStore - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.unique - Web APIs
WebAPIIDBIndexunique
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex - Web APIs
WebAPIIDBIndex
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBKeyRange.lower - Web APIs
WebAPIIDBKeyRangelower
syntax var lower = mykeyrange.lower value the lower bound of the key range (can be any type.) example the following example illustrates how you'd use a key range.
IDBKeyRange.lowerOpen - Web APIs
example the following example illustrates how you'd use a key range.
IDBKeyRange.upper - Web APIs
WebAPIIDBKeyRangeupper
syntax var upper = mykeyrange.upper value the upper bound of the key range (can be any type.) example the following example illustrates how you'd use a key range.
IDBKeyRange.upperOpen - Web APIs
example the following example illustrates how you'd use a key range.
IDBObjectStore.autoIncrement - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
IDBObjectStore.count() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore has been deleted.
IDBObjectStore.getAll() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive.
IDBObjectStore.getAllKeys() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive.
IDBObjectStore.getKey() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive.
IDBObjectStore.indexNames - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
IDBObjectStore.keyPath - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
IDBObjectStore.name - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
IDBObjectStore.openCursor() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore or idbindex has been deleted.
IDBObjectStore.openKeyCursor() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore or idbindex has been deleted.
IDBObjectStore.transaction - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
IDBOpenDBRequest.onupgradeneeded - Web APIs
}; example in the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
IDBOpenDBRequest - Web APIs
example in the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
IDBRequest.onerror - Web APIs
}; 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 into the object store.
IDBRequest.onsuccess - Web APIs
}; 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 into the object store.
IDBRequest.result - Web APIs
WebAPIIDBRequestresult
syntax var myresult = request.result; value any 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 into the object store.
IDBRequest.source - Web APIs
WebAPIIDBRequestsource
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 into the object store in another request.
IDBRequest - Web APIs
example in the following code snippet, we open a database asynchronously and make a request; onerror and onsuccess functions are included to handle the success and error cases.
IDBTransaction: abort event - Web APIs
bubbles yes cancelable no interface event event handler property onabort this can happen for any of the following reasons: bad requests, (for example, trying to add the same key twice, or put the same index key when the key has a uniqueness constraint), an explicit abort() call an uncaught exception in the request's success/error handler, an i/o error (an actual failure to write to disk, for example disk detached, or other os/hardware failure) quota exceeded.
IDBTransaction.db - Web APIs
WebAPIIDBTransactiondb
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.error - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.mode - Web APIs
transactions in this mode are known as "upgrade transactions." example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.onabort - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.oncomplete - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.onerror - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction - Web APIs
you should code defensively in case the object is not available anymore: var myidbtransaction = window.idbtransaction || window.webkitidbtransaction || { read_write: "readwrite" }; examples in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IIRFilterNode.getFrequencyResponse() - Web APIs
examples in the following example we are using an iir filter on a media stream (for a complete full demo, see our stream-source-buffer demo live, or read its source.) as part of this demo, we get the frequency responses for this iir filter, for five sample frequencies.
IIRFilterNode - Web APIs
it also has the following additional methods: getfrequencyresponse() uses the filter's current parameter settings to calculate the response for frequencies specified in the provided array of frequencies.
ImageCapture() constructor - Web APIs
example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor.
ImageCapture.getPhotoCapabilities() - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range.
ImageCapture - Web APIs
example the following code is taken from chrome's grab frame - take photo sample.
Browser storage limits and eviction criteria - Web APIs
in firefox, the following technologies make use of browser data storage to store data when required.
Checking when a deadline is due - Web APIs
when a notification is fired for each item object, its notification property is set to "yes" so this check will not pass on the next iteration, via the following code inside the createnotification() function (read using indexeddb for an explanation): // now we need to update the value of notified to "yes" in this particular data object, so the // notification won't be set off on it again // first open up a tranaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list o...
InputDeviceCapabilities - Web APIs
it contains the following property.
InputEvent() - Web APIs
inputeventinitoptional is a inputeventinit dictionary, having the following fields: inputtype: (optional) a string specifying the type of change for editible content such as, for example, inserting, deleting, or formatting text.
InputEvent.data - Web APIs
WebAPIInputEventdata
examples in the following simple example we've set up an event listener on the input event so that when any change is made to the contents of the <input> element (either by typing or pasting), the text that was added is retrieved via the inputevent.data property and reported in the paragraph below the input.
InputEvent.dataTransfer - Web APIs
examples in the following simple example we've set up an event listener on the input event so that when any content is pasted into the contenteditable <p> element, its html source is retrieved via the inputevent.datatransfer.getdata() method and reported in the paragraph below the input.
enabled - Web APIs
example the following code uses the startsoftwareupdate method to unconditionally trigger a download from http://royalairways/royalpkg.xpi as long as software installation is enabled on the browser: if (installtrigger.enabled() ) { installtrigger.startsoftwareupdate ("http://royalair.com/rasoft.xpi"); } ...
install - Web APIs
method of installtrigger object syntax int install(array xpilist [, function callbackfunc ] ) parameters the install method has the following parameters: xpilist an array of files to be installed (see example below).
installChrome - Web APIs
method of installtrigger object syntax int installchrome( type, url, name ) parameters the installchrome method has the following parameters: type type can be installtrigger.skin or installtrigger.locale.
startSoftwareUpdate - Web APIs
method of installtrigger object syntax boolean startsoftwareupdate ( string url); parameters the startsoftwareupdate method has the following parameter: url a uniform resource locator specifying the location of the xpi file containing the software.
InstallTrigger - Web APIs
the following is a basic example of an install trigger on a web page: xpi={'xpinstall dialog display name':'simple.xpi'}; installtrigger.install(xpi); you can also use the installtrigger object to install netscape 6/mozilla skins and language packs, and perform multiple-package installations with install.
IntersectionObserver.IntersectionObserver() - Web APIs
you can provide any combination of the following options: root an element or document object which is an ancestor of the intended target, whose bounding rectangle will be considered the viewport.
Keyboard.getLayoutMap() - Web APIs
example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard.
Keyboard - Web APIs
WebAPIKeyboard
example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard.
KeyboardEvent() - Web APIs
keyboardeventinitoptional is a keyboardeventinit dictionary, having the following fields: "key", optional and defaulting to "", of type domstring, that sets the value of keyboardevent.key.
KeyboardEvent.getModifierState() - Web APIs
example // ignore if following modifier is active.
KeyboardEvent.initKeyEvent() - Web APIs
the initkeyevent is the current gecko equivalent of the dom level 3 events (initially drafted and also deprecated in favor of keyboardevent() keyboard.initkeyboardevent() method with the following arguments : typearg of type domstring canbubblearg of type boolean cancelablearg of type boolean viewarg of type views::abstractview keyidentifierarg of type domstring keylocationarg of type unsigned long modifierslist of type domstring); ...
Key Values - Web APIs
the value of data will be one of the following: compositionevent.data value symbol comments gdk_key_dead_grave (0xfe50) qt::key_dead_grave (0x01001250) ` gdk_key_dead_acute (0xfe51) qt::key_dead_acute (0x01001251) ´ gdk_key_dead_circumflex (0xfe52) qt::key_dead_circumflex (0x01001252) ˆ gdk_key_dead_tilde (0xfe53) qt::key_dead_tilde (0x01001253) ...
KeyboardEvent.key - Web APIs
WebAPIKeyboardEventkey
try experimenting using the following two test cases: press and hold the shift key, then press 2 and release it.
KeyboardLayoutMap.get() - Web APIs
example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard.
KeyboardLayoutMap - Web APIs
examples the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard.
KeyframeEffect.KeyframeEffect() - Web APIs
keyframeoptions optional either an integer representing the animation's duration (in milliseconds), or an object containing one or more of the following: delay optional the number of milliseconds to delay the start of the animation.
KeyframeEffect.getKeyframes() - Web APIs
return value returns a sequence of objects with the following format: property value pairs as many property value pairs as are contained in each keyframe of the animation.
KeyframeEffect.setKeyframes() - Web APIs
the following special attributes may also be specified: offset the offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null.
LargestContentfulPaint - Web APIs
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.
LayoutShift - Web APIs
examples the following example shows how to capture layout shifts and log them to the console.
Location: origin - Web APIs
WebAPILocationorigin
containing the unicode serialization of the origin of the represented url; that is: for url using the http or https, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified); for url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:.
Locks.mode - Web APIs
WebAPILockmode
example the following examples show how the mode property is passed in the call to lockmanager.request().
Locks.name - Web APIs
WebAPILockname
example the following examples show how the name property passed in the call to lockmanager.request().
Lock - Web APIs
WebAPILock
examples the following examples show how the mode and name properties are passed in the call to lockmanager.request().
LockManager.query() - Web APIs
WebAPILockManagerquery
return value a promise that resolves with a lockmanagersnapshot containing the following properties.
MSCandidateWindowUpdate - Web APIs
tan ime candidate window may be identified as needing to change size for any of the following reasons: as a result of displaying new / changed alternatives or predictions web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element).
MediaDevices.getSupportedConstraints() - Web APIs
html <p>the following media constraints are supported by your browser:</p> <ul id="constraintlist"> </ul> css body { font: 15px arial, sans-serif; } javascript let constraintlist = document.getelementbyid("constraintlist"); let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); for (let constraint in supportedconstraints) { if (supportedconstraints.hasownproperty(constraint)) { let...
MediaList.mediaText - Web APIs
examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document.
MediaList - Web APIs
WebAPIMediaList
examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document.
MediaMetadata.MediaMetadata() - Web APIs
example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhand...
MediaQueryList - Web APIs
events the following events are delivered to mediaquerylist objects: change sent to the mediaquerylist when the result of running the media query against the document changes.
MediaRecorder() - Web APIs
options optional a dictionary object that can contain the following properties: mimetype: a mime type specifying the format for the resulting media; you may simply specify the container format (the browser will select its preferred codecs for audio and/or video), or you may use the codecs parameter and/or the profiles parameter to provide detailed information about which codecs to use and how to configure them.
MediaRecorder.mimeType - Web APIs
}) .catch(function(error) { console.log(error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible resource-constrained situations.
MediaRecorder.onerror - Web APIs
in addition to other general errors that might occur, the following errors are specifically possible when using the mediastream recording api; to determine which occurred, check the value of mediarecordererrorevent.error.name.
MediaRecorder.requestData() - Web APIs
when the requestdata() method is invoked, the browser queues a task that runs the following steps: if mediarecorder.state is not "recording", raise a dom invalidstate error and terminate these steps.
MediaRecorder.resume() - Web APIs
when the resume() method is invoked, the browser queues a task that runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps.
MediaRecorder.state - Web APIs
syntax var state = mediarecorder.state values a animationplaystate object containing one of the following values: enumeration description inactive recording is not occuring — it has either not been started yet, or it has been started and then stopped.
MediaRecorder.stop() - Web APIs
when the stop() method is invoked, the ua queues a task that runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps.
MediaRecorder - Web APIs
var audiourl = url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); deletebutton.onclick = function(e) { evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } }) .catch(function(err) { console.log('the following error occurred: ' + err); }) } this code sample is inspired by the web dictaphone demo.
MediaSession.metadata - Web APIs
example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhand...
MediaSession.setActionHandler() - Web APIs
the following strings identify the currently available types of media session action: nexttrack advances playback to the next track.
Media Session action types - Web APIs
the following strings identify the currently available types of media session action: nexttrack advances playback to the next track.
MediaSessionActionDetails - Web APIs
the following strings identify the currently available types of media session action: nexttrack advances playback to the next track.
MediaSettingsRange - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities().imagewidth to modify the size of an input range.
MediaSource.MediaSource() - Web APIs
example the following snippet is taken from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobje...
MediaSource.activeSourceBuffers - Web APIs
example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { ...
MediaSource.addSourceBuffer() - Web APIs
example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { ...
MediaSource.endOfStream() - Web APIs
their sourcebuffer.updating property is true.) example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { ...
MediaSource.isTypeSupported() - Web APIs
example the following snippet is from an example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var ...
MediaSource.readyState - Web APIs
example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', source...
MediaSource.sourceBuffers - Web APIs
example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); console.log(mediasource.sourcebuffers); // will contain the source buffer ...
MediaSource - Web APIs
examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can.
MediaStream.getVideoTracks() - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses getvideotracks() to retrieve a track for passing to the imagecapture() constructor.
MediaStreamAudioSourceNode() - Web APIs
iadevices.getusermedia ( // constraints: audio and video for this app { audio: true, video: false }).then(function(stream) { var options = { mediastream : stream } var source = new mediastreamaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported on your browser!'); } specifications specification status comment web audio apithe definition of 'mediastreamaudiosourcenode()' in that specification.
MediaStreamConstraints - Web APIs
properties some combination—but not necessarily all—of the following properties will exist on the object.
MediaStreamEvent() - Web APIs
mediastreameventinit is a mediastreameventinit dictionary, having the following fields: "stream" of type mediastream representing the stream being concerned by the event.
MediaStreamTrack.applyConstraints() - Web APIs
examples the following shows how to specify a basic and advanced set of constraints.
MediaStreamTrack.kind - Web APIs
syntax const type = track.kind value the possible values are a domstring with on of the following values: "audio": the track is an audio track.
MediaStreamTrack: mute event - Web APIs
the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'mute' in that specification.
MediaStreamTrack.readyState - Web APIs
syntax const state = track.readystate value it takes one of the following values: "live" which indicates that an input is connected and does its best-effort in providing real-time data.
MediaStreamTrack: unmute event - Web APIs
the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'unmute' in that specification.
MediaStreamTrack - Web APIs
this will be one of the following values: "live" which indicates that an input is connected and does its best-effort in providing real-time data.
MediaStreamTrackAudioSourceNode() - Web APIs
mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( { audio: true, video: false }).then(function(stream) { let options = { mediastreamtrack: stream.getaudiotracks()[0]; } let source = new mediastreamtrackaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported on your browser!'); } specifications specification status comment web audio apithe definition of 'mediastreamtrackaudiosourcenode()' in that specification.
MediaStreamTrackAudioSourceNode - Web APIs
music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; note: as a consequence of calling createmediastreamsource(), audio playback from the media stream will be re-routed into the processing graph of the audiocontext.
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( { audio: true, video: false }).then(function(stream) { let options = { mediastreamtrack: stream.getaudiotracks()[0]; } let source = new mediastreamtrackaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported on your browser!'); } specifications specification status comment web audio apithe definition of 'mediastreamtrackaudiosourceoptions.mediastream' in that specification.
MediaTrackConstraints.cursor - Web APIs
for example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertfakecursorflag = false; if (displaystream.getvideotracks()[0].getsettings().cursor === "never") { insertfakecursorflag = true; } following this code, insertfakecursorflag is true if there's no cursor rendered into the stream already.
MediaTrackConstraints.displaySurface - Web APIs
if your app needs to know that the surface being shared is a monitor or application—meaning that there's possibly a non-content backdrop—it can use code similar to this: let mayhavebackdropflag = false; let displaysurface = displaystream.getvideotracks()[0].getsettings().displaysurface; if (displaysurface === "monitor" || displaysurface ==="application") { mayhavebackdropflag = true; } following this code, mayhavebackdrop is true if the display surface contained in the stream is of type monitor or application; either of these may have non-content backdrop areas.
MediaTrackConstraints.facingMode - Web APIs
the following strings are permitted values for the facing mode.
MediaTrackConstraints.logicalSurface - Web APIs
for example, if your app needs to know if the selected display surface is a logical one: let islogicalsurface = displaystream.getvideotracks()[0].getsettings().logicalsurface; following this code, islogicalsurface is true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, or may even be entirely offscreen.
MediaTrackSettings.cursor - Web APIs
syntax cursorsetting = mediatracksettings.cursor; value the value of cursor comes from the cursorcaptureconstraint enumerated string type, and may have one of the following values: always the mouse should always be visible in the video content of the {domxref("mediastream"), unless the mouse has moved outside the area of the content.
MediaTrackSettings.displaySurface - Web APIs
syntax displaysurface = mediatracksettings.displaysurface; value the value of displaysurface is a string that comes from the displaycapturesurfacetype enumerated type, and is one of the following: application the stream's video track contains all of the windows belonging to the application chosen by the user.
MediaTrackSettings.facingMode - Web APIs
videofacingmodeenum the following strings are permitted values for the facing mode.
MerchantValidationEvent() - Web APIs
options optional an optional dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used.
MessageChannel() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessageChannel.port1 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel() constructor.
MessageChannel.port2 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessageChannel - Web APIs
example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessageEvent.MessageEvent() - Web APIs
this can be one of xxx init optional a dictionary object that can contain the following properties: data: the data you want contained in the messageevent.
MessageEvent - Web APIs
the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
MessagePort.close() - Web APIs
WebAPIMessagePortclose
example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using eventtarget.addeventlistener.
MessagePort.onmessage - Web APIs
}; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessagePort.postMessage() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessagePort.start() - Web APIs
WebAPIMessagePortstart
example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using onmessage: channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } another option would be to do this using eventtarget.addeventlistener, however, when this method is used, you need to explicitly call start() to begin the flow of messages to this document: channel.port1.addeventlistener('message...
MessagePort - Web APIs
example in the following example, you can see a new channel being created using the messagechannel() constructor.
MimeTypeArray - Web APIs
example the following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is.
MouseEvent() - Web APIs
mouseeventinit optional is a mouseeventinit dictionary, having the following fields: "screenx", optional and defaulting to 0, of type long, that is the horizontal position of the mouse event on the user's screen; setting this value doesn't move the mouse pointer.
MouseEvent.mozInputSource - Web APIs
syntax var source = instanceofmouseevent.mozinputsource; return value the following values are possible.
MouseEvent.screenX - Web APIs
yselector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result routing an event when you trap events on the window, document, or other roomy elements, you can get the coordinates of that event (e.g., a click) and route it properly, as the following example demonstrates: function checkclickmap(e) { if (e.screenx < 50) doredbutton(); if (50 <= e.screenx && e.screenx < 100) doyellowbutton(); if (e.screenx >= 100) doredbutton(); } specifications specification status comment css object model (cssom) view modulethe definition of 'screenx' in that specification.
msFirstPaint - Web APIs
example the following example shows how to calculate the time that is required to request the document before the document begins to display for the user.
MutationEvent - Web APIs
mutation events list the following is a list of all mutation events, as defined in dom level 3 events specification: domattrmodified domattributenamechanged domcharacterdatamodified domelementnamechanged domnodeinserted domnodeinsertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified usage you can register a listener for mutation events using eventtarget.addeventlistener() as follows: element...
MutationObserver.observe() - Web APIs
exceptions typeerror thrown in any of the following circumstances: the options are configured such that nothing will actually be monitored.
MutationObserver - Web APIs
mutation observer & customize resize event listener & demo https://codepen.io/webgeeker/full/yjrzgg/ example the following example was adapted from this blog post.
NDEFReader.scan() - Web APIs
WebAPINDEFReaderscan
exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: aborterror the scan operation was aborted with abortsignal passed in options.
NDEFRecord.encoding - Web APIs
syntax ndefrecord.encoding value a usvstring which can be one of the following: "utf-8", "utf-16", "utf-16le" or "utf-16be".
NDEFRecord.recordType - Web APIs
syntax ndefrecord.recordtype value a usvstring which can be one of the following: "empty" represents a empty ndef record.
NDEFWriter.write() - Web APIs
WebAPINDEFWriterwrite
exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: aborterror the write operation was aborted with abortsignal passed in options.
NavigationPreloadManager - Web APIs
await self.registration.navigationpreload.enable(); } }()); }); using a preloaded response the following example shows the implementation of a fetch event that uses a preloaded response.
Navigation Timing API - Web APIs
examples calculate the total page load time to compute the total amount of time it took to load the page, you can use the following code: const perfdata = window.performance.timing; const pageloadtime = perfdata.loadeventend - perfdata.navigationstart; this subtracts the time at which navigation began (navigationstart) from the time at which the load event handler returns (loadeventend).
Navigator.clipboard - Web APIs
examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard.
msSaveBlob - Web APIs
notes when a site calls this method, the behavior is the same as when windows internet explorer downloads a file with the following in the header, where x-download-options removes the file open button from the browser file download dialog: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> x-download-options: noopen specifications not part of any specifications.
msSaveOrOpenBlob - Web APIs
notes when a site calls this method, the behavior is the same as when windows internet explorer downloads a file with the following in the header: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> specifications not part of any specifications.
Navigator.registerProtocolHandler() - Web APIs
otherwise, the scheme must be one of the following: bitcoin geo im irc ircs magnet mailto mms news nntp openpgp4fpr sip sms smsto ssh tel urn webcal wtai xmpp example if your site is burgers.example.com, you can register a protocol handler for it to handle web+burger: links, like so: navigator.registerprotocolhandler("web+burger", "https://burgers.example.com/?burger=%s", ...
Navigator.share() - Web APIs
WebAPINavigatorshare
at least one of the following fields must be specified.
NavigatorID.userAgent - Web APIs
gecko-based browsers comply with the following general structure: useragent = appcodename/appversion number (platform; security; os-or-cpu; localization; rv: revision-version-number) product/productsub application-name application-name-version example alert(window.navigator.useragent) // alerts "mozilla/5.0 (windows; u; win98; en-us; rv:0.9.2) gecko/20010725 netscape6/6.1" specifications specification status comment ...
NetworkInformation.downlinkMax - Web APIs
examples the following example monitors the connection using the change event and logs changes as they occur.
NetworkInformation.type - Web APIs
syntax var type = netinfo.type return value an enumerated value that is one of the following values: "bluetooth" "cellular" "ethernet" "none" "wifi" "wimax" "other" "unknown" specifications specification status comment network information apithe definition of 'type' in that specification.
NetworkInformation - Web APIs
it will be one of the following values: bluetooth cellular ethernet none wifi wimax other unknown event handlers networkinformation.onchange the event that's fired when connection information changes and the change is fired on this object.
Node.isConnected - Web APIs
WebAPINodeisConnected
y: inline-block; border: 1px solid black; padding: 10px; background: white; border-radius: 10px; opacity: 0; transition: 0.6s all; positions: absolute; bottom: 20px; left: 10px; z-index: 3 } `; // attach the created style element to the shadow dom shadow.appendchild(style); console.log(style.isconnected); // returns true polyfill node.isconnected can be polyfilled with the following code for ie10 and edgehtml: /* * node.isconnected polyfill for ie and edgehtml * 2020-02-04 * * by eli grey, https://eligrey.com * public domain.
Node.nodeName - Web APIs
WebAPINodenodeName
mentfragment "#document-fragment" documenttype the value of documenttype.name element the value of element.tagname entity the entity name entityreference the name of entity reference notation the notation name processinginstruction the value of processinginstruction.target text "#text" example given the following markup: <div id="d1">hello world</div> <input type="text" id="t"> and the following script: var div1 = document.getelementbyid("d1"); var text_field = document.getelementbyid("t"); text_field.value = div1.nodename; in xhtml (or any other xml format), text_field's value would read "div".
Node.nodeType - Web APIs
WebAPINodenodeType
deprecated node type constants the following constants have been deprecated and should not be used anymore.
Node.nodeValue - Web APIs
WebAPINodenodeValue
the following table shows the return values for different elements: node value of nodevalue cdatasection content of the cdata section comment content of the comment document null documentfragment null documenttype null element null namednodemap null entityreference null notation null...
Node.prefix - Web APIs
WebAPINodeprefix
syntax string = node.prefix examples the following logs "x" to the console.
Node.rootNode - Web APIs
WebAPINoderootNode
example running the following line in supporting browsers should return a reference to the html/document node: console.log(document.body.rootnode); notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup.
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
cument.createelement("p"); let kid2 = document.createtextnode("hey"); let kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); let list = node.childnodes; list.foreach( function(currentvalue, currentindex, listobj) { console.log(currentvalue + ', ' + currentindex + ', ' + this); }, 'mythisarg' ); the above code results in the following: [object htmlparagraphelement], 0, mythisarg [object text], 1, mythisarg [object htmlspanelement], 2, mythisarg polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = function (callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) { ...
NonDocumentTypeChildNode - Web APIs
nondocumenttypechildnode.nextelementsibling read only returns the element immediately following this node in its parent's children list, or null if there is no element in the list following this node.
Notification.data - Web APIs
WebAPINotificationdata
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.dir - Web APIs
WebAPINotificationdir
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.lang - Web APIs
WebAPINotificationlang
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.maxActions - Web APIs
examples the following snippet logs the maximum number of supported actions.
Notification.onclick - Web APIs
examples in the following example, we use an onclick handler to open a webpage in a new tab (specified by the inclusion of the '_blank' parameter) once a notification is clicked: notification.onclick = function(event) { event.preventdefault(); // prevent the browser from focusing the notification's tab window.open('http://www.mozilla.org', '_blank'); } specifications specification status comment ...
Notification.permission - Web APIs
examples the following snippet could be used if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
Notification.renotify - Web APIs
examples the following snippet is intended to fire a notification that renotifies the user after it has been replaced; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.silent - Web APIs
examples the following snippet is intended to fire a silent notification; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.timestamp - Web APIs
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.vibrate - Web APIs
examples the following snippet is intended to create a notification that also triggers a device vibration; a simple options object is created, and then the notification is fired using the notification() constructor.
Notifications API - Web APIs
this will spawn a request dialog, along the following lines: from here the user can choose to allow notifications from this origin, or block them.
OES_standard_derivatives - Web APIs
glsl built-in functions the following new functions can be used in glsl shader code, if this extension is enabled: gentype dfdx(gentype) gentype dfdy(gentype) gentype fwidth(gentype) examples enabling the extensions: gl.getextension('oes_standard_derivatives'); gl.getextension('ext_shader_texture_lod'); shader code that avoids artifacts when wrapping texture coordinates: <script type="x-shader/x-fragment"> #extension gl_ext_sh...
OfflineAudioContext.resume() - Web APIs
exceptions the promise is rejected when the following exception is encountered.
OfflineAudioContext.suspend() - Web APIs
invalidstateerror if the quantized frame number is one of the following: a negative number is less than or equal to the current time is greater than or equal to the total render duration is scheduled by another suspend for the same time specifications specification status comment web audio apithe definition of 'suspend()' in that specification.
OffscreenCanvas - Web APIs
given these two <canvas> elements <canvas id="one"></canvas> <canvas id="two"></canvas> the following code will provide the rendering using an offscreencanvas as described above.
OrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second.
OscillatorNode.detune - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
OscillatorNode.frequency - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
OscillatorNode.onended - Web APIs
}; example the following example shows basic usage of an audiocontext to create an oscillator node.
OscillatorNode.setPeriodicWave() - Web APIs
returns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave.
OscillatorNode.start() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
OscillatorNode.stop() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
OscillatorNode.type - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
PaintWorklet.registerPaint - Web APIs
examples the following shows registering an example worklet module.
PannerNode.distanceModel - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
PannerNode.maxDistance - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
PannerNode.panningModel - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
PannerNode.positionX - Web APIs
example the following example starts an oscillator, and pans it to the left after 1 second, to the right after 2 seconds, and back to the center after 3 seconds.
PannerNode.positionY - Web APIs
example the following example starts an oscillator and pans it above the listener after 1 second, below the listener after 2 seconds, and back to the center after 3 seconds.
PannerNode.positionZ - Web APIs
example the following example starts an oscillator and moves it in front of the listener after 1 second, behind the listener after 2 seconds, and back to the listener's position after 3 seconds.
PannerNode.setOrientation() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
PannerNode.setPosition() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
PannerNode.setVelocity() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
PannerNode - Web APIs
examples in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
ParentNode.append() - Web APIs
WebAPIParentNodeappend
let parent = document.createelement("div") with(parent) { append("foo") } // referenceerror: append is not defined polyfill you can polyfill the append() method in internet explorer 9 and higher with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { return; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argarr = array.prototype.sl...
PasswordCredential - Web APIs
syntax var mycredential = new passwordcredential(passwordcredentialdata) var mycredential = new passwordcredential(htmlformelement) parameters either of the following: passwordcredentialdata a passwordcredentialdata dictionary containing the following fields: iconurl: (optional) the url of a user's avatar image.
PasswordCredential.additionalData - Web APIs
example the following example creates a formdata object with an appended csrf token.
PaymentAddress.addressLine - Web APIs
for example, the addressline array for the mozilla space in london would have the following entries: example showing addressline entries for an address in london index addressline[] value 0 metal box factory 1 suite 441, 4th floor 2 30 great guildford street these, combined with additional values for other properties of the paymentaddress, would represent the full address, which is: mozilla metal box factory suite 441, 4th ...
PaymentCurrencyAmount.value - Web APIs
this must be a valid decimal number, with an optional leading minus sign ("-"), then one or more decimal digits 0 through 9, optionally with a decimal point (".") with at least one digit following it to represent fractional units.
PaymentDetailsBase - Web APIs
derived dictionaries the following dictionaries include paymentdetailsbase.
PaymentDetailsUpdate.error - Web APIs
this happens if both of the following are true: the paymentrequest specifies using its requestshipping property that shipping information is required.
PaymentMethodChangeEvent - Web APIs
options optional an optional paymentmethodchangeeventinit dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used.
PaymentRequest.abort() - Web APIs
parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected.
PaymentRequest.canMakePayment() - Web APIs
parameters none examples in the following example, is excerpted from a demo that asynchronously builds a paymentrequest object for both apple pay and credit cards.
PaymentRequestUpdateEvent - Web APIs
methods in addition to methods inherited from the parent interface, event, paymentrequestupdateevent offers the following methods: paymentrequestupdateevent.updatewith() secure context if the event handler determines that information included in the payment request needs to be changed, or that new information needs to be added, it calls updatewith() with the information that needs to be replaced or added.
PaymentResponse.details - Web APIs
syntax var detailsobject = paymentresponse.details; example the following example extracts the details from the paymentresponse object to the promise returned from paymentrequest.show().
PaymentResponse.methodName - Web APIs
example the following example extracts the method name from the paymentresponse object to the promise returned from paymentrequest.show().
PaymentResponse.retry() - Web APIs
syntax retrypromise = paymentrequest.retry(errorfields); parameters errorfields a paymentvalidationerrors object, with the following properties: error optional a general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information.
Payment Request API - Web APIs
paymentdetailsupdate an object describing changes that need to be made to the payment details in the event that the server needs to update information following the instantiation of the payment interface but before the user begins to interact with it.
performance.clearMarks() - Web APIs
return value void example the following example shows both uses of the clearmarks() method.
performance.clearMeasures() - Web APIs
return value void example the following example shows both uses of the clearmeasures() method.
performance.mark() - Web APIs
WebAPIPerformancemark
return value void example the following example shows how to use mark() to create and retrieve performancemark entries.
performance.now() - Web APIs
WebAPIPerformancenow
bear in mind the following points: in dedicated workers created from a window context, the value in the worker will be lower than performance.now() in the window who spawned that worker.
Performance.onresourcetimingbufferfull - Web APIs
examples the following example sets a callback function on the onresourcetimingbufferfull property.
Performance: resourcetimingbufferfull event - Web APIs
bubbles yes cancelable yes interface event event handler property onresourcetimingbufferfull examples the following example sets a callback function on the onresourcetimingbufferfull property.
PerformanceEntry.duration - Web APIs
example the following example shows the use of the duration property.
PerformanceEntry.entryType - Web APIs
longtask performancelongtasktiming domstring reports instances of long tasks example the following example shows the use of the entrytype property.
PerformanceEntry.name - Web APIs
example the following example shows the use of the name property.
PerformanceEntry.startTime - Web APIs
example the following example shows the use of the starttime property.
PerformanceEntry.toJSON() - Web APIs
example the following example shows the use of the tojson() method.
PerformanceEventTiming - Web APIs
examples the following example shows how to use the api for all events: const observer = new performanceobserver(function(list) { const perfentries = list.getentries().foreach(entry => { // full duration const inputduration = entry.duration; // input delay (before processing event) const inputdelay = entry.processingstart - entry.starttime; // synchronous event processing ti...
PerformanceFrameTiming - Web APIs
h="220" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="111" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performanceframetiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties (for "frame" performance entry types) by qualifying and constraining the properties as follows: performanceentry.entrytype returns "frame".
PerformanceMark - Web APIs
1" width="150" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="276" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancemark</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties by qualifying/constraining the properties as follows: performanceentry.entrytype returns "mark".
PerformanceMeasure - Web APIs
width="180" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="291" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancemeasure</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties by qualifying/constrainting the properties as follows: performanceentry.entrytype returns "measure".
PerformanceNavigation.type - Web APIs
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.
PerformanceNavigation - Web APIs
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.
PerformanceNavigationTiming.domComplete - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.domInteractive - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.loadEventEnd - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.loadEventStart - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.redirectCount - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.unloadEventEnd - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.unloadEventStart - Web APIs
example the following example illustrates this property's usage.
PerformanceObserver.observe() - Web APIs
syntax observer.observe(options); parameters options a performanceobserverinit dictionary with the following possible members: entrytypes: an array of domstring objects, each specifying one performance entry type to observe.
PerformanceObserverEntryList.getEntries() - Web APIs
syntax general syntax: entries = list.getentries(); entries = list.getentries(performanceentryfilteroptions); specific usage: entries = list.getentries({name: "entry_name", entrytype: "mark"}); parameters performanceentryfilteroptionsoptional is a performanceentryfilteroptions dictionary, having the following fields: "name", the name of a performance entry.
PerformanceResourceTiming.connectEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.connectStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.decodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged.
PerformanceResourceTiming.domainLookupEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.domainLookupStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.encodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged.
PerformanceResourceTiming.fetchStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.nextHopProtocol - Web APIs
example the following example uses the nexthopprotocol property.
PerformanceResourceTiming.redirectEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.redirectStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.requestStart - Web APIs
syntax resource.requeststart; return value a domhighrestimestamp representing the time immediately before the browser starts requesting the resource from the server example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.responseEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.responseStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.secureConnectionStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.transferSize - Web APIs
example the following example, the value of size properties of all "resource" type events are logged.
PerformanceResourceTiming.workerStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
Performance API - Web APIs
the navigation property returns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the page was navigated to from history, the page was navigated to by following a link, etc.
Performance Timeline - Web APIs
this interface has the following four properties, and these properties are extended (with additional constraints) by other interfaces (such as performancemark): name the name of the performance entry when the metric was created.
PeriodicWave - Web APIs
example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave.
Using the Permissions API - Web APIs
see the following code in our demo: var revokebtn = document.queryselector('.revoke'); ...
PhotoCapabilities - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range.
PointerEvent.PointerEvent() - Web APIs
pointereventinitoptional is a pointereventinit dictionary, having the following fields: pointerid — optional and defaulting to 0, of type long, that sets the value of the instance's pointerevent.pointerid.
PointerEvent.pointerId - Web APIs
example the following code snippet compares a previously saved pointerid with the one of the pointerdown event that was just fired.
PointerEvent.pointerType - Web APIs
the supported values are the following strings: "mouse" the event was generated by a mouse device.
Pointer Lock API - Web APIs
pointer lock is different from mouse capture in the following ways: it is persistent: pointer lock does not release the mouse until an explicit api call is made or the user uses a specific release gesture.
Multi-touch interaction - Web APIs
// log events flag var logevents = false; // event caches, one per touch target var evcache1 = new array(); var evcache2 = new array(); var evcache3 = new array(); register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup.
Pinch zoom gestures - Web APIs
// global vars to cache event state var evcache = new array(); var prevdiff = -1; register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup.
PopStateEvent - Web APIs
the popstate event as an example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?p...
ProgressEvent.initProgressEvent() - Web APIs
the following values are allowed: value meaning loadstart the operation has started.
ProgressEvent - Web APIs
examples the following example adds a progressevent to a new xmlhttprequest and uses it to display the status of the request.
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
syntax authenticatorselection = publickeycredentialcreationoptions.authenticatorselection value an object with the following properties: authenticatorattachmentoptional a string which is either "platform" or "cross-platform".
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
syntax excludecredentials = publickeycredentialcreationoptions.excludecredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
syntax pubkeycredparams = publickeycredentialcreationoptions.pubkeycredparams value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
syntax allowcredentials = publickeycredentialrequestoptions.allowcredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
PushEvent.data - Web APIs
WebAPIPushEventdata
examples the following example takes data from a pushevent and displays it on all of the service workers' clients.
PushEvent - Web APIs
WebAPIPushEvent
examples the following example takes data from a pushevent and displays it on all of the service worker's clients.
PushManager.permissionState() - Web APIs
it can have the following properties: uservisibleonly: a boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.
PushManager.registrations() - Web APIs
pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the endpoint.
PushManager.subscribe() - Web APIs
it can have the following properties: uservisibleonly: a boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.
PushManager.unregister() - Web APIs
pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the unregistered endpoint.
PushSubscription.options - Web APIs
syntax var options = pushsubscription.options value an read-only options object containing the following values: uservisibleonly: a boolean, indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
options a dictionary of type rtcdtmftonechangeeventinit, which may contain one or more of the following fields: tone a domstring containing a single dtmf tone character which has just begun to play, or an empty string ("") to indicate that the previous tone has stopped playing.
RTCDTMFToneChangeEvent - Web APIs
properties in addition to the properties of event, this interface offers the following: rtcdtmftonechangeevent.tone read only a domstring specifying the tone which has begun playing, or an empty string ("") if the previous tone has finished playing.
RTCDataChannelEvent() - Web APIs
rtcdatachanneleventinit a rtcdatachanneleventinit dictionary, which has following fields: "channel" of type rtcdatachannel, representing the data channel being concerned by the event.
RTCDtlsTransport.state - Web APIs
its value is one of the following: new the initial state when dtls has not started negotiating yet.
RTCError - Web APIs
WebAPIRTCError
properties in addition to the properties defined by the parent interface, domexception, rtcerror includes the following properties: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred.
RTCErrorEvent - Web APIs
properties in addition to the standard properties available on the event interface, rtcerrorevent also includes the following: error read only an rtcerror object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the sdp or what sctp cause code was at issue).
RTCIceCandidate.RTCIceCandidate() - Web APIs
the following fields are initialized to null if they are not included in the rtcicecandidate.candidate property: foundation, component, priority , ip, protocol, port, type, tcptype, relatedaddress, and relatedport.
RTCIceCandidate.relatedAddress - Web APIs
here's an sdp attribute line (a-line) describing an ice candidate discovered by the stun server: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 6502 typ srflx raddr 192.168.2.77 rport 32768 generation 0 the remote address, relatedaddress, is the dotted quad (for ipv4) or colon-delineated 64-bit address (for ipv6) immediately following the text "raddr", or "192.168.2.77".
RTCIceCandidate.relatedPort - Web APIs
here's an sdp attribute line (a-line) describing an ice candidate discovered by the stun server: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 6502 typ srflx raddr 192.168.2.77 rport 32768 generation 0 the remote port, relatedport, is the number immediately following the "rport" label on the a-line, or 32768.
RTCIceCandidatePairStats.availableOutgoingBitrate - Web APIs
the returned value is undefined in each of the following situations: the underlying implementation doesn't support computing a sender-side estimate of the outgoing bit rate.
RTCIceCandidatePairStats.circuitBreakerTriggerCount - Web APIs
a 5-tuple defining a tcp connection is made up of the following data: the source ip address.
RTCIceCandidateStats.priority - Web APIs
the priority of a candidate is calculated using the following variables as inputs: the preferability of the candidate type (local, server reflexive, peer reflexive, or relayed) the preferability of the candidate's specific ip address (for multihomed agents) the candidate's component id (1 for rtp, 2 for rtcp) the candidate's priority is computed using the formula (ptype is the priority of the candidate's type and plocal is the priority of the ip addr...
RTCIceCredentialType - Web APIs
obsolete values the following values are no longer part of the webrtc specification, but were in the past.
RTCIceServer - Web APIs
obsolete properties the following properties have been removed from the specification and should not be used.
RTCIceTransport.state - Web APIs
its value will be one of the following: "new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both.
RTCIceTransport: statechange event - Web APIs
bubbles no cancelable no interface event event handler property rtcicetransport.onstatechange examples given an rtcpeerconnection, pc, the following code creates an event handler that calls a function named handlefailure() if the ice transport enters a failure state.
RTCIceTransport - Web APIs
it also offers the following properties: component read only the ice component being used by the transport.
RTCIdentityErrorEvent.idp - Web APIs
firefox implements the interface of this property under the following name: rtcpeerconnectionidentityerrorevent.
RTCIdentityErrorEvent.loginUrl - Web APIs
firefox implements the interface of this property under the following name: rtcpeerconnectionidentityerrorevent.
RTCIdentityErrorEvent - Web APIs
firefox implements this interface under the following name: rtcpeerconnectionidentityerrorevent.
RTCIdentityEvent.assertion - Web APIs
firefox implements the interface this property belongs to under the following name: rtcpeerconnectionidentityevent.
RTCIdentityEvent - Web APIs
firefox implements this interface under the following name: rtcpeerconnectionidentityevent.
RTCInboundRtpStreamStats.averageRtcpInterval - Web APIs
this interval is computed following the formula outlined in rfc 1889: a.7.
RTCNetworkType - Web APIs
this type is used as the value or the following properties: rtcicecandidate's networktype rtcstunserverconnectionstats's networktype values bluetooth a bluetooth connection is used by the described connection.
RTCOutboundRtpStreamStats.averageRtcpInterval - Web APIs
this interval is computed following the formula outlined in rfc 1889: a.7.
RTCOutboundRtpStreamStats - Web APIs
properties the rtcoutboundrtpstreamstats dictionary includes the following properties in addition to those it inherits from rtcsentrtpstreamstats, rtcrtpstreamstats, and rtcstats.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
example var pc = new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice.
RTCPeerConnection.connectionState - Web APIs
constant description "new" at least one of the connection's ice transports (rtcicetransports or rtcdtlstransports) are in the "new" state, and none of them are in one of the following states: "connecting", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state.
RTCPeerConnection.createDataChannel() - Web APIs
options optional an rtcdatachannelinit dictionary providing configuration options for the data channel rtcdatachannelinit dictionary the rtcdatachannelinit dictionary provides the following fields, any of which may be included in the object passed as the options parameter in order to configure the data channel to suit your needs: ordered optional indicates whether or not messages sent on the rtcdatachannel are required to arrive at their destination in the same order in which they were sent (true), or if they're allowed to arrive out-of-order (false).
RTCPeerConnection.getStats() - Web APIs
exceptions this method does not throw exceptions; instead, it rejects the returned promise with one of the following errors: invalidaccesserror there is no rtcrtpsender or rtcrtpreceiver whose track matches the specified selector, or selector matches more than one sender or receiver.
RTCPeerConnection.getStreamById() - Web APIs
example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not natively available.
RTCPeerConnection.getTransceivers() - Web APIs
example the following snippet of code stops all transceivers associated with an rtcpeerconnection.
RTCPeerConnection: icecandidateerror event - Web APIs
example the following example establishes a handler for icecandidateerrors that occur on the rtcpeerconnection pc.
RTCPeerConnection.setLocalDescription() - Web APIs
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 place.
RTCPeerConnectionIceErrorEvent - Web APIs
properties the rtcpeerconnectioniceerrorevent interface includes the properties found on the event interface, as well as the following properties: address read only a domstring providing the local ip address used to communicate with the stun or turn server being used to negotiate the connection, or null if the local ip address has not yet been exposed as part of a local ice candidate.
RTCPeerConnectionIceEvent() - Web APIs
options a dictionary of type rtcpeerconnectioninit, which may contain one or more of the following fields: "candidate" (optional, default is null): a rtcicecandidate representing the ice candidate being concerned by the event.
RTCRemoteOutboundRtpStreamStats - Web APIs
properties in addition to the properties defined by rtcsentrtpstreamstats and its underlying rtcrtpstreamstats and rtcstats dictionaries, rtcremoteoutboundrtpstreamstats defines the following properties.
RTCRtpSender.replaceTrack() - Web APIs
exceptions if the returned promise is rejected, one of the following exceptions is provided to the rejection handler: invalidmodificationerror replacing the rtcrtpsender's current track with the new one would require negotiation.
RTCRtpSender.setParameters() - Web APIs
invalidmodificationerror one of the following problems was detected: the number of encodings specified in the parameters object's encodings property does not match the number of encodings currently listed for the rtcrtpsender.
RTCRtpTransceiver.direction - Web APIs
exceptions when setting the value of direction, the following exceptions can occur: invalidstateerror either the receiver's rtcpeerconnection is closed or the rtcrtpreceiver is stopped.
RTCRtpTransceiver.setCodecPreferences() - Web APIs
the following code snippet demonstrates how to get both the list of codecs supported by the transceiver's rtcrtpsender and rtcrtpreceiver.
RTCSctpTransport.state - Web APIs
its value is one of the following: connecting the initial state when the connection is being estabilished.
RTCSessionDescription.toJSON() - Web APIs
syntax var jsonvalue = sd.tojson(); the result value is a json object containing the following values: "type", containing the value of the rtcsessiondescription.type property and can be one of the following values: "offer", "answer", "pranswer" or null.
RTCTrackEvent() - Web APIs
this object has the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media.
RTCTrackEventInit - Web APIs
properties rtctrackeventinit inherits properties from the eventinit dictionary, and also includes the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media.
Range.compareNode() - Web APIs
WebAPIRangecompareNode
the following function can be used as replacement: function rangecomparenode(range, node) { var noderange = node.ownerdocument.createrange(); try { noderange.selectnode(node); } catch (e) { noderange.selectnodecontents(node); } var nodeisbefore = range.compareboundarypoints(range.start_to_start, noderange) == 1; var nodeisafter = range.compareboundarypoints(range.end_to_end, noderange) =...
Range.setEnd() - Web APIs
WebAPIRangesetEnd
exceptions exceptions are thrown as domexception objects of the following types: invalidnodetypeerror the node specified by endnode is a doctype node; range endpoints cannot be located inside a doctype node.
ReadableStream.getReader() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
ReadableStream.pipeThrough() - Web APIs
examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream.
ReadableStream.tee() - Web APIs
examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui.
ReadableStreamDefaultController.close() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStreamDefaultController.enqueue() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStreamDefaultController - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
ReadableStreamDefaultReader.cancel() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
RelativeOrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an relativeorientationsensor with a frequency of 60 times a second.
Reporting API - Web APIs
available report types the spec defines the following report types: deprecation report indicates that a webapi or other browser feature being used in the website is expected to stop working in a future release.
Request() - Web APIs
WebAPIRequestRequest
note the following behavioural updates to retain security while making the constructor less likely to throw exceptions: if this object exists on another origin to the constructor call, the request.referrer is stripped out.
Request.clone() - Web APIs
WebAPIRequestclone
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request.
Request.context - Web APIs
WebAPIRequestcontext
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request context in a variable: var myrequest = new request('flowers.jpg'); var mycontext = myrequest.context; // returns the empty string by default ...
Request.credentials - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentia...
Request.destination - Web APIs
example in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in tha...
Request.headers - Web APIs
WebAPIRequestheaders
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request headers in a variable: var myrequest = new request('flowers.jpg'); var myheaders = myrequest.headers; // headers {} to add a header to the headers object we use headers.append; we then create a new request along with a 2nd init parameter, passing headers in as an init option: var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default'...
Request.integrity - Web APIs
WebAPIRequestintegrity
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request integrity value in a variable: var myrequest = new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification.
Request.method - Web APIs
WebAPIRequestmethod
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification.
Request.mode - Web APIs
WebAPIRequestmode
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification.
Request.referrer - Web APIs
WebAPIRequestreferrer
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification.
Request.referrerPolicy - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe definition of 'referrerp...
Request.url - Web APIs
WebAPIRequesturl
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest = new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification.
ResizeObserver() - Web APIs
the callback will generally follow a pattern along the lines of: function(entries, observer) { for (let entry of entries) { // do something to each entry // and possibly something to the observer itself } } examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.styl...
ResizeObserver.observe() - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.styl...
ResizeObserver.unobserve() - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.conte...
ResizeObserverEntry.contentBoxSize - Web APIs
examples the following snippet is taken from the resize-observer-border-radius.html (see source) example.
ResizeObserverEntry.contentRect - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example.
ResizeObserverEntry.target - Web APIs
examples the following snippet is taken from the resize-observer-border-radius.html (see source) example.
ResizeObserverEntry - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example.
Response.type - Web APIs
WebAPIResponsetype
it can be one of the following: basic: normal, same origin response, with all headers exposed except “set-cookie” and “set-cookie2″.
Screen.availHeight - Web APIs
in the main window, when it's time to open the panels, code like the following is used.
Screen.lockOrientation() - Web APIs
the following strings represent the possible orientation requirements you may specify: portrait-primary it represents the orientation of the screen when it is in its primary portrait mode.
ScreenOrientation.lock() - Web APIs
one of the following: "any" "natural" "landscape" "portrait" "portrait-primary" "portrait-secondary" "landscape-primary" "landscape-secondary" return value a promise.
Using the Screen Capture API - Web APIs
using await, the following line of code does not get executed until after the promise returned by getdisplaymedia() resolves.
ScriptProcessorNode.bufferSize - Web APIs
example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode.
ScriptProcessorNode.onaudioprocess - Web APIs
} example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode.
ScriptProcessorNode - Web APIs
examples the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode.
ScrollToOptions.behavior - Web APIs
syntax behavior: scrollbehavior value an enum, the value of which can be one of the following: smooth: the scrolling animates smoothly.
ScrollToOptions - Web APIs
a scrolltooptions dictionary can be provided as a parameter for the following methods: window.scroll() window.scrollby() window.scrollto() element.scroll() element.scrollby() element.scrollto() properties scrolltooptions.top specifies the number of pixels along the y axis to scroll the window or element.
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
this can include the following properties, but bear in mind that if you do include an eventinitdict, certain properties must be included (marked below with required): blockeduri: the blockeduri of the securitypolicyviolationevent.
Selection.modify() - Web APIs
WebAPISelectionmodify
note: starting in gecko 5.0, the "word" granularity no longer includes the following space, regardless of the default platform behavior.
Selection.rangeCount - Web APIs
syntax value = sel.rangecount example the following example will show the rangecount every second.
Selection - Web APIs
WebAPISelection
the above behavior applies to selections made using the following methods: selection.collapse() selection.collapsetostart() selection.collapsetoend() selection.extend() selection.selectallchildren() selection.addrange() selection.setbaseandextent() and when the range is modified using the following methods: range.setstart() range.setend() range.setstartbefore() range.setstartafter() range.setendbefore() range.setendafter() range.collapse() ...
ServiceWorker.state - Web APIs
it can be one of the following values: installing, installed, activating, activated, or redundant.
ServiceWorker - Web APIs
it returns one of the following values: installing, installed, activating, activated, or redundant.
ServiceWorkerGlobalScope: activate event - Web APIs
bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.onactivate examples the following snippet shows how you could use an activate event handler to upgrade a cache.
ServiceWorkerGlobalScope: contentdelete event - Web APIs
bubbles no cancelable no interface contentindexevent event handler property oncontentdelete examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item.
ServiceWorkerGlobalScope: install event - Web APIs
bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.oninstall examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', ...
ServiceWorkerGlobalScope.onactivate - Web APIs
}; examples the following snippet shows how you could use an activate event handler to upgrade a cache.
ServiceWorkerGlobalScope.oncontentdelete - Web APIs
}; examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item.
ServiceWorkerGlobalScope.oninstall - Web APIs
}; examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', ...
ServiceWorkerGlobalScope.onpush - Web APIs
}) example the following example takes data from a pushevent and displays it on all of the service worker's clients.
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
the following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker.
ServiceWorkerGlobalScope - Web APIs
therefore it also has the following property available to it: globalfetch.fetch() starts the process of fetching a resource.
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
init optional an initialisation object, which should contain the following parameters: data: the event's data — this can be any type.
ServiceWorkerMessageEvent.data - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.lastEventId - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.origin - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.ports - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.source - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerRegistration.unregister() - Web APIs
example the following simple example registers a service worker example, but then immediately unregisters it again: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); registration.unregister().then(function(boolean) { // if boolean = true, unregister ...
ServiceWorkerRegistration.update() - Web APIs
example the following simple example registers a service worker example then adds an event handler to a button so you can explicitly update the service worker whenever desired: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); button.onclick = function() {...
Service Worker API - Web APIs
download, install and activate at this point, your service worker will observe the following lifecycle: download install activate the service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.
SharedWorker() - Web APIs
examples the following code snippet shows creation of a sharedworker object using the sharedworker() constructor and subsequent usage of the object: var myworker = new sharedworker('worker.js'); myworker.port.start(); first.onchange = function() { myworker.port.postmessage([first.value,second.value]); console.log('message posted to worker'); } second.onchange = function() { myworker.port.postmessage([first.va...
SharedWorker.port - Web APIs
WebAPISharedWorkerport
example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
SharedWorker - Web APIs
the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
SharedWorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope.
Slottable - Web APIs
WebAPISlottable
the slottable mixin defines features that allow nodes to become the contents of a <slot> element — the following features are included in both element and text.
SourceBuffer.appendWindowEnd - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer.appendWindowStart - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer.mode - Web APIs
WebAPISourceBuffermode
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer.timestampOffset - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer.trackDefaults - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer - Web APIs
examples the following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can.
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
examples the following snippet is excerpted from our speech synthesizer demo.
SpeechSynthesisVoice - Web APIs
examples the following snippet is excerpted from our speech synthesiser demo.
Storage.clear() - Web APIs
WebAPIStorageclear
examples the following function creates three data entries in local storage, and then deletes them by using clear().
Storage.getItem() - Web APIs
WebAPIStoragegetItem
example the following function retrieves three data items from local storage, then uses them to set custom styles on a page.
Storage.key() - Web APIs
WebAPIStoragekey
examples the following function iterates over the local storage keys: function foreachkey(callback) { for (var i = 0; i < localstorage.length; i++) { callback(localstorage.key(i)); } } the following function iterates over the local storage keys and gets the value set for each key: for(var i =0; i < localstorage.length; i++){ console.log(localstorage.getitem(localstorage.key(i))); } note: for a real world...
Storage.length - Web APIs
WebAPIStoragelength
example the following function adds three data items to the local storage for the current domain, then returns the number of items in the storage: function populatestorage() { localstorage.setitem('bgcolor', 'yellow'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'cats.png'); return localstorage.length; // should return 3 } note: for a real world example, see our web storage demo.
Storage.removeItem() - Web APIs
example the following function creates three data items inside local storage, then removes the image data item.
Storage.setItem() - Web APIs
WebAPIStoragesetItem
example the following function creates three data items inside local storage.
Storage Access API - Web APIs
this is enforced through the following constraints: access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click.
SubtleCrypto.decrypt() - Web APIs
exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g.
SubtleCrypto.deriveBits() - Web APIs
exceptions the promise is rejected when one of the following exceptions are encountered: invalidaccesserror raised when the base key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey.
SubtleCrypto.deriveKey() - Web APIs
exceptions the promise is rejected when one of the following exceptions are encountered: invalidaccesserror raised when the master key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey.
SubtleCrypto.encrypt() - Web APIs
exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g.
SubtleCrypto.generateKey() - Web APIs
exceptions the promise is rejected when the following exception is encountered: syntaxerror raised when the result is a cryptokey of type secret or private but keyusages is empty.
SubtleCrypto.sign() - Web APIs
WebAPISubtleCryptosign
exceptions the promise is rejected when the following exception is encountered: invalidaccesserror raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing.
SubtleCrypto.verify() - Web APIs
exceptions the promise is rejected when the following exception is encountered: invalidaccesserror raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation.
SubtleCrypto - Web APIs
the subtlecrypto api provides the following cryptography functions: * sign() and verify(): create and verify digital signatures.
Text.wholeText - Web APIs
WebAPITextwholeText
syntax str = textnode.wholetext; notes and example suppose you have the following simple paragraph within your webpage (with some whitespace added to aid formatting throughout the code samples here), whose dom node is stored in the variable para: <p>thru-hiking is great!
Text - Web APIs
WebAPIText
properties included from slotable the text interface includes the following property, defined on the slotable mixin.
TextDecoder.prototype.encoding - Web APIs
it can be one of the following values: the recommended encoding for the web: 'utf-8'.
TextEncoder.encoding - Web APIs
it can only have the following value utf-8.
TextMetrics.width - Web APIs
WebAPITextMetricswidth
you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('foo'); // textmetrics object text.width; // 16; specifications specification html living standardthe definition of 'textmetrics.width' in that specification.
TextRange - Web APIs
WebAPITextRange
example the following example is valid under ie9.
TextTrack.mode - Web APIs
WebAPITextTrackmode
text track mode constants the text track mode—sometimes identified using the idl enum texttrackmode—must be one of the following values: disabled the text track is currently disabled.
Touch() - Web APIs
WebAPITouchTouch
syntax touch = new touch(touchinit); arguments touchinit is a touchinit dictionary, having the following fields: "identifier", required, of type long, that is the identification number for the touch point.
Touch.force - Web APIs
WebAPITouchforce
in following code snippet, the touchstart event handler iterrates through the targettouches list and logs the force value of each touch point but the code could invoke different processing depending on the value.
Touch.pageX - Web APIs
WebAPITouchpageX
in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface.
Touch.pageY - Web APIs
WebAPITouchpageY
in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface.
Touch.radiusX - Web APIs
WebAPITouchradiusX
the following simple code snippet, registers a single handler for the touchstart, touchmove and touchend events.
Touch.screenX - Web APIs
WebAPITouchscreenX
in following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of source and then releases contacts with the surface.
Touch.target - Web APIs
WebAPITouchtarget
in following simple code snippet, we assume the user initiates one or more touch contacts on the source element.
TouchEvent() - Web APIs
toucheventinit optional is a toucheventinit dictionary, having the following fields: "touches", optional and defaulting to [], of type touch[], that is a list of objects for every point of contact currently touching the surface.
TouchEvent.altKey - Web APIs
WebAPITouchEventaltKey
in following code snippet, the touchstart event handler logs the state of the event's modifier keys.
TouchEvent.changedTouches - Web APIs
in following code snippet, the touchmove event handler iterates through the changedtouches list and prints the identifier of each touch point that changed since the last event.
TouchEvent.targetTouches - Web APIs
in following code snippet, the function compares the length of the touches list to the the length of the targettouches list and returns true if the lengths are the same and returns false otherwise.
TouchEvent.touches - Web APIs
in following code snippet, the touchstart event handler checks the length of the touchevent.touches list to determine the number of touch points that were activated and then invokes different handlers depending on the number of touch points.
Multi-touch interaction - Web APIs
example this example demonstrates using the touchstart, touchmove, touchcancel, and touchend) touch events for the following gestures: single touch, two (simultaneous) touches, more than two simultaneous touches, 1-finger swipe, and 2-finger move/pinch/swipe.
Supporting both TouchEvent and MouseEvent - Web APIs
// touchmove handler function process_touchmove(ev) { // call preventdefault() to prevent any further handling ev.preventdefault(); } event order although the specific ordering of touch and mouse events is implementation-defined, the standard indicates the following order is typical: for single input: touchstart zero or more touchmove events, depending on movement of the finger(s) touchend mousemove mousedown mouseup click if the touchstart, touchmove or touchend event is canceled during an interaction, no mouse or click events will be fired, and the resulting sequence of events would just be: touchstart zero or more touchmove events, dependin...
TrackDefault.TrackDefault() - Web APIs
errors when this constructor is invoked, the following errors can occur: error explanation invalidaccesserror the supplied language is not a valid language code, e.g.
TrackEvent() - Web APIs
eventinfo optional an optional dictionary providing additional information configuring the new event; it can contain the following fields in any combination: track optional the track to which the event refers; this is null by default, but should be set to a videotrack, audiotrack, or texttrack as appropriate given the type of track.
TransformStream - Web APIs
methods none examples anything-to-uint8array stream in the following example, a transform stream passes through all chunks it receives as uint8array values.
TransitionEvent.initTransitionEvent() - Web APIs
the following value is allowed: value meaning transitionend the transition completed.
UIEvent() - Web APIs
WebAPIUIEventUIEvent
uieventinit optional is a uieventinit dictionary, having the following fields: detail: optional and defaulting to 0, of type long, that is a event-dependant value associated with the event.
URL.origin - Web APIs
WebAPIURLorigin
for blob: urls, the origin of the url following blob: will be used, e.g "blob:https://mozilla.org" will be returned as "https://mozilla.org".
URLSearchParams() - Web APIs
examples the following example shows how to create a urlsearchparams object from a url string.
URLSearchParams - Web APIs
an object implementing urlsearchparams can directly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mysearchparams) {} for (const [key, value] of mysearchparams.entries()) {} note: this feature is available in web workers.
USB.getDevices() - Web APIs
WebAPIUSBgetDevices
example the following example logs the product name and serial number of paired devices to the console.
USBDevice.claimInterface() - Web APIs
example the following example shows claiminterface() in the context of connecting to a usb device.
USBDevice.clearHalt() - Web APIs
example the following example shows how to test for and clear a 'stall' condition in the result of a data transfer.
USBDevice.configuration - Web APIs
example the following example uses this property to test for the existence of a usbconfiguration property to select a configuration before claiming an interface.
ValidityState.patternMismatch - Web APIs
examples given the following: <p> <label>enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"/...
ValidityState.rangeOverflow - Web APIs
given the following: <input type="number" min="20" max="40" step="2"/> if value > 40, rangeoverflow will be true.
ValidityState.rangeUnderflow - Web APIs
given the following: <input type="number" min="20" max="40" step="2"/> if value < 20, rangeunderflow will be true.
ValidityState.stepMismatch - Web APIs
given the following: <input type="number" min="20" max="40" step="2"/> if (value - min) / 2 != 0, stepmismatch will be true.
ValidityState.typeMismatch - Web APIs
type attribute conformance input type value expected value email x@y or x@y.z email address, with or without tld url x: or x://y.z protocol or full url with protocol examples given the following: <p> <label> enter an email address: <input type="email" value="example.com"/> </label> </p> <p> <label> enter a url: <input type="url" value="example.com"/> </label> </p> input:invalid { border: red solid 3px; } the above each produce a typemismatch because the email address is just a domain and the url has no protocol the typemismatch occurs when there is a discon...
WakeLock.request() - Web APIs
WebAPIWakeLockrequest
examples the following asynchronous function requests a wakelocksentinel object.
WakeLock - Web APIs
WebAPIWakeLock
examples the following asynchronous function requests a wakelocksentinel object.
WakeLockSentinel - Web APIs
properties this interface provides the following properties.
WaveShaperNode.curve - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
WaveShaperNode.oversample - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
WaveShaperNode - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
WebGL2RenderingContext.getUniformBlockIndex() - Web APIs
examples // assuming a shader with the following declaration: // uniform ubodata { // mat4 foo; // } instancename; // use the block name, not the instance name: var blockindex = gl.getuniformblockindex(program, 'ubodata'); specifications specification status comment webgl 2.0the definition of 'getuniformblockindex' in that specification.
WebGL2RenderingContext.texImage3D() - Web APIs
gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) source one of the following objects can be used as a pixel source for the texture: arraybufferview, imagebitmap, imagedata, htmlimageelement, htmlcanvaselement, htmlvideoelement.
WebGL2RenderingContext.texStorage2D() - Web APIs
possible values: gl.r8 gl.r16f gl.r32f gl.r8ui gl.rg8 gl.rg16f gl.rg32f gl.rg8ui gl.rgb8 gl.srgb8 gl.rgb565 gl.r11f_g11f_b10f gl.rgb9_e5 gl.rgb16f gl.rgb32f gl.rgb8ui gl.rgba8 gl.srgb8_aplha8 gl.rgb5_a1 gl.rgba4 gl.rgba16f gl.rgba32f gl.rgba8ui unlike opengl 3.0, webgl 2 doesn't support the following etc2 and eac compressed texture formats (see section 5.37 in the webgl 2 spec).
WebGL2RenderingContext.texSubImage3D() - Web APIs
gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) pixels one of the following objects can be used as a pixel source for the texture: arraybufferview, a uint8array must be used if type is gl.unsigned_byte.
WebGLBuffer - Web APIs
when working with webglbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindbuffer() webglrenderingcontext.createbuffer() webglrenderingcontext.deletebuffer() webglrenderingcontext.isbuffer() examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'webglbuffer' in that specification.
WebGLFramebuffer - Web APIs
when working with webglframebuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindframebuffer() webglrenderingcontext.createframebuffer() webglrenderingcontext.deleteframebuffer() webglrenderingcontext.isframebuffer() examples creating a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createframebuffer(); specifications specification status comment webgl 1.0the definition of 'we...
WebGLQuery - Web APIs
when working with webglquery objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createquery() webgl2renderingcontext.deletequery() webgl2renderingcontext.isquery() webgl2renderingcontext.beginquery() webgl2renderingcontext.endquery() webgl2renderingcontext.getquery() webgl2renderingcontext.getqueryparameter() examples creating a webglquery object in this example, gl must be a webgl2renderin...
WebGLRenderbuffer - Web APIs
when working with webglrenderbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindrenderbuffer() webglrenderingcontext.createrenderbuffer() webglrenderingcontext.deleterenderbuffer() webglrenderingcontext.isrenderbuffer() examples creating a render buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createrenderbuffer(); specifications specification status comment ...
WebGLRenderingContext.activeTexture() - Web APIs
examples the following call selects gl.texture1 as the current texture.
WebGLRenderingContext.attachShader() - Web APIs
examples the following code attaches pre-existing shaders to a webglprogram.
WebGLRenderingContext.bindBuffer() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another.
WebGLRenderingContext.bindFramebuffer() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer.
WebGLRenderingContext.bindTexture() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture.
WebGLRenderingContext.blendEquation() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination.
WebGLRenderingContext.blendFunc() - Web APIs
constants the following constants can be used for sfactor and dfactor.
WebGLRenderingContext.blendFuncSeparate() - Web APIs
constants the following constants can be used for srcrgb, dstrgb, srcalpha, and dstalpha the formulas for the blending factors can be described like this (all rgba values are between 0 and 1): color(rgb) = (sourcecolor * srcrgb) + (destinationcolor * dstrgb) color(a) = (sourcealpha * srcalpha) + (destinationalpha * dstalpha) constant rgb factor alpha factor description gl.zero 0,...
WebGLRenderingContext.bufferSubData() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another.
WebGLRenderingContext.disable() - Web APIs
when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard deactivates that primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage.
WebGLRenderingContext.drawingBufferHeight - Web APIs
syntax gl.drawingbufferheight; examples given this <canvas> element: <canvas id="canvas"></canvas> you can get the height of the drawing buffer with the following lines: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.drawingbufferheight; // 150 specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.drawingbufferheight' in that specification.
WebGLRenderingContext.drawingBufferWidth - Web APIs
syntax gl.drawingbufferwidth; examples given this <canvas> element: <canvas id="canvas"></canvas> you can get the width of the drawing buffer with the following lines: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.drawingbufferwidth; // 300 specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.drawingbufferwidth' in that specification.
WebGLRenderingContext.enable() - Web APIs
when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage.
WebGLRenderingContext.generateMipmap() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture.
WebGLRenderingContext.getActiveUniform() - Web APIs
the type attribute of the return value will be one of the following: gl.float gl.float_vec2 gl.float_vec3 gl.float_vec4 gl.int gl.int_vec2 gl.int_vec3 gl.int_vec4 gl.bool gl.bool_vec2 gl.bool_vec3 gl.bool_vec4 gl.float_mat2 gl.float_mat3 gl.float_mat4 gl.sampler_2d gl.sampler_cube when using a webgl 2 context, the following values are possible additionally: gl.unsigned_int gl.unsigned_int_vec2 gl.unsigned_int_vec3 gl.unsigned_in...
WebGLRenderingContext.getProgramParameter() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.transform_feedback_buffer_mode: returns a glenum indicating the buffer mode when transform feedback is active.
WebGLRenderingContext.getRenderbufferParameter() - Web APIs
when using a webgl 2 context, the following value is available additionally: gl.renderbuffer_samples: returns a glint indicating the number of samples of the image of the currently bound renderbuffer.
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
examples the following code gets the precision format of a gl.vertex_shader with a gl.medium_float precision type.
WebGLRenderingContext.getTexParameter() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture.
WebGLRenderingContext.getVertexAttrib() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.vertex_attrib_array_integer: returns a glboolean indicating whether or not an integer data type is in the vertex attribute array at the given index.
WebGLRenderingContext.isEnabled() - Web APIs
when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage.
WebGLRenderingContext.makeXRCompatible() - Web APIs
exceptions this method doesn't throw traditional exceptions; instead, the promise rejects with one of the following errors as the value passed into the rejection handler: aborterror switching the context over to the webxr-compatible context failed.
WebGLRenderingContext.pixelStorei() - Web APIs
glenum gl.browser_default_webgl gl.browser_default_webgl, gl.none webgl when using a webgl 2 context, the following values are available additionally: constant description type default value allowed values (for param) specified in gl.pack_row_length number of pixels in a row.
WebGLRenderingContext.renderbufferStorage() - Web APIs
gl.depth_stencil when using a webgl 2 context, the following values are available additionally: gl.r8 gl.r8ui gl.r8i gl.r16ui gl.r16i gl.r32ui gl.r32i gl.rg8 gl.rg8ui gl.rg8i gl.rg16ui gl.rg16i gl.rg32ui gl.rg32i gl.rgb8 gl.rgba8 gl.srgb8_alpha8 (also available as an extension for webgl 1, see below) gl.rgb10_a2 gl.rgba8ui gl.rgba8i gl.rgb10_a2ui gl.rgba16ui gl.
WebGLRenderingContext.stencilFunc() - Web APIs
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 constants with getparameter().
WebGLRenderingContext.stencilFuncSeparate() - Web APIs
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 following constants with getparameter().
WebGLRenderingContext.stencilOp() - Web APIs
gl.enable(gl.stencil_test); gl.stencilop(gl.incr, gl.decr, gl.invert); to get the current information about stencil and depth pass or fail, query the following constants with getparameter().
WebGLRenderingContext.stencilOpSeparate() - Web APIs
gl.enable(gl.stencil_test); gl.stencilopseparate(gl.front, gl.incr, gl.decr, gl.invert); to get the current information about stencil and depth pass or fail, query the following constants with getparameter().
WebGLRenderingContext.texParameter[fi]() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture.
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
examples const a_foobar = gl.getattriblocation(shaderprogram, 'foobar'); //either set each component individually: gl.vertexattrib3f(a_foobar, 10.0, 5.0, 2.0); //or provide a float32array: const floatarray = new float32array([10.0, 5.0, 2.0]); gl.vertexattrib3fv(a_foobar, floatarray); // we want to load the following 3x3 matrix into attribute named "matrix3x3" // 0 1 2 // 3 4 5 // 6 7 8 const matrix3x3location = gl.getattriblocation(shaderprogram, 'matrix3x3'); gl.vertexattrib3f(matrix3x3location, 0, 3, 6); gl.vertexattrib3f(matrix3x3location + 1, 1, 4, 7); gl.vertexattrib3f(matrix3x3location + 2, 2, 5, 8); specifications specification status comment webgl 1.0the definition of '...
WebGLRenderingContext - Web APIs
the webgl context the following properties and methods provide general information and functionality to deal with the webgl context: webglrenderingcontext.canvas a read-only back-reference to the htmlcanvaselement.
WebGLSampler - Web APIs
when working with webglsampler objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createsampler() webgl2renderingcontext.deletesampler() webgl2renderingcontext.issampler() webgl2renderingcontext.bindsampler() webgl2renderingcontext.getsamplerparameter() examples creating a webglsampler object in this example, gl must be a webgl2renderingcontext.
WebGLSync - Web APIs
WebAPIWebGLSync
when working with webglsync objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.fencesync() webgl2renderingcontext.deletesync() webgl2renderingcontext.issync() webgl2renderingcontext.clientwaitsync() webgl2renderingcontext.waitsync() webgl2renderingcontext.getsyncparameter() examples creating a webglsync object in this example, gl must be a webgl2renderingcontext.
WebGLTexture - Web APIs
when working with webgltexture objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindtexture() webglrenderingcontext.createtexture() webglrenderingcontext.deletetexture() webglrenderingcontext.istexture() examples creating a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); specifications specification status comment webgl 1.0the definition of 'webgltexture' in that ...
WebGLTransformFeedback - Web APIs
when working with webgltransformfeedback objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createtransformfeedback() webgl2renderingcontext.deletetransformfeedback() webgl2renderingcontext.istransformfeedback() webgl2renderingcontext.bindtransformfeedback() webgl2renderingcontext.begintransformfeedback() webgl2renderingcontext.endtransformfeedback() webgl2renderingcontext.pausetransformfeedback() webgl2renderingcontext.resumetransformfeedback() webgl2ren...
WebGLUniformLocation - Web APIs
when working with webgluniformlocation objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.getuniformlocation() webglrenderingcontext.uniform() examples getting an uniform location var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var location = gl.getuniformlocation(webglprogram, 'uniformname'); specifications specification status comment webgl 1.0the definition of 'webgluniformlocation' in that specification.
WebGLVertexArrayObject - Web APIs
when working with webglvertexarrayobject objects, the following methods are useful: webgl2renderingcontext.createvertexarray() webgl2renderingcontext.deletevertexarray() webgl2renderingcontext.isvertexarray() webgl2renderingcontext.bindvertexarray() webgl 1: the oes_vertex_array_object extension allows you to use vertex array objects in a webgl 1 context.
Basic scissoring - Web APIs
ign : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } window.addeventlistener("load", function setupwebgl (evt) { "use strict" window.removeeventlistener(evt.type, setupwebgl, false); var paragraph = document.queryselector("p"); var canvas = document.queryselector("canvas"); // the following two lines set the size (in css pixels) of // the drawing buffer to be identical to the size of the // canvas html element, as determined by css.
Boilerplate 1 - Web APIs
in following examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context.
Compressed texture formats - Web APIs
which formats support texture_2d_array and texture_3d targets (in combination with compressedteximage3d) are noted in the following table.
Matrix math for the web - Web APIs
for instance, to scale something down by 80%, move it down 200 pixels, and then rotate about the origin 90 degrees would look something like the following in pseudo-code.
Animating objects with WebGL - Web APIs
we can do that by creating a new variable to track the time at which we last animated (let's call it then), then adding the following code to the end of the main function var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; drawscene(gl, programinfo, buffers, deltatime); requestanimationframe(render); } requestanimationframe(render); this code uses requestanimationframe to ask the browser to call the f...
WebGL types - Web APIs
WebAPIWebGL APITypes
the following types are used in webgl interfaces.
WebRTC connectivity - Web APIs
the pending description (returned by rtcpeerconnection.pendinglocaldescription and rtcpeerconnection.pendingremotedescription) indicates a description which is currently under consideration following a call to setlocaldescription() or setremotedescription(), respectively.
Introduction to WebRTC protocols - Web APIs
for example, lines providing media descriptions have the type "m", so those lines are referred to as "m-lines." for more information to learn more about sdp, see the following useful resources: specification: rfc 4566: sdp: session description protocol iana registry of sdp parameters ...
WebSocket.readyState - Web APIs
syntax var readystate = awebsocket.readystate; value one of the following unsigned short values: value state description 0 connecting socket has been created.
WebSocket.send() - Web APIs
WebAPIWebSocketsend
it may be one of the following types: usvstring a text string.
Writing WebSocket servers - Web APIs
that header looks something like the following (remember each header line ends with \r\n and put an extra \r\n after the last one to indicate the end of the header): http/1.1 101 switching protocols upgrade: websocket connection: upgrade sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo= additionally, the server can decide on extension/subprotocol requests here; see miscellaneous for details.
Writing a WebSocket server in Java - Web APIs
if it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit must be 0) are the length.
Using bounded reference spaces - Web APIs
you can create a session that supports a bounded-floor reference space if available by using code such as the following: async function onactivatexrbutton(event) { if (!xrsession) { navgator.xr.requestsession("immersive-vr"), { requiredfeatures: ["local-floor"], optionalfeatures: ["bounded-floor"] }).then((session) => { xrsession = session; startsessionanimation(); }); } } this function, called when the user clicks on a button to start the xr experience, works as usual, e...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
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.perspective(transf...
Fundamentals of WebXR - Web APIs
the following articles can help.
WebXR performance guide - Web APIs
consider the following function drawscene(gl, view, programinfo, buffers, texture, deltatime) { ...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
for example, given an xrsession whose reference space is worldrefspace, the following line of code would request the first frame of animation to be scheduled: animationframerequestid = xrsession.requestanimationframe(mydrawframe); then, the mydrawframe() function—the callback executed when it's time to draw the frame—might be something like this: function mydrawframe(currentframetime, frame) { let session = frame.session; let viewerpose = frame.getviewerpose(viewerrefs...
Keyframe Formats - Web APIs
the following special attributes may also be specified: offset the offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null.
Example and tutorial: Simple synth keyboard - Web APIs
this example makes use of the following web api interfaces: audiocontext, oscillatornode, periodicwave, and gainnode.
Visualizations with Web Audio API - Web APIs
draw(); this code gives us a result like the following: note: the examples listed in this article have shown usage of analysernode.getbytefrequencydata() and analysernode.getbytetimedomaindata().
WheelEvent() - Web APIs
wheeleventinit optional is a wheeleventinit dictionary, having the following fields: "deltax", optional and defaulting to 0.0, is a double representing the horizontal scroll amount in the deltamode unit.
Window.alert() - Web APIs
WebAPIWindowalert
the following text is shared between this article, dom:window.prompt and dom:window.confirm dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed.
Window.closed - Web APIs
WebAPIWindowclosed
examples change the url of a window from a popup the following example demonstrates how a popup window can change the url of the window that opened it.
Window.confirm() - Web APIs
WebAPIWindowconfirm
example if (window.confirm("do you really want to leave?")) { window.open("exit.html", "thanks for visiting!"); } produces: notes the following text is shared between this article, dom:window.prompt and dom:window.alert dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed.
Window.content - Web APIs
WebAPIWindowcontent
syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none.
Window.customElements - Web APIs
examples the most common example you'll see of this property being used is to get access to the customelementregistry.define() method to define and register a new custom element, e.g.: let customelementregistry = window.customelements; customelementregistry.define('my-custom-element', mycustomelement); however, it is usually shortened to something like the following: customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(true)); } } ); see our web-components-examples repo for more usage examples.
Window.external - Web APIs
WebAPIWindowexternal
methods the external object has the following methods: method description addsearchprovider(descriptionurl) dummy function; does nothing.
Window: hashchange event - Web APIs
the hashchange event is fired when the fragment identifier of the url has changed (the part of the url beginning with and following the # symbol).
Window.innerHeight - Web APIs
graphical example the following figure shows the difference between outerheight and innerheight.
Window.localStorage - Web APIs
example the following snippet accesses the current domain's local storage object and adds a data item to it using storage.setitem().
window.location - Web APIs
WebAPIWindowlocation
location.assign("http://www.mozilla.org"); // or location = "http://www.mozilla.org"; example #2: force reloading the current page from the server location.reload(true); example #3 consider the following example, which will reload the page by using the replace() method to insert the value of location.pathname into the hash: function reloadpagewithhash() { var initialpage = location.pathname; location.replace('http://example.com/#' + initialpage); } example #4: display the properties of the current url in an alert dialog: function showloc() { var olocation = location, alog = ["property (...
Window.locationbar - Web APIs
syntax objref = window.locationbar example the following complete html example shows how the visible property of the locationbar object is used.
Window.menubar - Web APIs
WebAPIWindowmenubar
syntax objref = window.menubar example the following complete html example demonstrates how the visible property of the menubar object is used.
Window.onbeforeinstallprompt - Web APIs
}); window.onbeforeinstallprompt = function(event) { ...}; example the following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler.
Privileged features - Web APIs
the following features require the chrome-privilege.
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
to access these extra parameters from within dialog code, use the following scheme: var food = window.arguments[0]; var price = window.arguments[1]; note that you can access this property from within anywhere in the dialog code.
Window.outerHeight - Web APIs
graphical example the following figure shows the difference between outerheight and innerheight.
Window: popstate event - Web APIs
examples a page at http://example.com/example.html running the following code will generate logs as indicated: window.addeventlistener('popstate', (event) => { console.log("location: " + document.location + ", state: " + json.stringify(event.state)); }); history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // logs "location: http://example.com/e...
window.postMessage() - Web APIs
the dispatched event otherwindow can listen for dispatched messages by executing the following javascript: window.addeventlistener("message", receivemessage, false); function receivemessage(event) { if (event.origin !== "http://example.org:8080") return; // ...
Window.prompt() - Web APIs
WebAPIWindowprompt
the following text is shared between this article, dom:window.confirm and dom:window.alert dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed.
Window: resize event - Web APIs
examples window size logger the following example reports the window size each time it is resized.
Window.scrollbars - Web APIs
WebAPIWindowscrollbars
syntax objref = window.scrollbars example the following complete html example shows how the visible property of the scrollbars object is used.
Window.sidebar - Web APIs
WebAPIWindowsidebar
methods the sidebar object returned has the following methods: method description (seamonkey) description (firefox) addpanel(title, contenturl, "") adds a sidebar panel.
Window: unload event - Web APIs
bubbles no cancelable no interface event event handler property onunload it is fired after: beforeunload (cancelable event) pagehide the document is in the following state: all the resources still exist (img, iframe etc.) nothing is visible anymore to the end user ui interactions are ineffective (window.open, alert, confirm, etc.) an error won't stop the unloading workflow please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below).
Window.window - Web APIs
WebAPIWindowwindow
thus, the following expressions all return the same window object: window.window window.window.window window.window.window.window // ...
Window - Web APIs
WebAPIWindow
also available via the ongamepaddisconnected property history events hashchange fired when the fragment identifier of the url has changed (the part of the url beginning with and following the # symbol).
WindowEventHandlers.onhashchange - Web APIs
'location1' : 'location2'; } the hashchange event the dispatched hashchange event has the following properties: field type description newurl domstring the new url to which the window is navigating.
WindowEventHandlers.onpopstate - Web APIs
examples for example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?p...
WindowOrWorkerGlobalScope.caches - Web APIs
example the following example shows how you'd use a cache in a service worker context to store assets offline.
WindowOrWorkerGlobalScope.indexedDB - Web APIs
example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open('todolist'); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; } } specifications specification status comment indexed database api draftthe definition of 'indexeddb' in that specification.
WindowOrWorkerGlobalScope.origin - Web APIs
examples executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message onmessage = function() { console.log(self.origin); }; if the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e.
Worker() - Web APIs
WebAPIWorkerWorker
examples the following code snippet shows creation of a worker object using the worker() constructor and subsequent usage of the object: var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see our basic dedicated worker example (run dedicated worker).
Worker.onmessage - Web APIs
WebAPIWorkeronmessage
} example the following code snippet shows creation of a worker object using the worker() constructor.
Worker.prototype.postMessage() - Web APIs
example the following code snippet shows the creation of a worker object using the worker() constructor.
Worker.terminate() - Web APIs
WebAPIWorkerterminate
example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated.
Worker - Web APIs
WebAPIWorker
example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker = new worker('/worker.js'); var first = document.queryselector('input#number1'); var second = document.queryselector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a full example, se...
WorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you wanted to close your worker instance from inside the worker itself, you could call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope.
WorkerGlobalScope.dump() - Web APIs
next, run a worker containing the following line: dump('test\n'); this should result in a "test" message being output to the terminal.
WorkerGlobalScope.importScripts() - Web APIs
example if you had some functionality written in a separate script called foo.js that you wanted to use inside worker.js, you could import it using the following line: importscripts('foo.js'); importscripts() and self.importscripts() are effectively equivalent — both represent importscripts() being called from inside the worker's inner scope.
WorkerGlobalScope.location - Web APIs
example if you called the following in a document served at localhost:8000 console.log(location); inside a worker (which would basically be the equivalent of self.console.log(self.location);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerlocation object written to the console — something like the following: workerlocation {hash: "", search: "", pathname: "/worker.js", port: "8000", hostname: "localhost"…} hash...
WorkerGlobalScope.navigator - Web APIs
example if you call the following console.log(navigator); inside a worker (which would basically be the equivalent of self.console.log(self.navigator);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workernavigator object written to the console — something like the following: object {online: true, useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) ap…ml, like gecko) chrome/40.0.2214.93 safari/537.36", ...
WorkerGlobalScope.onclose - Web APIs
}; example the following code snippet shows an onclose handler set inside a worker: self.onclose = function() { console.log('your worker instance has been closed'); } specifications this feature is no longer defined in any specifications.
WorkerGlobalScope.onerror - Web APIs
}; example the following code snippet shows an onerror handler set inside a worker: self.onerror = function() { console.log('there is an error inside your worker!'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onerror' in that specification.
WorkerGlobalScope.onlanguagechange - Web APIs
}; example the following code snippet shows an onlanguagechange handler set inside a worker: self.onlanguagechange = function() { console.log('your preferred language settings have been changed'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onlanguagechange' in that specification.
WorkerGlobalScope.onoffline - Web APIs
}; example the following code snippet shows an onoffline handler set inside a worker: self.onoffline = function() { console.log('your worker is now offline'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onoffline' in that specification.
WorkerGlobalScope.ononline - Web APIs
}; example the following code snippet shows an ononline handler set inside a worker: self.ononline = function() { console.log('your worker is now online'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.ononline' in that specification.
WorkerGlobalScope.performance - Web APIs
example if you called console.log(performance); inside a worker (which would basically be the equivalent of self.console.log(self.performance);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerperformance object written to the console — something like the following: workerperformance {now: function} __proto__: workerperformance constructor: function workerperformance() { [native code] } now: function now() { [native code] } __proto__: object you could use this performance object to return performance data, as you might do with a normal performance object.
WorkerGlobalScope.self - Web APIs
example if you called console.log(self); inside a worker, you will get a worker global scope of the same type as that worker object written to the console — something like the following: dedicatedworkerglobalscope { undefined: undefined, infinity: infinity, math: mathconstructor, nan: nan, intl: object…} infinity: infinity array: function array() { [native code] } arguments: null caller: null isarray: function isarray() { [native code] } length: 1 name: "array" observe: function observe() { [native code] } prototype: array[0] ...
WorkerGlobalScope - Web APIs
for example, you could import another script into the worker and print out the contents of the worker scope's navigator object using the following two lines: importscripts('foo.js'); console.log(navigator); since the global scope of the worker script is effectively the global scope of the worker you are running (dedicatedworkerglobalscope or whatever) and all worker global scopes inherit methods, properties, etc.
Worklet - Web APIs
WebAPIWorklet
instead, you can use one of the following classes: name description location specification paintworklet for programmatically generating an image where a css property expects a file.
WritableStream.getWriter() - Web APIs
examples the following example illustrates several features of this interface.
WritableStream - Web APIs
examples the following example illustrates several features of this interface.
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
WritableStreamDefaultWriter.close() - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
WritableStreamDefaultWriter.ready - Web APIs
example the following example shows two uses of the ready property.
WritableStreamDefaultWriter.write() - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
WritableStreamDefaultWriter - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
HTML in XMLHttpRequest - Web APIs
this test file is small and is not well-formed xml: <title>&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 &...
Sending and Receiving Binary Data - Web APIs
the following example creates a text file on-the-fly and uses the post method to send the "file" to the server.
Using XMLHttpRequest in IE6 - Web APIs
in all modern browsers, you can create a new xmlhttprequest object using the following code: var request = new xmlhttprequest() however, if you need to also support internet explorer 6 and older, you need to extend your code like this: if (window.xmlhttprequest) { //firefox, opera, ie7, and other browsers will use the native object var request = new xmlhttprequest(); } else { //ie 5 and 6 will use the activex control var request = new activexobject("microsoft.xmlhttp"); } see also using xmlhttprequest ...
XMLHttpRequest.readyState - Web APIs
an xhr client exists in one of the following states: value state description 0 unsent client has been created.
XMLHttpRequest.responseText - Web APIs
the read-only xmlhttprequest property responsetext returns the text received from a server following a request being sent.
XMLHttpRequest.responseType - Web APIs
the values supported by responsetype are the following: "" an empty responsetype string is treated the same as "text", the default type.
XMLHttpRequest.sendAsBinary() - Web APIs
however, on google chrome, when you try to send an arraybuffer, the following warning message will appear: arraybuffer is deprecated in xmlhttprequest.send().
XMLHttpRequest.status - Web APIs
example var xhr = new xmlhttprequest(); console.log('unsent: ', xhr.status); xhr.open('get', '/server'); console.log('opened: ', xhr.status); xhr.onprogress = function () { console.log('loading: ', xhr.status); }; xhr.onload = function () { console.log('done: ', xhr.status); }; xhr.send(); /** * outputs the following: * * unsent: 0 * opened: 0 * loading: 200 * done: 200 */ specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.statusText - Web APIs
example 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 ...
XMLHttpRequest.upload - Web APIs
the following events can be triggered on an upload object and used to monitor the upload: event event listener description loadstart onloadstart the upload has begun.
XMLSerializer.serializeToString() - Web APIs
the following types are also permitted as descendants of the root node, in addition to node and attr: documenttype document documentfragment element comment text processinginstruction attr if any other type is encountered, a typeerror exception is thrown.
XMLSerializer - Web APIs
note: in the real world, you should usually instead call importnode() method to import the new node into the dom, then call one of the following methods to add the node to the dom tree: the document and element methods append() and prepend() the node.replacewith() method (to replace an existing node with the new one) the document.insertadjacentelement() and element.insertadjacentelement() methods.
XPathEvaluator.createExpression() - Web APIs
example the following example shows the use of the evaluate() method.
XPathEvaluator.evaluate() - Web APIs
example the following example shows the use of the evaluate() method.
XPathEvaluator - Web APIs
example the following example shows the use of the xpathevaluator interface.
XPathExpression.evaluate() - Web APIs
example the following example shows the use of the evaluate() method.
XPathExpression - Web APIs
example the following example shows the use of the xpathexpression interface.
XPathResult.booleanValue - Web APIs
example the following example shows the use of the booleanvalue property.
XPathResult.invalidIteratorState - Web APIs
example the following example shows the use of the invaliditeratorstate property.
XPathResult.iterateNext() - Web APIs
example the following example shows the use of the iteratenext() method.
XPathResult.numberValue - Web APIs
example the following example shows the use of the numbervalue property.
XPathResult.resultType - Web APIs
example the following example shows the use of the resulttype property.
XPathResult.singleNodeValue - Web APIs
example the following example shows the use of the singlenodevalue property.
XPathResult.snapshotItem() - Web APIs
example the following example shows the use of the snapshotitem() method.
XPathResult.snapshotLength - Web APIs
example the following example shows the use of the snapshotlength property.
XPathResult.stringValue - Web APIs
example the following example shows the use of the stringvalue property.
XRBoundedReferenceSpace - Web APIs
properties in addition to the properties of xrreferencespace, xrboundedreferencespace includes the following: boundsgeometry read only an array of dompointreadonly objects, each of which defines a vertex in the polygon defining the boundaries within which the user will be required to remain.
XRInputSource.handedness - Web APIs
the value, which comes from the xrhandedness enumerated type, is one of the following: none the input controller is not associated with one of the user's hands.
XRInputSourceEventInit - Web APIs
it also offers the following: frame an xrframe object representing the event frame during which the event took place.
XRInputSourcesChangeEvent() - Web APIs
example the following snippet of code creates a new xrinputsourceschangeevent object indicating that a single new input source, described by an xrinputsource object named newinputsource, has been added to the system.
XRInputSourcesChangeEvent - Web APIs
examples the following example shows how to set up an event handler which uses inputsourceschange events to detect newly-available pointing devices and to load their models in preparation to display them in the next animation frame.
XRPermissionDescriptor - Web APIs
properties in addition to inheriting the properties of the parent interface, permissiondescriptor, xrpermissiondescriptor provides the following properties.
XRReferenceSpace: reset event - Web APIs
most common among them are the following: the user has manually reset the coordinate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and hand controllers are synchronized with the user's actual position and facing.
XRReferenceSpaceEvent - Web APIs
properties in addition to inheriting the properties available on the parent interface, event, xrreferencespaceevent objects include the following properties: referencespace read only an xrreferencespace indicating the reference space that generated the event.
XRSession: select event - Web APIs
examples the following example uses addeventlistener() to set up a handler for the select event.
XRSession: selectend event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select.
XRSession: selectstart event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select.
XRSession: squeeze event - Web APIs
examples the following example uses addeventlistener() to set up a handler for the squeeze event.
XRSession: squeezeend event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze.
XRSession: squeezestart event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze.
XRSessionEvent() - Web APIs
event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property.
XRSessionEvent - Web APIs
session event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property.
XRSessionInit - Web APIs
properties the following parameters are all optional.
XRSystem: isSessionSupported() - Web APIs
exceptions rather than throwing true exceptions, issessionsupported() rejects the returned promise, passing to the rejection handler a domexception whose name is one of the following strings.
XRViewerPose - Web APIs
properties in addition to the properties inherited from xrpose, xrviewerpose includes the following: views read only an array of xrview objects, one for each viewpoint on the scene which is needed to represent the scene to the user.
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
this method of dividing the frame buffer between views is shown in the following diagram.
XSLTProcessor - Web APIs
properties non-web-exposed properties the following properties are [chromeonly] and not exposed to web content: [chromeonly] attribute unsigned long xsltprocessor.flags flags that tweak the behavior of the processor.
ARIA live regions - Accessibility
here is a screenshot of voiceover on mac announcing the update (via subtitles) to the live region: preferring specialized live region roles in the following well-known predefined cases it is better to use a specific provided "live region role": role description compatibility notes log chat, error, game or other type of log to maximize compatibility, add a redundant aria-live="polite" when using this role.
ARIA Screen Reader Implementors Guide - Accessibility
the following is intended to provide implementation guidance that respects screen readers developers' need to try different things.
Using the alert role - Accessibility
possible effects on user agents and assistive technology when the alert role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having an alert role in the operating system's accessibility api.
Using the alertdialog role - Accessibility
possible effects on user agents and assistive technology when the alertdialog role is used, the user agent should do the following: expose the element as a dialog in the operating system's accessibility api.
Using the aria-invalid attribute - Accessibility
examples example 1: simple form validation the following snippet shows a simplified version of two form fields with a validation function attached to the blur event.
Using the aria-relevant attribute - Accessibility
values a space-delimited list of one or more of the following values: additions element nodes added to the accessibility tree within the live region; should be considered relevant.
Using the link role - Accessibility
possible effects on user agents and assistive technology when the link role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a link role in the operating system's accessibility api.
Using the log role - Accessibility
possible effects on user agents and assistive technology when the log role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a log role in the operating system's accessibility api.
Using the slider role - Accessibility
<label for="fader">volume</label> <input type="range" id="fader" min="1" max="100" value="50" step="1" aria-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputupdate(value)"> <output for="fader" id="volume">50</output> the following code snippet allows you to return the output as it is updated by user input: function outputupdate(vol) { document.queryselector('#volume').value = vol; } example 2: text values sometimes, a slider is used to choose a value that is not, semantically, a number.
Using the status role - Accessibility
possible effects on user agents and assistive technology when the status role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a status role in the operating system's accessibility api.
ARIA: Comment role - Accessibility
examples in the following example we have a document section that has been commented.
ARIA: grid role - Accessibility
if cells, rows, or columns can be selected, the following key combination are commonly used: key combination action ctrl + space select the column that contains the focus.
ARIA: gridcell role - Accessibility
examples the following example creates a table-style grouping of information: <h3 id="table-title">jovian gas giant planets</h3> <div role="grid" aria-describedby="table-title"> <div role="rowgroup"> <div role="row"> <div role="columnheader">name</div> <div role="columnheader">diameter (km)</div> <div role="columnheader">length of day (hours)</div> <div role="columnheader">distance from s...
ARIA: Mark role - Accessibility
examples in the following example we have a document section that has been commented.
ARIA: img role - Accessibility
for example, take the following code: <div role="img" aria-label="that cat is so funny"> <p> &#x1f408; &#x1f602; </p> </div> &#x1f408; &#x1f602; are entity references for emojis read out as "cat" and "face with tears of joy", but this doesn't necessarily make sense — the implied meaning is possibly more like "that cat is so funny", so we include that in an aria-label along with role="img".
ARIA: button role - Accessibility
space activates the button following button activation, focus is set depending on the type of action the button performs.
ARIA: heading role - Accessibility
examples the following shows a typical page structure.
Web applications and ARIA FAQ - Accessibility
browsers aria is supported in the following browsers: browser minimum version notes firefox 3.0+ works with nvda, jaws 10+, and orca chrome latest screen reader support still experimental as of chrome 15 safari 4+ safari 5 support is much improved.
Alerts - Accessibility
ge the two inputs for e-mail and name for this: <input name="name" id="name" aria-required="true" onblur="checkvalidity('name', ' ', 'invalid name entered!');"/> <br /> <input name="email" id="email" aria-required="true" onblur="checkvalidity('email', '@', 'invalid e-mail address');"/> testing the example if you use firefox 3 and a currently-supported screen reader, try the following: enter only your first name as the name.
Forms - Accessibility
the following pages provide various techniques for improving the accessibility of web forms: basic form hints: adding hints and descriptions for invalid or required fields alerts: using alerts to provide client-side validation error messages multi-part labels: enabling complex form labels with a control inside each label see also the yahoo!
ARIA - Accessibility
videos following talks are a great way to understand aria: aria, accessibility apis and coding like you give a damn!
Accessibility and Spacial Patterns - Accessibility
which they published in the paper, characterizing the patterned images that precipitate seizures and optimizing guidelines to prevent them the steps necessary to evaluate material reduce to the following: look at the screen are there more than five stripes?
An overview of accessible web applications and widgets - Accessibility
in practice, this usually involves following the conventions supported by similar widgets on the desktop, taking full advantage of the tab, enter, spacebar, and arrow keys.
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
see the following diagram for examples of nodes that do no support iaccessible.
Keyboard-navigable JavaScript widgets - Accessibility
the following table describes tabindex behavior in modern browsers: tabindex attribute focusable with mouse or javascript via element.focus() tab navigable not present follows the platform convention of the element (yes for form controls, links, etc.).
Mobile accessibility checklist - Accessibility
for touch events, at least one of the following must be true (wcag 2.1: pointer cancellation): the down-event should not be used to trigger any action the action is triggered on the up event and an option to abort the action before its completion is available or an option to undo the action after its completion the up-event will undo any action that was triggered on a down event it is essential to trigger the action on the down ...
Web accessibility for seizures and physical reactions - Accessibility
transitions (for css and svg) the following is from the web animations model csswg.org drafts the web animations model is intended to provide the features necessary for expressing css transitions [css-transitions-1], css animations [css-animations-1], and svg [svg11].
Web Accessibility: Understanding Colors and Luminance - Accessibility
the expert consensus of the epilepsy foundation noted the following in their publication, photic- and pattern-induced seizures: expert consensus of the epilepsy foundation of america working group "irrespective of luminance, a transition to or from a saturated red is also considered a risk" saturation is sometimes described as the "purity" or "intensity" of a color, and although these are good definitions for "pigments" in an artist's paint set, they are not qu...
Color contrast - Accessibility
when designing readable interfaces for different vision capabilities, the wcag guidelines recommend the following contrast ratios: type of content minimum ratio (aa rating) enhanced ratio (aaa rating) body text 4.5 : 1 7 : 1 large-scale text (120-150% larger than body text) 3 : 1 4.5 : 1 active user interface components and graphical objects such as icons and graphs 3 : 1 not defined these ratios do not apply to "incidental" text, such as inactive controls, logotypes, or purely decorative text.
Robust - Accessibility
this can generally be achieved by following web standards and testing rigorously.
Understandable - Accessibility
3.3.4 error prevention (legal, financial, data) (aa) in the case of forms involved with entry of sensitive data (such as legal agreements, e-commerce transactions, or personal data), at least one of the following should be true: submissions are reversible.
Accessibility
wai-aria basics following on from the previous article, sometimes making complex ui controls that involve unsemantic html and dynamic javascript-updated content can be difficult.
-moz-image-rect - CSS: Cascading Style Sheets
(var i=1; i<=4; i++) { var curid = "box" + i; // shift the background images var curstyle = window.getcomputedstyle(document.getelementbyid(curid), null).getpropertyvalue("background-image"); document.getelementbyid(curid).style.backgroundimage = prevstyle; prevstyle = curstyle; } } this uses window.getcomputedstyle() to fetch the style of each element, shifting it to the following element.
-moz-orient - CSS: Cascading Style Sheets
formal definition initial valueinlineapplies toany element; it has an effect on progress and meter, but not on <input type="range"> or other elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax inline | block | horizontal | vertical examples html <p> the following progress meter is horizontal (the default): </p> <progress max="100" value="75"></progress> <p> the following progress meter is vertical: </p> <progress class="vert" max="100" value="75"></progress> css .vert { -moz-orient: vertical; width: 16px; height: 150px; } result specifications not part of any standard.
-moz-outline-radius - CSS: Cascading Style Sheets
/* one value */ -moz-outline-radius: 25px; /* two values */ -moz-outline-radius: 25px 1em; /* three values */ -moz-outline-radius: 25px 1em 12%; /* four values */ -moz-outline-radius: 25px 1em 12% 4mm; /* global values */ -moz-outline-radius: inherit; -moz-outline-radius: initial; -moz-outline-radius: unset; constituent properties this property is a shorthand for the following css properties: -moz-outline-radius-bottomleft -moz-outline-radius-bottomright -moz-outline-radius-topleft -moz-outline-radius-topright syntax values elliptical outlines and <percentage> values follow the syntax described in border-radius.
-webkit-border-before - CSS: Cascading Style Sheets
syntax values one or more of the following, in any order: <'border-width'> see border-width <'border-style'> see border-style <'color'> see color formal definition initial valueas each of the properties of the shorthand:border-width: as each of the properties of the shorthand:border-top-width: mediumborder-right-width: mediumborder-bottom-width: mediumborder-left-width: mediumborder-style: as each of the properties of the short...
-webkit-text-stroke - CSS: Cascading Style Sheets
/* width and color values */ -webkit-text-stroke: 4px navy; text-stroke: 4px navy; /* global values */ -webkit-text-stroke: inherit; -webkit-text-stroke: initial; -webkit-text-stroke: unset; text-stroke: inherit; text-stroke: initial; text-stroke: unset; constituent properties this property is a shorthand for the following css properties: -webkit-stroke-color -webkit-stroke-width syntax values <length> the width of the stroke.
:-moz-ui-invalid - CSS: Cascading Style Sheets
this pseudo-class is applied according to the following rules: if the control does not have focus, and the value is invalid, apply this pseudo-class.
:-moz-ui-valid - CSS: Cascading Style Sheets
this pseudo-class is applied according to the following rules: if the control does not have focus, and the value is valid, apply this pseudo-class.
::-webkit-scrollbar - CSS: Cascading Style Sheets
css scrollbar selectors you can use the following pseudo elements to customize various parts of the scrollbar for webkit browsers: ::-webkit-scrollbar — the entire scrollbar.
::cue-region - CSS: Cascading Style Sheets
syntax ::cue-region | ::cue-region( <selector> ) permitted properties rules whose selectors include this element may only use the following css properties: background background-attachment background-clip background-color background-image background-origin background-position background-repeat background-size color font font-family font-size font-stretch font-style font-variant font-weight line-height opacity outline outline-color outline-style outline-width ruby-position text-combine-upright text-decorati...
::slotted() - CSS: Cascading Style Sheets
WebCSS::slotted
'='<attr-modifier> = i | s examples highlighting slotted elements the following snippets are taken from our slotted-pseudo-element demo (see it live also).
:enabled - CSS: Cascading Style Sheets
WebCSS:enabled
/* selects any enabled <input> */ input:enabled { color: blue; } syntax :enabled examples the following example makes the color of text and button <input>s green when enabled, and gray when disabled.
:fullscreen - CSS: Cascading Style Sheets
#fs-toggle:not(:fullscreen) { background-color: #afa; } when the document is in full-screen mode, the following css applies instead, setting the background color to a pale shade of red.
:has() - CSS: Cascading Style Sheets
WebCSS:has
examples matching <a> elements that directly contain an <img> the following selector matches only <a> elements that directly contain an <img> child: a:has(> img) matching <h1> elements that are followed by a <p> the following selector matches <h1> elements only if they have a <p> element directly following them: h1:has(+ p) specifications specification status comment selectors level 4the definition of ':has()' in that specification.
:host() - CSS: Cascading Style Sheets
WebCSS:host()
'='<attr-modifier> = i | s examples selectively styling shadow hosts the following snippets are taken from our host-selectors example (see it live also).
:host-context() - CSS: Cascading Style Sheets
'='<attr-modifier> = i | s examples selectively styling shadow hosts the following snippets are taken from our host-selectors example (see it live also).
:host - CSS: Cascading Style Sheets
WebCSS:host
/* selects a shadow root host */ :host { font-weight: bold; } syntax :host examples styling the shadow host the following snippets are taken from our host-selectors example (see it live also).
:nth-child() - CSS: Cascading Style Sheets
:nth-child(n+7) represents the seventh and all following elements: 7 [=0+7], 8 [=1+7], 9 [=2+7], etc.
:placeholder-shown - CSS: Cascading Style Sheets
html <input id="input1" placeholder="name, rank, and serial number"> <br><br> <input id="input2" placeholder="name, rank, and serial number"> css #input2:placeholder-shown { text-overflow: ellipsis; } result customized input field the following example highlights the branch and id code fields with a custom style.
:target - CSS: Cascading Style Sheets
WebCSS:target
/* selects an element with an id matching the current url's fragment */ :target { border: 2px solid black; } for example, the following url has a fragment (denoted by the # sign) that points to an element called section2: http://www.example.com/index.html#section2 the following element would be selected by a :target selector when the current url is equal to the above: <section id="section2">example</section> syntax :target examples a table of contents the :target pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents.
:valid - CSS: Cascading Style Sheets
WebCSS:valid
syntax :valid examples indicating valid and invalid form fields in this example, we use structures like this, which include extra <span>s to generate content on; we'll use these to provide indicators of valid/invalid data: <div> <label for="fname">first name *: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> to provide these indicators, we use the following css: input + span { position: relative; } input + span::before { position: absolute; right: -20px; top: 5px; } input:invalid { border: 2px solid red; } input:invalid + span::before { content: '✖'; color: red; } input:valid + span::before { content: '✓'; color: green; } we set the <span>s to position: relative so that we can position the generated content relative to th...
symbols - CSS: Cascading Style Sheets
this must be one of the following data types: <string> <image> (note: this value is "at risk" and may be removed from the specification.
system - CSS: Cascading Style Sheets
"; } ul { list-style: abc; } result numeric counter with numeric symbols as shown in the following example, if digits from 0 to 9 are specified as symbols, this counter style will render symbols same as the decimal counter style.
font-stretch - CSS: Cascading Style Sheets
understanding wcag 2.0 formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax <font-stretch-absolute>{1,2}where <font-stretch-absolute> = normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | <percentage> examples setting a percentage range for font-stretch the following find a local open sans font or import it, and allow using the font for normal, semi-condensed and semi-expanded states.
font-style - CSS: Cascading Style Sheets
formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax normal | italic | oblique <angle>{0,2} examples specifying an italic font style as an example, consider the garamond font family, in its normal form, we get the following result: @font-face { font-family: garamond; src: url('garamond.ttf'); } the italicized version of this text uses the same glyphs present in the unstyled version, but they are artificially sloped by a few degrees.
@font-face - CSS: Cascading Style Sheets
for example, the following will not work: .classname { @font-face { font-family: myhelvetica; src: local("helvetica neue bold"), local("helveticaneue-bold"), url(mgopenmodernabold.ttf); font-weight: bold; } } formal syntax @font-face { [ font-family: <family-name>; ] | [ src: <src>; ] | [ unicode-range: <unicode-range>; ] | [ font-variant: <font-variant>; ] | [ font-featur...
prefers-reduced-data - CSS: Cascading Style Sheets
examples note: no browser currently implements this feature so the following example will not work.
prefers-reduced-transparency - CSS: Cascading Style Sheets
examples note: no browser currently implements this feature so the following example will not work.
Alternative style sheets - CSS: Cascading Style Sheets
details any stylesheet in a document falls into one of the following categories: persistent (no rel="alternate", no title=""): always applies to the document.
CSS Animations tips and tricks - CSS: Cascading Style Sheets
the following demo shows how you'd achieve the aforementioned javascript technique: .slidein { animation-duration: 5s; animation-name: slidein; animation-iteration-count: infinite; } .stopped { animation-name: none; } @keyframes slidein { 0% { margin-left: 0%; } 50% { margin-left: 50%; } 100% { margin-left: 0%; } } <h1 id="watchme">click me to stop</h1> let watchme = docu...
Using multiple backgrounds - CSS: Cascading Style Sheets
that is, the following background properties can be specified as a list, one per background: background, background-attachment, background-clip, background-image, background-origin, background-position, background-repeat, background-size.
Using URL values for the cursor property - CSS: Cascading Style Sheets
for example, the following value would be allowed: cursor: url(foo.cur), url(http://www.example.com/bar.gif), auto; this will first try loading foo.cur.
Handling content breaks in multicol - CSS: Cascading Style Sheets
they take the following values when in a multicol context: auto avoid avoid-column column in this next example, we are forcing a column break before an h2 element.
CSS Multi-column Layout - CSS: Cascading Style Sheets
basic example in the following example the column-count property has been applied to the element with a class of container.
CSS Containment - CSS: Cascading Style Sheets
to gain as much containment as possible use contain: strict, which behaves the same as contain: size layout paint, or perhaps the following to also add style containment in browsers that support it: contain: strict; contain: strict style; reference css properties contain external resources an introduction to css containment ...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
the align-content property takes the following values: align-content: flex-start align-content: flex-end align-content: center align-content: space-between align-content: space-around align-content: stretch align-content: space-evenly (not defined in the flexbox specification) in the live example below, the flex container has a height of 400 pixels, which is more than needed to display our items.
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
instead, you will need to use a css pre-processor to make the most of the following.
Typical use cases of Flexbox - CSS: Cascading Style Sheets
this has now been made straightforward using the alignment properties in flexbox, as the following live example shows.
CSS Flexible Box Layout - CSS: Cascading Style Sheets
basic example in the following example a container has been set to display: flex, which means that the three child items become flex items.
Block and inline layout in normal flow - CSS: Cascading Style Sheets
in the following example, we have three inline boxes created by a paragraph with a <strong> element inside it.
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
the following example shows blocks using horizontal-tb.
CSS Flow Layout - CSS: Cascading Style Sheets
basic example the following example demonstrates block and inline level boxes.
OpenType font features guide - CSS: Cascading Style Sheets
the general syntax looks like this: .small-caps { font-feature-settings: "smcp", "c2sc"; } according to the specification you can either supply just the 4-character feature code or supply a 1 following the code (for enabling that feature) or a 0 (zero) to disable it.
CSS Fonts - CSS: Cascading Style Sheets
WebCSSCSS Fonts
basic example the following example shows a simple use of basic font properties to style a paragraph of text.
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
the following track listing will create an initial implicit row track as 100 pixels and a second as 200px.
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
the concept of visual display following document source order is detailed in the wcag techniques for success criteria – technique c27.
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
you should only do this if your items do not have a set order – and be aware of the issues of the tab order following the source and not your reordered display.
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
in the following markup, i have a grid and the first item on the grid is set to span all three column tracks.
Using CSS gradients - CSS: Cascading Style Sheets
the following are valid for all gradient functions: using more than two colors you don't have to limit yourself to two colors—you may use as many as you like!
Consistent list indentation - CSS: Cascading Style Sheets
if you want to reproduce the default display in netscape 6.x, you write: ul {margin-left: 0; padding-left: 40px;} if you're more interested in following the internet explorer/opera model, then: ul {margin-left: 40px; padding-left: 0;} of course, you can fill in your own preferred values.
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
using any four-value shorthand such as margin, padding, or border will currently use the physical versions, so if following the flow of the document is important, use the longhand properties for the time being.
CSS Overflow - CSS: Cascading Style Sheets
basic example the following interactive example shows how changing the value of the overflow property, changes how the overflow of a fixed height box is dealt with.
Using z-index - CSS: Cascading Style Sheets
in the following example, the layers' stacking order is rearranged using z-index.
Stacking context example 1 - CSS: Cascading Style Sheets
in terms of stacking contexts, div #1 and div #3 are simply assimilated into the root element, and the resulting hierarchy is the following: root stacking context div #2 (z-index 1) div #4 (z-index 2) note: div #1 and div #3 are not translucent.
Stacking context example 3 - CSS: Cascading Style Sheets
so a third-level menu will be stacked under the following second-level menus, because all second-level menus share the same z-index value and the default stacking rules apply.
Stacking without the z-index property - CSS: Cascading Style Sheets
when the z-index property is not specified on any element, elements are stacked in the following order (from bottom to top): the background and borders of the root element descendant non-positioned blocks, in order of appearance in the html descendant positioned elements, in order of appearance in the html keep in mind, when the order property alters rendering from the "order of appearance in the html" within flex containers, it similarly affects the order for stacking context.
CSS Properties Reference - CSS: Cascading Style Sheets
common css properties reference the following is a basic list of the most common css properties with the equivalent of the dom notation which is usually accessed from javascript: note: this list is incomplete.
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
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 five links that point to elements in the same document.
Basic Shapes - CSS: Cascading Style Sheets
we will see this in the following examples of basic shapes.
Shapes From Images - CSS: Cascading Style Sheets
many demos do this as it helps to show the shape we are following, however the shape-outside property is not related to the image that is displayed on the page and so you do not need to display an image to use an image to create a shape.
CSS Shapes - CSS: Cascading Style Sheets
the specification defines a number of different ways to define a shape on a floated element, causing wrapping lines to wrap round the shape rather than following the rectangle of the element's box.
CSS data types - CSS: Cascading Style Sheets
WebCSSCSS Types
index the data types defined by the set of css specifications include the following: <angle> <angle-percentage> <angular-color-hint> <angular-color-stop> <attr-fallback> <attr-name> <basic-shape> <blend-mode> <calc-product> <calc-sum> <calc-value> <color> <color-stop> <color-stop-angle> <counter-style> <custom-ident> <dimension> <filter-function> <flex> <frequency> <frequency-percentage> <gradient> <ident> <image> <integer> <length> <length-percentage> <number> <number-percentage> <percentage> <position>...
Class selectors - CSS: Cascading Style Sheets
ll elements with class="spacious" */ .spacious { margin: 2em; } /* all <li> elements with class="spacious" */ li.spacious { margin: 2em; } /* all <li> elements with a class list that includes both "spacious" and "elegant" */ /* for example, class="elegant retro spacious" */ li.spacious.elegant { margin: 2em; } syntax .class_name { style properties } note that this is equivalent to the following attribute selector: [class~=class_name] { style properties } examples css .red { color: #f33; } .yellow-bg { background: #ffa; } .fancy { font-weight: bold; text-shadow: 4px 4px 3px #77f; } html <p class="red">this paragraph has red text.</p> <p class="red yellow-bg">this paragraph has red text and a yellow background.</p> <p class="red fancy">this paragraph has red text and "fan...
Layout and the containing block - CSS: Cascading Style Sheets
if the position property is absolute or fixed, the containing block may also be formed by the edge of the padding box of the nearest ancestor element that has the following: a transform or perspective value other than none a will-change value of transform or perspective a filter value other than none or a will-change value of filter (only works on firefox).
ID selectors - CSS: Cascading Style Sheets
/* the element with id="demo" */ #demo { border: red 2px solid; } syntax #id_value { style properties } note that syntactically (but not specificity-wise), this is equivalent to the following attribute selector: [id=id_value] { style properties } examples css #identified { background-color: skyblue; } html <div id="identified">this div has a special id on it!</div> <div>this is just a regular div.</div> result specifications specification status comment selectors level 4the definition of 'id selectors' in that specification.
Card - CSS: Cascading Style Sheets
when setting up the single column grid i use the following: .card { display: grid; grid-template-rows: max-content 200px 1fr; } the heading track is set to max-content, which prevents it from stretching.
Recipe: Media objects - CSS: Cascading Style Sheets
requirements media object pattern needs some or all of the following characteristics: stacked on mobile, two columns on desktop.
CSS reference - CSS: Cascading Style Sheets
WebCSSReference
-timing-functiontranslatetranslate()translate3d()translatex()translatey()translatez()turnuunicode-bidiunicode-range (@font-face)unset<url>url()user-zoom (@viewport)v:validvar()vertical-alignvh@viewportviewport-fit (@viewport)visibility:visitedvmaxvminvwwwhite-spacewidowswidthwidth (@viewport)will-changeword-breakword-spacingword-wrapwriting-modexxzz-indexzoom (@viewport)others--* selectors the following are the various selectors, which allow styles to be conditional based on various features of elements within the dom.
Selector list - CSS: Cascading Style Sheets
#main, .content, article { font-size: 1.1em; } selector list invalidation a downside to using selector lists is that the following aren't equivalent: h1 { font-family: sans-serif } h2:maybe-unsupported { font-family: sans-serif } h3 { font-family: sans-serif } h1, h2:maybe-unsupported, h3 { font-family: sans-serif } this is because a single unsupported selector in a selector list invalidates the whole rule.
Visual formatting model - CSS: Cascading Style Sheets
in the following example, the line boxes following the floated <div> are shortened to wrap around the float.
animation-fill-mode - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-fill-mode>#where <single-animation-fill-mode> = none | forwards | backwards | both examples you can see the effect of animation-fill-mode in the following example.
animation-timing-function - CSS: Cascading Style Sheets
whether the animation holds temporarily at 0%, 20%, 40%, 60% and 80%, on the 20%, 40%, 60%, 80% and 100%, or makes 5 stops between the 0% and 100% along the animation, or makes 5 stops including the 0% and 100% marks (on the 0%, 25%, 50%, 75%, and 100%) depends on which of the following jump terms is used: jump-start denotes a left-continuous function, so that the first jump happens when the animation begins; jump-end denotes a right-continuous function, so that the last jump happens when the animation ends; jump-none there is no jump on either end.
background-position-x - CSS: Cascading Style Sheets
]#where <length-percentage> = <length> | <percentage> examples basic example the following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image's horizontal and vertical positions separately.
background-position-y - CSS: Cascading Style Sheets
]#where <length-percentage> = <length> | <percentage> examples basic example the following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image's horizontal and vertical positions separately.
background-size - CSS: Cascading Style Sheets
ground-size: 3em 25%; background-size: auto 6px; background-size: auto auto; /* multiple backgrounds */ background-size: auto, auto; /* not to be confused with `auto auto` */ background-size: 50%, 25%, 25%; background-size: 6px, auto, contain; /* global values */ background-size: inherit; background-size: initial; background-size: unset; the background-size property is specified in one of the following ways: using the keyword values contain or cover.
<basic-shape> - CSS: Cascading Style Sheets
shape functions the following shapes are supported.
<blend-mode> - CSS: Cascading Style Sheets
examples blend mode comparison in the following example, we have a <div> with two background images set on it — a firefox logo on top of a linear gradient.
border-block - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-block-color border-block-style border-block-width syntax values the border-block is specified with one or more of the following, in any order: <'border-width'> the width of the border.
border-bottom-width - CSS: Cascading Style Sheets
if it's a keyword, it must be one of the following values: thin a thin border medium a medium border thick a thick border note: because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific.
border-bottom - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-bottom-color border-bottom-style border-bottom-width syntax border-bottom: 1px; border-bottom: 2px dotted; border-bottom: medium dashed blue; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted.
border-color - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-bottom-color border-left-color border-right-color border-top-color syntax /* <color> values */ border-color: red; /* horizontal | vertical */ border-color: red #f015ca; /* top | vertical | bottom */ border-color: red rgb(240,30,50,.7) green; /* top | right | bottom | left */ border-color: red yellow green blue; /* global values */ border-color: inherit; border-...
border-image-width - CSS: Cascading Style Sheets
t-letter.inheritednopercentagesrefer to the width or height of the border image areacomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typeby computed value type formal syntax [ <length-percentage> | <number> | auto ]{1,4}where <length-percentage> = <length> | <percentage> examples tiling a border image this example creates a border image using the following ".png" file, which is 90 by 90 pixels: thus, each circle in the source image is 30 by 30 pixels.
border-image - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-image-outset border-image-repeat border-image-slice border-image-source border-image-width syntax /* source | slice */ border-image: linear-gradient(red, blue) 27; /* source | slice | repeat */ border-image: url("/images/border.png") 27 space; /* source | slice | width */ border-image: linear-gradient(red, blue) 27 / 35px; /* source | slice | width | outset | r...
border-inline - CSS: Cascading Style Sheets
rthand:border-top-width: mediumborder-top-style: noneborder-top-color: currentcolorapplies toall elementsinheritednocomputed valueas each of the properties of the shorthand:border-top-width: the absolute length or 0 if border-top-style is none or hiddenborder-top-style: as specifiedborder-top-color: computed coloranimation typediscrete constituent properties this property is a shorthand for the following css properties: border-inline-color border-inline-style border-inline-width syntax values the border-inline is specified with one or more of the following, in any order: <'border-width'> the width of the border.
border-left-width - CSS: Cascading Style Sheets
if it's a keyword, it must be one of the following values: thin a thin border medium a medium border thick a thick border note: because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific.
border-left - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-left-color border-left-style border-left-width syntax border-left: 1px; border-left: 2px dotted; border-left: medium dashed green; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted.
border-radius - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-bottom-left-radius border-bottom-right-radius border-top-left-radius border-top-right-radius syntax /* the syntax of the first radius allows one to four values */ /* radius is set for all 4 sides */ border-radius: 10px; /* top-left-and-bottom-right | top-right-and-bottom-left */ border-radius: 10px 5%; /* top-left | top-right-and-bottom-left | bottom-right */ bor...
border-right-width - CSS: Cascading Style Sheets
if it's a keyword, it must be one of the following values: thin a thin border medium a medium border thick a thick border note: because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific.
border-right - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-right-color border-right-style border-right-width syntax border-right: 1px; border-right: 2px dotted; border-right: medium dashed green; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted.
border-top-width - CSS: Cascading Style Sheets
if it's a keyword, it must be one of the following values: thin a thin border medium a medium border thick a thick border note: because the specification doesn't define the exact thickness denoted by each keyword, the precise result when using one of them is implementation-specific.
border-top - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: border-top-color border-top-style border-top-width syntax border-top: 1px; border-top: 2px dotted; border-top: medium dashed green; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted.
box-decoration-break - CSS: Cascading Style Sheets
the specified value will impact the appearance of the following properties: background border border-image box-shadow clip-path margin padding syntax /* keyword values */ box-decoration-break: slice; box-decoration-break: clone; /* global values */ box-decoration-break: initial; box-decoration-break: inherit; box-decoration-break: unset; the box-decoration-break property is specified as one of the keyword values listed below.
color-adjust - CSS: Cascading Style Sheets
syntax color-adjust: economy; color-adjust: exact; the color-adjust property's value must be one of the following keywords.
color - CSS: Cascading Style Sheets
WebCSScolor
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples making text red the following are all ways to make a paragraph's text red: p { color: red; } p { color: #f00; } p { color: #ff0000; } p { color: rgb(255,0,0); } p { color: rgb(100%, 0%, 0%); } p { color: hsl(0, 100%, 50%); } /* 50% translucent */ p { color: #ff000080; } p { color: rgba(255, 0, 0, 0.5); } p { color: hsla(0, 100%, 50%, 0.5); } specifications specification status comment css c...
columns - CSS: Cascading Style Sheets
WebCSScolumns
constituent properties this property is a shorthand for the following css properties: column-count column-width syntax /* column width */ columns: 18em; /* column count */ columns: auto; columns: 2; /* both column width and count */ columns: 2 auto; columns: auto 12em; columns: auto auto; /* global values */ columns: inherit; columns: initial; columns: unset; the columns property may be specified as one or two of the values listed below, in any order.
contain - CSS: Cascading Style Sheets
WebCSScontain
syntax /* keyword values */ contain: none; contain: strict; contain: content; contain: size; contain: layout; contain: style; contain: paint; /* multiple keywords */ contain: size paint; contain: size layout paint; /* global values */ contain: inherit; contain: initial; contain: unset; the contain property is specified as either one of the following: using a single none, strict, or content keyword.
counter-increment - CSS: Cascading Style Sheets
nt: my-counter -1; /* increment "counter1" by 1, and decrement "counter2" by 4 */ counter-increment: counter1 counter2 -4; /* do not increment/decrement anything: used to override less specific rules */ counter-increment: none; /* global values */ counter-increment: inherit; counter-increment: initial; counter-increment: unset; the counter-increment property is specified as either one of the following: a <custom-ident> naming the counter, followed optionally by an <integer>.
counter-reset - CSS: Cascading Style Sheets
unter; /* set "my-counter" to -1 */ counter-reset: my-counter -1; /* set "counter1" to 1, and "counter2" to 4 */ counter-reset: counter1 1 counter2 4; /* cancel any reset that could have been set in less specific rules */ counter-reset: none; /* global values */ counter-reset: inherit; counter-reset: initial; counter-reset: unset; the counter-reset property is specified as either one of the following: a <custom-ident> naming the counter, followed optionally by an <integer>.
counter-set - CSS: Cascading Style Sheets
r-set: my-counter; /* set "my-counter" to -1 */ counter-set: my-counter -1; /* set "counter1" to 1, and "counter2" to 4 */ counter-set: counter1 1 counter2 4; /* cancel any counter that could have been set in less specific rules */ counter-set: none; /* global values */ counter-set: inherit; counter-set: initial; counter-set: unset; the counter-set property is specified as either one of the following: a <custom-ident> naming the counter, followed optionally by an <integer>.
cross-fade() - CSS: Cascading Style Sheets
the two following are lines (almost) identical: cross-fade( url(red.png), url(yellow.png), url(blue.png)); /* all three will be 33.3333% opaque */ cross-fade( url(red.png) 33.33%, url(yellow.png) 33.33%, url(blue.png) 33.33%); older, implemented syntax cross-fade( <image, <image>, <percentage> ) the specification for the cross-fade() function allows for multiple images and for each image to have transparency v...
<custom-ident> - CSS: Cascading Style Sheets
it consists of one or more characters, where characters can be any of the following: any alphabetical character (a to z, or a to z), any decimal digit (0 to 9), a hyphen (-), an underscore (_), an escaped character (preceded by a backslash, \), a unicode character (in the format of a backslash, \, followed by one to six hexadecimal digits, representing its unicode code point) note that id1, id1, id1 and id1 are all different identifiers as they are case-sensitive.
<display-internal> - CSS: Cascading Style Sheets
examples css tables example the following example demonstrates laying out a simple form using css table layout.
<display-outside> - CSS: Cascading Style Sheets
examples in the following example, span elements (normally displayed as inline elements) are set to display: block and so break onto new lines and expand to fill their container in the inline dimension.
display - CSS: Cascading Style Sheets
WebCSSdisplay
in addition, see the following material, which covers the various values of display in depth.
flex-direction - CSS: Cascading Style Sheets
syntax /* the direction text is laid out in a line */ flex-direction: row; /* like <row>, but reversed */ flex-direction: row-reverse; /* the direction in which lines of text are stacked */ flex-direction: column; /* like <column>, but reversed */ flex-direction: column-reverse; /* global values */ flex-direction: inherit; flex-direction: initial; flex-direction: unset; values the following values are accepted: row the flex container's main-axis is defined to be the same as the text direction.
flex-flow - CSS: Cascading Style Sheets
WebCSSflex-flow
constituent properties this property is a shorthand for the following css properties: flex-direction flex-wrap syntax /* flex-flow: <'flex-direction'> */ flex-flow: row; flex-flow: row-reverse; flex-flow: column; flex-flow: column-reverse; /* flex-flow: <'flex-wrap'> */ flex-flow: nowrap; flex-flow: wrap; flex-flow: wrap-reverse; /* flex-flow: <'flex-direction'> and <'flex-wrap'> */ flex-flow: row nowrap; flex-flow: column wrap; flex-flow: column-reverse w...
flex-wrap - CSS: Cascading Style Sheets
WebCSSflex-wrap
values the following values are accepted: nowrap the flex items are laid out in a single line which may cause the flex container to overflow.
font-smooth - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | never | always | <absolute-size> | <length>where <absolute-size> = xx-small | x-small | small | medium | large | x-large | xx-large | xxx-large examples basic usage example the following example shows the safari/chromium and firefox equivalents that turn on font-smoothing on macos.
font-synthesis - CSS: Cascading Style Sheets
syntax this property can take any one of the following forms: the keyword value none.
font-variant - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: font-variant-alternates font-variant-caps font-variant-east-asian font-variant-ligatures font-variant-numeric syntax font-variant: small-caps; font-variant: common-ligatures small-caps; /* global values */ font-variant: inherit; font-variant: initial; font-variant: unset; values normal specifies a normal font face; each of the longhand properties has an initi...
font - CSS: Cascading Style Sheets
WebCSSfont
constituent properties this property is a shorthand for the following css properties: font-family font-size font-stretch font-style font-variant font-weight line-height syntax the font property may be specified as either a single keyword, which will select a system font, or as a shorthand for various font-related properties.
grid-area - CSS: Cascading Style Sheets
WebCSSgrid-area
constituent properties this property is a shorthand for the following css properties: grid-column-end grid-column-start grid-row-end grid-row-start syntax /* keyword values */ grid-area: auto; grid-area: auto / auto; grid-area: auto / auto / auto; grid-area: auto / auto / auto / auto; /* <custom-ident> values */ grid-area: some-grid-area; grid-area: some-grid-area / another-grid-area; /* <integer> && <custom-ident>?
grid-column - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: grid-column-end grid-column-start syntax this property is specified as one or two <grid-line> values.
grid-row - CSS: Cascading Style Sheets
WebCSSgrid-row
constituent properties this property is a shorthand for the following css properties: grid-row-end grid-row-start syntax /* keyword values */ grid-row: auto; grid-row: auto / auto; /* <custom-ident> values */ grid-row: somegridarea; grid-row: somegridarea / someothergridarea; /* <integer> + <custom-ident> values */ grid-row: somegridarea 4; grid-row: 4 somegridarea / 6; /* span + <integer> + <custom-ident> values */ grid-row: span 3; grid-row: span somegr...
grid - CSS: Cascading Style Sheets
WebCSSgrid
constituent properties this property is a shorthand for the following css properties: grid-auto-columns grid-auto-flow grid-auto-rows grid-template-areas grid-template-columns grid-template-rows syntax /* <'grid-template'> values */ grid: none; grid: "a" 100px "b" 1fr; grid: [linename1] "a" 100px [linename2]; grid: "a" 200px "b" min-content; grid: "a" minmax(100px, max-content) "b" 20%; grid: 100px / 200px; grid: minmax(400px, min-content) / repeat(auto-...
hanging-punctuation - CSS: Cascading Style Sheets
two-value syntax uses one of the following: first together with any one of last, allow-end, or force-end last together with any one of first, allow-end, or force-end three-value syntax uses one of the following: first, allow-end, and last first, force-end, and last values none no character hangs.
hyphens - CSS: Cascading Style Sheets
WebCSShyphens
auto the browser is free to automatically break words at appropriate hyphenation points, following whatever rules it chooses.
ident - CSS: Cascading Style Sheets
WebCSSident
it consists of one or more characters, where characters can be any of the following: any alphabetical character (a to z, or a to z), any decimal digit (0 to 9), a hyphen (-), an underscore (_), an escaped character (preceded by a backslash, \), a unicode character (in the format of a backslash, \, followed by one to six hexadecimal digits, representing its unicode code point) note that id1, id1, id1 and id1 are all different identifiers as they are case-sensitive.
ime-mode - CSS: Cascading Style Sheets
WebCSSime-mode
users may correct the inappropriate behavior of sites that don't follow this recommendation by placing the following css into their user stylesheet: input[type=password] { ime-mode: auto !important; } the mac version of gecko 1.9 (firefox 3) can't recover the previous state of the ime when a field for which it is disabled loses focus, so mac users may get grumpy when you use the disabled value.
inset-block - CSS: Cascading Style Sheets
<length> values */ inset-block: 3px 10px; inset-block: 2.4em 3em; inset-block: 10px; /* value applied to start and end */ /* <percentage>s of the width or height of the containing block */ inset-block: 10% 5%; /* keyword value */ inset-block: auto; /* global values */ inset-block: inherit; inset-block: initial; inset-block: unset; constituent properties this property is a shorthand for the following css properties: inset-block-end inset-block-start syntax values the inset-block property takes the same values as the left property.
inset-inline - CSS: Cascading Style Sheets
> values */ inset-inline: 3px 10px; inset-inline: 2.4em 3em; inset-inline: 10px; /* value applied to start and end */ /* <percentage>s of the width or height of the containing block */ inset-inline: 10% 5%; /* keyword value */ inset-inline: auto; /* global values */ inset-inline: inherit; inset-inline: initial; inset-inline: unset; constituent properties this property is a shorthand for the following css properties: inset-inline-end inset-inline-start syntax values the inset-inline property takes the same values as the left property.
justify-items - CSS: Cascading Style Sheets
baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end examples simple demonstration in the following example we have a simple 2 x 2 grid layout.
justify-self - CSS: Cascading Style Sheets
baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end examples simple demonstration in the following example we have a simple 2 x 2 grid layout.
<length> - CSS: Cascading Style Sheets
WebCSSlength
examples length unit comparison the following demo provides you with an input field in which you can enter a <length> value (e.g.
line-height - CSS: Cascading Style Sheets
syntax /* keyword value */ line-height: normal; /* unitless values: use this number multiplied by the element's font size */ line-height: 3.5; /* <length> values */ line-height: 3em; /* <percentage> values */ line-height: 34%; /* global values */ line-height: inherit; line-height: initial; line-height: unset; the line-height property is specified as any one of the following: a <number> a <length> a <percentage> the keyword normal.
list-style - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: list-style-image list-style-position list-style-type syntax /* type */ list-style: square; /* image */ list-style: url('../img/shape.png'); /* position */ list-style: inside; /* type | position */ list-style: georgian inside; /* type | image | position */ list-style: lower-roman url('../img/shape.png') outside; /* keyword value */ list-style: none; /* global values *...
margin-block - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: margin-block-end margin-block-start syntax values the margin-block property takes the same values as the margin-left property.
margin-inline - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: margin-inline-end margin-inline-start syntax values the margin-inline property takes the same values as the margin-left property.
mask-border - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: mask-border-mode mask-border-outset mask-border-repeat mask-border-slice mask-border-source mask-border-width syntax /* source | slice */ mask-border: url('border-mask.png') 25; /* source | slice | repeat */ mask-border: url('border-mask.png') 25 space; /* source | slice | width */ mask-border: url('border-mask.png') 25 / 35px; /* source | slice | width | outset | repeat | mode */ mask-border: url('border-mask.png') 25 / 35px / 12px space alpha; values <'mask-border-source'> the source image.
mask - CSS: Cascading Style Sheets
WebCSSmask
constituent properties this property is a shorthand for the following css properties: mask-clip mask-composite mask-image mask-mode mask-origin mask-position mask-repeat mask-size syntax /* keyword values */ mask: none; /* image values */ mask: url(mask.png); /* pixel image used as mask */ mask: url(masks.svg#star); /* element within svg graphic used as mask */ /* combined values */ mask: url(masks.svg#star) lumi...
offset-anchor - CSS: Cascading Style Sheets
| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage> examples setting various offset-anchor values in the following example, we have three <div> elements nested in <section> elements.
offset - CSS: Cascading Style Sheets
WebCSSoffset
constituent properties this property is a shorthand for the following css properties: offset-anchor offset-distance offset-path offset-position offset-rotate syntax /* offset position */ offset: auto; offset: 10px 30px; offset: none; /* offset path */ offset: ray(45deg closest-side); offset: path('m 100 100 l 300 100 l 200 300 z'); offset: url(arc.svg); /* offset path with distance and/or rotation */ offset: url(circle.svg) 100px; offset: url(circle.svg) 40%; offset: url(circle.svg) 30deg; offset: url(circle.svg) 50px 20deg; /* including offset anchor */ offset: ray(45deg closest-side) / 40px 20px; offset: ...
orphans - CSS: Cascading Style Sheets
WebCSSorphans
(the paragraph continues on a following page.) syntax values <integer> the minimum number of lines that can stay by themselves at the bottom of a fragment before a fragmentation break.
Guide to scroll anchoring - CSS: Cascading Style Sheets
these suppression triggers are changes to the computed value of any of the following properties: top, left, right, or bottom margin or padding any width or height-related properties transform additionally, position changes anywhere inside the scrolling box also disable scroll anchoring.
overflow - CSS: Cascading Style Sheets
WebCSSoverflow
constituent properties this property is a shorthand for the following css properties: overflow-x overflow-y syntax /* keyword values */ overflow: visible; overflow: hidden; overflow: clip; overflow: scroll; overflow: auto; overflow: hidden visible; /* global values */ overflow: inherit; overflow: initial; overflow: unset; the overflow property is specified as one or two keywords chosen from the list of values below.
padding-block - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: padding-block-end padding-block-start syntax values the padding-block property takes the same values as the padding-left property.
padding-inline - CSS: Cascading Style Sheets
n absolute length */ padding-inline: 1em 2em; /* relative to the text size */ padding-inline: 10px; /* sets both start and end values */ /* <percentage> values */ padding-inline: 5% 2%; /* relative to the nearest block container's width */ /* global values */ padding-inline: inherit; padding-inline: initial; padding-inline: unset; constituent properties this property is a shorthand for the following css properties: padding-inline-end padding-inline-start syntax values the padding-inline property takes the same values as the padding-left property.
padding - CSS: Cascading Style Sheets
WebCSSpadding
constituent properties this property is a shorthand for the following css properties: padding-bottom padding-left padding-right padding-top syntax /* apply to all four sides */ padding: 1em; /* vertical | horizontal */ padding: 5% 10%; /* top | horizontal | bottom */ padding: 1em 2em 2em; /* top | right | bottom | left */ padding: 5px 1em 0 2em; /* global values */ padding: inherit; padding: initial; padding: unset; the padding property may be specif...
place-content - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: align-content justify-content syntax /* positional alignment */ /* align-content does not take left and right values */ place-content: center start; place-content: start center; place-content: end left; place-content: flex-start center; place-content: flex-end center; /* baseline alignment */ /* justify-content does not take baseline values */ place-content: baseline cente...
place-items - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: align-items justify-items syntax /* keyword values */ place-items: auto center; place-items: normal start; /* positional alignment */ place-items: center normal; place-items: start auto; place-items: end normal; place-items: self-start auto; place-items: self-end normal; place-items: flex-start auto; place-items: flex-end normal; place-items: left auto; place-items: right ...
repeating-conic-gradient() - CSS: Cascading Style Sheets
the following two gradients are equivalent repeating-conic-gradient(red, orange, yellow, green, blue 50%); repeating-conic-gradient(from -45deg, red 45deg, orange, yellow, green, blue 225deg) by default, colors transition smoothly from the color at one color stop to the color at the subsequent color stop, with the midpoint between the colors being the half way point between the color transition.
resize - CSS: Cascading Style Sheets
WebCSSresize
resize does not apply to the following: inline elements block elements for which the overflow property is set to visible formal definition initial valuenoneapplies toelements with overflow other than visible, and optionally replaced elements representing images or videos, and iframesinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | both | horizontal | vertical | block | inline examples disabli...
scroll-margin-block - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: scroll-margin-block-end scroll-margin-block-start syntax /* <length> values */ scroll-margin-block: 10px; scroll-margin-block: 1em .5em ; /* global values */ scroll-margin-block: inherit; scroll-margin-block: initial; scroll-margin-block: unset; values <length> an outset from the corresponding edge of the scroll container.
scroll-margin-inline - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: scroll-margin-inline-end scroll-margin-inline-start syntax /* <length> values */ scroll-margin-inline: 10px; scroll-margin-inline: 1em .5em ; /* global values */ scroll-margin-inline: inherit; scroll-margin-inline: initial; scroll-margin-inline: unset; values <length> an outset from the corresponding edge of the scroll container.
scroll-margin - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: scroll-margin-bottom scroll-margin-left scroll-margin-right scroll-margin-top syntax /* <length> values */ scroll-margin: 10px; scroll-margin: 1em .5em 1em 1em; /* global values */ scroll-margin: inherit; scroll-margin: initial; scroll-margin: unset; values <length> an outset from the corresponding edge of the scroll container.
scroll-padding-block - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: scroll-padding-block-end scroll-padding-block-start syntax /* keyword values */ scroll-padding-block: auto; /* <length> values */ scroll-padding-block: 10px; scroll-padding-block: 1em .5em; scroll-padding-block: 10%; /* global values */ scroll-padding-block: inherit; scroll-padding-block: initial; scroll-padding-block: unset; values <length-percentage> an inwards of...
scroll-padding-inline - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: scroll-padding-inline-end scroll-padding-inline-start syntax /* keyword values */ scroll-padding-inline: auto; /* <length> values */ scroll-padding-inline: 10px; scroll-padding-inline: 1em .5em; scroll-padding-inline: 10%; /* global values */ scroll-padding-inline: inherit; scroll-padding-inline: initial; scroll-padding-inline: unset; values <length-percentage> an i...
scroll-padding - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: scroll-padding-bottom scroll-padding-left scroll-padding-right scroll-padding-top syntax /* keyword values */ scroll-padding: auto; /* <length> values */ scroll-padding: 10px; scroll-padding: 1em .5em 1em 1em; scroll-padding: 10%; /* global values */ scroll-padding: inherit; scroll-padding: initial; scroll-padding: unset; values <length-percentage> an inwards offs...
scrollbar-width - CSS: Cascading Style Sheets
it must be one of the following values: auto the default scrollbar width for the platform.
shape-outside - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies tofloatsinheritednocomputed valueas defined for <basic-shape> (with <shape-box> following, if supplied), the <image> with its uri made absolute, otherwise as specified.animation typeyes, as specified for <basic-shape>, otherwise no formal syntax none | <shape-box> | <basic-shape> | <image>where <shape-box> = <box> | margin-box<basic-shape> = <inset()> | <circle()> | <ellipse()> | <polygon()> | <path()><image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fad...
Specified value - CSS: Cascading Style Sheets
the specified value for a given property is determined according to the following rules: if the document's style sheet explicitly specifies a value for the property, the given value will be used.
symbols() - CSS: Cascading Style Sheets
WebCSSsymbols
[ <string> | <image> ]+ ); <symbols-type> can be one of the following: cyclic: the system cycles through the given values in the order of their definition, and returns to the start when it reaches the end.
text-align - CSS: Cascading Style Sheets
-all; text-align: start; text-align: end; text-align: match-parent; /* character-based alignment in a table column */ text-align: "."; text-align: "." center; /* block alignment values (non-standard syntax) */ text-align: -moz-center; text-align: -webkit-center; /* global values */ text-align: inherit; text-align: initial; text-align: unset; the text-align property is specified in one of the following ways: using the keyword values start, end, left, right, center, justify, justify-all, or match-parent.
text-decoration - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: text-decoration-color text-decoration-line text-decoration-style text-decoration-thickness syntax the text-decoration property is specified as one or more space-separated values representing the various longhand text-decoration properties.
text-emphasis - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: text-emphasis-color text-emphasis-style syntax /* initial value */ text-emphasis: none; /* no emphasis marks */ /* <string> value */ text-emphasis: 'x'; text-emphasis: '点'; text-emphasis: '\25b2'; text-emphasis: '*' #555; text-emphasis: 'foo'; /* should not use.
text-transform - CSS: Cascading Style Sheets
the text-transform property takes into account language-specific case mapping rules such as the following: in turkic languages, like turkish (tr), azerbaijani (az), crimean tatar (crh), volga tatar (tt), and bashkir (ba), there are two kinds of i, with and without the dot, and two case pairings: i/İ and ı/i.
matrix() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 ac bd actxbdty001 actxbdty001 ac0txbd0ty00100001 [a b c d tx ty] the values represent the following functions: matrix( scalex(), skewy(), skewx(), scaley(), translatex(), translatey() ) examples html <div>normal</div> <div class="changed">changed</div> css div { width: 80px; height: 80px; background-color: skyblue; } .changed { transform: matrix(1, 2, -1, 1, 80, 80); background-color: pink; } result specifications specification status comment cs...
<transform-function> - CSS: Cascading Style Sheets
examples transform function comparison the following example provides a 3d cube created from dom elements and transforms, and a select menu allowing you to choose different transform functions to transform the cube with, so you can compare the effects of the different types.
transform-origin - CSS: Cascading Style Sheets
the keywords are convenience shorthands and match the following <percentage> values: keyword value left 0% center 50% right 100% top 0% bottom 100% formal definition initial value50% 50% 0applies totransformable elementsinheritednopercentagesrefer to the size of bounding boxcomputed valuefor <length> the absolute value, otherwise a percentageanimation typesimple list of lengt...
transition-timing-function - CSS: Cascading Style Sheets
whether the transition holds temporarily at 0%, 20%, 40%, 60% and 80%, on the 20%, 40%, 60%, 80% and 100%, or makes 5 stops between the 0% and 100% along the transition, or makes 5 stops including the 0% and 100% marks (on the 0%, 25%, 50%, 75%, and 100%) depends on which of the following jump terms is used: jump-start denotes a left-continuous function, so that the first jump happens when the transition begins; jump-end denotes a right-continuous function, so that the last jump happens when the animation ends; jump-none there is no jump on either end.
transition - CSS: Cascading Style Sheets
constituent properties this property is a shorthand for the following css properties: transition-delay transition-duration transition-property transition-timing-function syntax /* apply to 1 property */ /* property name | duration */ transition: margin-right 4s; /* property name | duration | delay */ transition: margin-right 4s 1s; /* property name | duration | timing function */ transition: margin-right 4s ease-in-out; /* property name | duration | tim...
unicode-bidi - CSS: Cascading Style Sheets
this value allows the display of data that is already formatted using a tool following the unicode bidirectional algorithm.
url() - CSS: Cascading Style Sheets
WebCSSurl()
the following are all valid and equivalent: <css_property>: url("https://example.com/image.png") <css_property>: url('https://example.com/image.png') <css_property>: url(https://example.com/image.png) path references the id of an svg shape -- circle, ellipse, line, path, polygon, polyline, or rect -- using the shape's geometry as the path.
Used value - CSS: Cascading Style Sheets
the following are the css 2.1 properties that do depend on layout, so they have a different computed value and used value: (taken from css 2.1 changes: specified, computed, and actual values): background-position bottom, left, right, top height, width margin-bottom, margin-left, margin-right, margin-top min-height, min-width padding-bottom, padding-left, padding-right, padding-top text-indent specif...
vertical-align - CSS: Cascading Style Sheets
line-relative values the following values vertically align the element relative to the entire line: top aligns the top of the element and its descendants with the top of the entire line.
white-space - CSS: Cascading Style Sheets
the following table summarizes the behavior of the various white-space values: new lines spaces and tabs text wrapping end-of-line spaces normal collapse collapse wrap remove nowrap collapse collapse no wrap remove pre preserve preserve no wrap preserve pre-wrap preserve preserve wrap hang pr...
width - CSS: Cascading Style Sheets
WebCSSwidth
syntax /* <length> values */ width: 300px; width: 25em; /* <percentage> value */ width: 75%; /* keyword values */ width: max-content; width: min-content; width: fit-content(20em); width: auto; /* global values */ width: inherit; width: initial; width: unset; the width property is specified as either: one of the following keyword values: min-content, max-content, fit-content, auto.
exsl:object-type() - EXSLT
returns the object's type, which will be one of the following: string number boolean node-set rtf external specifications exslt - exsl:object-type ...
regexp:match() - EXSLT
WebEXSLTregexpmatch
for example: <xsl:for-each select="regexp:match('http://developer.mozilla.org/en/docs/firefox_3_for_developers', '(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)')"> part <xsl:value-of select="position()" /> = <xsl:value-of select="." /> </xsl:for-each> this code generates the following output: part 1 = http://developer.mozilla.org/en/docs/firefox_3_for_developers part 2 = http part 3 = developer.mozilla.org part 4 = part 5 = /en/docs/firefox_3_for_developers specifications exslt - regexp:match ...
WAI ARIA Live Regions/API Support - Developer guides
retrieving author-supplied aria live region semantics from an event for any mutation event in a page, the author can get the following object attributes from the event object, if they are defined on some ancestor element (closest ancestor wins): object attribute name possible values default value if not specified meaning aria markup if required container-live "off" | "polite" | "assertive" "off" interruption policy aria-live on ancestor element container-relevant "[additions]...
Adding captions and subtitles to HTML5 video - Developer guides
mp4"> <source src="video/sintel-short.webm" type="video/webm"> <track label="english" kind="subtitles" srclang="en" src="captions/vtt/sintel-en.vtt" default> <track label="deutsch" kind="subtitles" srclang="de" src="captions/vtt/sintel-de.vtt"> <track label="español" kind="subtitles" srclang="es" src="captions/vtt/sintel-es.vtt"> </video> as you can see, each <track> element has the following attributes set: kind is given a value of subtitles, indicating the type of content the files contain label is given a value indicating which language that subtitle set is for — for example english or deutsch — these labels will appear in the user interface to allow the user to easily select which subtitle language they want to see.
Setting up adaptive streaming media sources - Developer guides
this article explains how, looking at two of the most common formats: mpeg-dash and hls (http live streaming.) choosing formats in terms of adaptive streaming formats, there are many to choose from; we decided to choose the following two as between them we can support most modern browsers.
Audio and video manipulation - Developer guides
libraries currently exist for the following formats : aac: aac.js alac: alac.js flac: flac.js mp3: mp3.js opus: opus.js vorbis: vorbis.js note: at audiocogs, you can try out a few demos; audiocogs also provides a framework, aurora.js, which is intended to help you author your own codecs in javascript.
Creating and triggering events - Developer guides
the following shows an example with document.createevent(): // create the event.
DOM onevent handlers - Developer guides
(the html specification names these: onblur, onerror, onfocus, onload, and onscroll.) event handler's parameters, this binding, and the return value when the event handler is specified as an html attribute, the specified code is wrapped into a function with the following parameters: event — for all event handlers except onerror.
Media events - Developer guides
you can easily watch for these events, using code such as the following: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("seeked", function() { v.play(); }, true); v.currenttime = 10.0; this example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes.
Mouse gesture events - Developer guides
direction constants the direction field in the gesture events can take one of the following values: simplegestureevent.direction_left leftward swipe.
Mutation events - Developer guides
mutation events list the following is a list of all mutation events, as defined in dom level 3 events specification: domattrmodified domattributenamechanged domcharacterdatamodified domelementnamechanged domnodeinserted domnodeinsertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified mutation observers alternatives examples domnoderemovedfromdocument var isdescendant = function (desc, root) {...
Using device orientation with 3D transforms - Developer guides
iew3d"); window.addeventlistener("deviceorientation", function(e) { // again, use vendor-prefixed transform property elem.style.transform = "rotatey(" + ( -e.gamma ) + "deg)" + "rotatex(" + e.beta + "deg) " + "rotatez(" + - ( e.alpha - 180 ) + "deg) "; }); rotate3d to orientation should you ever need to convert a rotate3d axis-angle to orientation euler angles, you can use the following algorithm: // convert a rotate3d axis-angle to deviceorientation angles function orient( aa ) { var x = aa.x, y = aa.y, z = aa.z, a = aa.a, c = math.cos( aa.a ), s = math.sin( aa.a ), t = 1 - c, // axis-angle to rotation matrix rm00 = c + x*x * t, rm10 = z*s + y*x * t, rm20 = -y*s + z*x * t, rm01 = -z*s + x*y * t, rm...
Using HTML sections and outlines - Developer guides
s that have javascript disabled that your page relies on javascript: <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> this leads to the following code to allow the support of the html5 sections and headings elements in non-html5 browsers, even for internet explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting: <!--[if lt ie 9]> <script> document.createelement("article"); document.createelement("aside"); document.createelement("footer"); document.createele...
Index - Developer guides
WebGuideIndex
it's not always possible to follow all of these, but following as many of them as possible will help future-proof your website.
Localizations and character encodings - Developer guides
to specify that a page is using, for example, the utf-8 character encoding (as per the recommendation), simply place the following line in the <head> block: <meta charset="utf-8"> details and browser internals when the encoding is declared by web content like the html specification requires, firefox will use that encoding for turning the bytes into the internal representation.
A hybrid approach - Developer guides
approaches to mobile web development see the following articles for background and other approaches to developing for mobile platforms.
Mobile-friendliness - Developer guides
approaches to mobile web development the following approaches aim to achieve each of these goals by different means.
Separate sites for mobile and desktop - Developer guides
approaches to mobile web development see the following articles for background and other approaches to developing for mobile platforms.
HTML attribute: pattern - HTML: Hypertext Markup Language
examples given the following: <p> <label>enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"...
HTML attribute: rel - HTML: Hypertext Markup Language
WebHTMLAttributesrel
the type of relationships is given by the value of the rel attribute, which, if present, must have a value that is an unordered set of unique space-separated keywords, which are listed in the following table.
HTML attribute reference - HTML: Hypertext Markup Language
the following examples are valid ways to mark up a boolean attribute: <div itemscope> this is valid html but invalid xml.
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
calling any of the following on a tainted canvas will result in an error: calling getimagedata() on the canvas's context calling toblob() on the <canvas> element itself calling todataurl() on the canvas attempting any of these when the canvas is tainted will cause a securityerror to be thrown.
<area> - HTML: Hypertext Markup Language
WebHTMLElementarea
the following keywords have special meanings: _self (default): show the resource in the current browsing context.
<bgsound>: The Background Sound element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementbgsound
src this attribute specifies the url of the sound file to be played, which must be one of the following types: .wav, .au, or .mid.
<blink>: The Blinking Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementblink
css polyfill if you really do need a polyfill, then you can use the following css polyfill.
<br>: The Line Break element - HTML: Hypertext Markup Language
WebHTMLElementbr
examples simple br in the following example we use <br> elements to create line breaks between the different lines of a postal address: mozilla<br> 331 e.
<button>: The Button element - HTML: Hypertext Markup Language
WebHTMLElementbutton
the following keywords have special meanings: _self: load the response into the same browsing context as the current one.
<cite>: The Citation element - HTML: Hypertext Markup Language
WebHTMLElementcite
usage notes in the context of the <cite> element, a creative work that might be cited could be, for example, one of the following: a book a research paper an essay a poem a musical score a song a play or film script a film a television show a game a sculpture a painting a theatrical production a play an opera a musical an exhibition a legal case report a computer program a web site a web page a blog post or comment a forum post or comment a tweet a facebook post a written or oral statement and ...
<col> - HTML: Hypertext Markup Language
WebHTMLElementcol
deprecated attributes the following attributes are deprecated and should not be used.
<colgroup> - HTML: Hypertext Markup Language
WebHTMLElementcolgroup
deprecated attributes the following attributes are deprecated and should not be used.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcontent
shadowroot.innerhtml = '<h2>inserted heading</h2> <content select="p"></content>'; </script> </body> </html> if you display this in a web browser it should look like the following.
<data> - HTML: Hypertext Markup Language
WebHTMLElementdata
examples the following example displays product names but also associates each name with a product number.
<details>: The Details disclosure element - HTML: Hypertext Markup Language
WebHTMLElementdetails
this might look like the following: here we see a standard disclosure widget with the label "system requirements", in its default closed state.
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
specifying the term being defined the term being defined is identified following these rules: if the <dfn> element has a title attribute, the value of the title attribute is considered to be the term being defined.
<head>: The Document Metadata (Header) element - HTML: Hypertext Markup Language
WebHTMLElementhead
the end tag may be omitted if the first thing following the <head> element is not a space character or a comment.
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
examples alternative text the following example embeds an image into the page and includes alternative text for accessibility.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
a simple button we'll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph): <form> <input type="button" value="start machine"> </form> <p>the machine is stopped.</p> const button = document.queryselector('input'); const paragraph = document.queryselector('p'); button.addeventlistener('click', updatebutton); function updatebutton() { if (button.value === 'start machine') { button.value = 'stop machine'; paragraph.textcontent = 'the machine has ...
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
this label is likely to be something along the lines of "submit" or "submit query." here's an example of a submit button with a default label in your browser: <input type="submit"> additional attributes in addition to the attributes shared by all <input> elements, submit button inputs support the following attributes: attribute description formaction the url to which to submit the form's data; overrides the form's action attribute, if any formenctype a string specifying the encoding type to use for the form data formmethod the http method (get or post) to use when submitting the form.
<isindex> - HTML: Hypertext Markup Language
WebHTMLElementisindex
example <head> <isindex prompt="search document..." action="/search"> </head> in past browsers, this would generate, at parse time, a dom tree equivalent to the following html: <form action="/search"> <hr> <label> search document...
<map> - HTML: Hypertext Markup Language
WebHTMLElementmap
examples <map name="primary"> <area shape="circle" coords="75,75,75" href="left.html"> <area shape="circle" coords="275,75,75" href="right.html"> </map> <img usemap="#primary" src="https://udn.realityripple.com/samples/6a/7e559101b3.png" alt="350 x 150 pic"> result expected live example output the live example above should appear similar to the following images (when using your keyboard tab key): for the left.html link: for the right.html link specifications specification status comment html living standardthe definition of '<map>' in that specification.
theme-color - HTML: Hypertext Markup Language
WebHTMLElementmetanametheme-color
example <meta name="theme-color" content="#4285f4"> the following image shows the effect that the <meta> element above will have on a document displayed in chrome running on an android mobile device.
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
WebHTMLElementmeta
implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlmetaelement the type of metadata provided by the meta element can be one of the following: if the name attribute is set, the meta element provides document-level metadata, applying to the whole page.
<output>: The Output element - HTML: Hypertext Markup Language
WebHTMLElementoutput
examples in the following example, the form provides a slider whose value can range between 0 and 100, and an <input> element into which you can enter a second number.
<plaintext>: The Plain Text element (Deprecated) - HTML: Hypertext Markup Language
the html plaintext element (<plaintext>) renders everything following the start tag as raw text, ignoring any following html.
<select>: The HTML Select element - HTML: Hypertext Markup Language
WebHTMLElementselect
for more useful information on styling <select>, see: styling html forms advanced styling for html forms examples basic select the following example creates a very simple dropdown menu, the second option of which is selected by default.
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
WebHTMLElementshadow
shadowroot2.innerhtml = '<shadow></shadow> <p>younger shadow root, displayed because it is the youngest.</p>'; </script> </body> </html> if you display this in a web browser it should look like the following.
<style>: The Style Information element - HTML: Hypertext Markup Language
WebHTMLElementstyle
examples a simple stylesheet in the following example, we apply a very simple stylesheet to a document: <!doctype html> <html> <head> <style> p { color: red; } </style> </head> <body> <p>this is my paragraph.</p> </body> </html> multiple style elements in this example we've included two <style> elements — notice how the conflicting declarations in the later <style> element override those in the earlier one, if they...
<sub>: The Subscript element - HTML: Hypertext Markup Language
WebHTMLElementsub
n use case for <sub>: <p>according to the computations by nakamura, johnson, and mason<sub>1</sub> this will result in the complete annihilation of both particles.</p> the resulting output looks like this: variable subscripts in mathematics, families of variables related to the same concept (such as distances along the same axis) are represented using the same variable name with a subscript following.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
consider the following html and javascript: html <div id="container"></div> <template id="template"> <div>click me</div> </template> javascript const container = document.getelementbyid("container"); const template = document.getelementbyid("template"); function clickhandler(event) { alert("clicked a div"); } const firstclone = template.content.clonenode(true); firstclone.addeventlistener("click", clickhandl...
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
for example, to give your textarea a different border depending on whether it is valid or invalid: textarea:invalid { border: 2px dashed red; } textarea:valid { border: 2px solid lime; } examples basic example the following example show a very simple textarea, with a set numbers of rows and columns and some default content.
<th> - HTML: Hypertext Markup Language
WebHTMLElementth
it may have the following values: row: the header relates to all cells of the row it belongs to.
<time> - HTML: Hypertext Markup Language
WebHTMLElementtime
it may represent one of the following: a time on a 24-hour clock.
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
deprecated attributes the following attributes may still be implemented in browsers but are no longer part of the html specification and may be missing or may not work as expected.
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
WebHTMLElementtrack
the following keywords are allowed: subtitles subtitles provide translation of content that cannot be understood by the viewer.
<var>: The Variable element - HTML: Hypertext Markup Language
WebHTMLElementvar
other elements that are used in contexts in which <var> is commonly used include: <code>: the html code element <kbd>: the html keyboard input element <samp>: the html sample output element if you encounter code that is mistakenly using <var> for style purposes rather than semantic purposes, you should either use a <span> with appropriate css or, an appropriate semantic element among the following: <em> <i> <q> default style most browsers apply font-style to "italic" when rendering <var>.
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
it may have one of the following values: none: indicates that the video should not be preloaded.
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
<plaintext> the html plaintext element (<plaintext>) renders everything following the start tag as raw text, ignoring any following html.
autocapitalize - HTML: Hypertext Markup Language
the attribute must take one of the following values: off or none: no autocapitalization is applied (all letters default to lowercase) on or sentences: the first letter of each sentence defaults to a capital letter; all other letters default to lowercase words: the first letter of each word defaults to a capital letter; all other letters default to lowercase characters: all letters should default to uppercase the autocapitalize attribute doesn’t affect behavior when typing on a physical keyboard.
contenteditable - HTML: Hypertext Markup Language
the attribute must take one of the following values: true or an empty string, which indicates that the element is editable.
data-* - HTML: Hypertext Markup Language
the * may be replaced by any name following the production rule of xml names with the following restrictions: the name must not start with xml, whatever case is used for these letters; the name must not contain any semicolon (u+003a); the name must not contain capital letters.
dir - HTML: Hypertext Markup Language
it can have the following values: ltr, which means left to right and is to be used for languages that are written from the left to the right (like english); rtl, which means right to left and is to be used for languages that are written from the right to the left (like arabic); auto, which lets the user agent decide.
draggable - HTML: Hypertext Markup Language
draggable can have the following values: true: the element can be dragged.
dropzone - HTML: Hypertext Markup Language
it can have the following values: copy, which indicates that dropping will create a copy of the element that was dragged.
inputmode - HTML: Hypertext Markup Language
it can have the following values: none no virtual keyboard.
is - HTML: Hypertext Markup Language
examples the following code is taken from our word-count-web-component example (see it live also).
itemid - HTML: Hypertext Markup Language
however, the following example correctly illustrates that a urn may also be used.
spellcheck - HTML: Hypertext Markup Language
it may have the following values: true, which indicates that the element should be, if possible, checked for spelling errors; false, which indicates that the element should not be checked for spelling errors.
title - HTML: Hypertext Markup Language
some caution must be taken, as this means the following renders across two lines: html <p>newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on.
translate - HTML: Hypertext Markup Language
it can have the following values: empty string or "yes", which indicates that the element should be translated when the page is localized.
Link types - HTML: Hypertext Markup Language
<link> <a>, <area>, <form> external indicates that the hyperlink leads to a resource outside the site of the current page; that is, following the link will make the user leave the site.
HTML reference - HTML: Hypertext Markup Language
link types in html, the following link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, or <link> element.
HTTP authentication - HTTP
the syntax for these headers is the following: www-authenticate: <type> realm=<realm> proxy-authenticate: <type> realm=<realm> here, <type> is the authentication scheme ("basic" is the most common scheme and introduced below).
Common MIME types - HTTP
ics interchange format (gif) image/gif .htm .html hypertext markup language (html) text/html .ico icon format image/vnd.microsoft.icon .ics icalendar format text/calendar .jar java archive (jar) application/java-archive .jpeg .jpg jpeg images image/jpeg .js javascript text/javascript, per the following specifications: https://html.spec.whatwg.org/multipage/#scriptinglanguages https://html.spec.whatwg.org/multipage/#dependencies:willful-violation https://datatracker.ietf.org/doc/draft-ietf-dispatch-javascript-mjs/ .json json format application/json .jsonld json-ld format application/ld+json .mid .midi musical instrument ...
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
for example, in apache, add a line such as the following to the server's configuration (within the appropriate <directory>, <location>, <files>, or <virtualhost> section).
Reason: CORS header 'Access-Control-Allow-Origin' missing - HTTP
in apache, add a line such as the following to the server's configuration (within the appropriate <directory>, <location>, <files>, or <virtualhost> section).
CORS errors - HTTP
WebHTTPCORSErrors
it will probably look like this: the text of the error message will be something similar to the following: cross-origin request blocked: the same origin policy disallows reading the remote resource at https://some-url-here.
Compression in HTTP - HTTP
do not use the two following techniques for files in a compressed format.
Configuring servers for Ogg media - HTTP
for apache, you can add the following to your configuration: addtype audio/ogg .oga addtype video/ogg .ogv addtype application/ogg .ogg you can find specific information about possible media file types and the codecs used within them in our comprehensive guide to media types and formats on the web.
Using HTTP cookies - HTTP
WebHTTPCookies
with strict, the cookie is sent only to the same site as the one that originated it; lax is similar, with an exception for when the user navigates to a url from an external site, such as by following a link; none has no restrictions on cross-site requests.
Access-Control-Allow-Origin - HTTP
the "null" value for the acao header should therefore be avoided." examples a response that tells the browser to allow code from any origin to access a resource will include the following: access-control-allow-origin: * a response that tells the browser to allow requesting code from the origin https://developer.mozilla.org to access a resource will include the following: access-control-allow-origin: https://developer.mozilla.org limiting the possible access-control-allow-origin values to a set of allowed origins requires code on the server side to check the value of the origin...
CSP: child-src - HTTP
syntax one or more sources can be allowed for the child-src policy: content-security-policy: child-src <source>; content-security-policy: child-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
CSP: frame-ancestors - HTTP
syntax one or more sources can be set for the frame-ancestors policy: content-security-policy: frame-ancestors <source>; content-security-policy: frame-ancestors <source> <source>; sources <source> can be one of the following: the frame-ancestors directive’s syntax is similar to a source list of other directives (e.g.
CSP: navigate-to - HTTP
syntax one or more sources can be set for the navigate-to policy: content-security-policy: navigate-to <source>; content-security-policy: navigate-to <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
CSP: referrer - HTTP
syntax content-security-policy: referrer <referrer-policy>; where <referrer-policy> can be one of the following values: "no-referrer" the referer header will be omitted entirely.
CSP: require-sri-for - HTTP
examples if you set your site to require sri for script and styles using this directive: content-security-policy: require-sri-for script style <script> elements like the following will be loaded as they use a valid integrity attribute.
CSP: sandbox - HTTP
syntax content-security-policy: sandbox; content-security-policy: sandbox <value>; where <value> can optionally be one of the following values: allow-downloads-without-user-activation allows for downloads to occur without a gesture from the user.
CSP: script-src-attr - HTTP
syntax one or more sources can be allowed for the script-src-attr policy: content-security-policy: script-src-attr <source>; content-security-policy: script-src-attr <source> <source>; script-src-attr can be used in conjunction with script-src: content-security-policy: script-src <source>; content-security-policy: script-src-attr <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
CSP: script-src-elem - HTTP
syntax one or more sources can be allowed for the script-src-elem policy: content-security-policy: script-src-elem <source>; content-security-policy: script-src-elem <source> <source>; script-src-elem can be used in conjunction with script-src: content-security-policy: script-src <source>; content-security-policy: script-src-elem <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
CSP: style-src-attr - HTTP
syntax one or more sources can be allowed for the style-src-attr policy: content-security-policy: style-src-attr <source>; content-security-policy: style-src-attr <source> <source>; style-src-attr can be used in conjunction with style-src: content-security-policy: style-src <source>; content-security-policy: style-src-attr <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
CSP: style-src-elem - HTTP
syntax one or more sources can be allowed for the style-src-elem policy: content-security-policy: style-src-elem <source>; content-security-policy: style-src-elem <source> <source>; style-src-elem can be used in conjunction with style-src: content-security-policy: style-src <source>; content-security-policy: style-src-elem <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
CSP: worker-src - HTTP
syntax one or more sources can be allowed for the worker-src policy: content-security-policy: worker-src <source>; content-security-policy: worker-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number.
Device-Memory - HTTP
the header takes on the following values: 0.25, 0.5, 1, 2, 4, 8.
Feature-Policy: accelerometer - HTTP
syntax feature-policy: accelerometer <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: ambient-light-sensor - HTTP
syntax feature-policy: ambient-light-sensor <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: autoplay - HTTP
syntax feature-policy: autoplay <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: battery - HTTP
syntax feature-policy: battery <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: camera - HTTP
syntax feature-policy: camera <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: display-capture - HTTP
syntax feature-policy: display-capture <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: document-domain - HTTP
syntax feature-policy: document-domain <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: encrypted-media - HTTP
syntax feature-policy: encrypted-media <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: gyroscope - HTTP
syntax feature-policy: gyroscope <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: layout-animations - HTTP
syntax feature-policy: layout-animations <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: legacy-image-formats - HTTP
syntax feature-policy: legacy-image-formats <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: magnetometer - HTTP
syntax feature-policy: magnetometer <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: microphone - HTTP
syntax feature-policy: microphone <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: midi - HTTP
syntax feature-policy: midi <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: oversized-images - HTTP
syntax feature-policy: oversized-images <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: payment - HTTP
syntax feature-policy: payment <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: picture-in-picture - HTTP
syntax feature-policy: picture-in-picture <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: publickey-credentials-get - HTTP
syntax feature-policy: publickey-credentials-get <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: screen-wake-lock - HTTP
syntax feature-policy: screen-wake-lock <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: sync-xhr - HTTP
syntax feature-policy: sync-xhr <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: unoptimized-images - HTTP
syntax feature-policy: unoptimized-images <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: unsized-media - HTTP
syntax feature-policy: unsized-media <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: usb - HTTP
syntax feature-policy: usb <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: vibrate - HTTP
syntax feature-policy: vibrate <allowlist>; <vibrate> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: wake-lock - HTTP
syntax feature-policy: wake-lock <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
web-share - HTTP
syntax feature-policy: web-share <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
Feature-Policy: xr-spatial-tracking - HTTP
syntax feature-policy: xr-spatial-tracking <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
If-None-Match - HTTP
note that the server generating a 304 response must generate any of the following header fields that would have been sent in a 200 (ok) response to the same request: cache-control, content-location, date, etag, expires, and vary.
Index - HTTP
WebHTTPHeadersIndex
for each of the following directives that are absent, the user agent will look for the default-src directive and will use this value for it: 34 csp: font-src csp, directive, http, reference, security the http content-security-policy (csp) font-src directive specifies valid sources for fonts loaded using @font-face.
Keep-Alive - HTTP
the following identifiers are possible: timeout: indicating the minimum amount of time an idle connection has to be kept opened (in seconds).
HTTP Index - HTTP
WebHTTPIndex
for each of the following directives that are absent, the user agent will look for the default-src directive and will use this value for it: 82 csp: font-src csp, content-security-policy, directive, http, reference, security, font, source the http content-security-policy (csp) font-src directive specifies valid sources for fonts loaded using @font-face.
HTTP Messages - HTTP
WebHTTPMessages
http responses status line the start line of an http response, called the status line, contains the following information: the protocol version, usually http/1.1.
OPTIONS - HTTP
WebHTTPMethodsOPTIONS
in this example, the server response says that: access-control-allow-origin the https://foo.example origin is permitted to request the bar.example/resources/post-here/ url via the following: access-control-allow-methods post, get, and options are permitted methods for the url.
POST - HTTP
WebHTTPMethodsPOST
as described in the http 1.1 specification, post is designed to allow a uniform method to cover the following functions: annotation of existing resources posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; adding a new user through a signup modal; providing a block of data, such as the result of submitting a form, to a data-handling process; extending a database through an append operation.
Protocol upgrade mechanism - HTTP
after creating the initial http/1.1 session, you need to request the upgrade by adding to a standard request the upgrade and connection headers, as follows: connection: upgrade upgrade: websocket websocket-specific headers the following headers are involved in the websocket upgrade process.
Proxy servers and tunneling - HTTP
a common way to disclose this information is by using the following http headers: the standardized header: forwarded contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request.
404 Not Found - HTTP
WebHTTPStatus404
apache servers can be configured using an .htaccess file and a code snippet like the following example.
Concurrency model and the event loop - JavaScript
runtime concepts the following sections explain a theoretical model.
Assertions - JavaScript
types the following section is also duplicated on this cheatsheet.
Groups and ranges - JavaScript
types the following section is also duplicated on this cheatsheet.
Unicode property escapes - JavaScript
syntax the following section is also duplicated on this cheatsheet.
JavaScript language resources - JavaScript
the following ecmascript standards have been approved or are being worked on: name links release date description current editions ecma-262 10th edition pdf, html, working draft, repository 2019 ecmascript 2019 language specification ecma-262 9th edition pdf, html, working draft, repository 2018 ecmascript 2018 language specification ecma-402 5th edition working draft, repository 2018 ecmascript 2018 internationalization api specification obsolete/historical editions ecma-262 pdf ju...
Memory Management - JavaScript
in the following example, two objects are created with properties that reference one another, thus creating a cycle.
Private class fields - JavaScript
in the following example this refers to the derived class (not the base class) when we try to call derived.publicstaticmethod2(), and thus exhibits the same "provenance restriction" as mentioned above: class base { static #privatestaticmethod() { return 42; } static publicstaticmethod1() { return base.#privatestaticmethod(); } static publicstaticmethod2() { return this...
static - JavaScript
} examples using static in classes the following example demonstrates several things: how a static method is implemented on a class.
Classes - JavaScript
you first need to declare your class and then access it, otherwise code like the following will throw a referenceerror: const p = new rectangle(); // referenceerror class rectangle {} class expressions a class expression is another way to define a class.
The legacy Iterator protocol - JavaScript
an object is an legacy iterator when it implements a next() method with the following semantics, and throws stopiteration at the end of iteration.
TypeError: can't assign to property "x" on "y": not an object - JavaScript
examples invalid cases 'use strict'; var foo = "my string"; // the following line does nothing if not in strict mode.
TypeError: cyclic object value - JavaScript
examples circular references in a circular structure like the following var circularreference = {otherdata: 123}; circularreference.myself = circularreference; json.stringify() will fail json.stringify(circularreference); // typeerror: cyclic object value to serialize circular references you can use a library that supports them (e.g.
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
examples deprecated syntax var num = 15; string.replace(num, /5/, '2'); standard syntax var num = 15; string(num).replace(/5/, '2'); shim the following is a shim to provide support to non-supporting browsers: /*globals define*/ // assumes all supplied string instance methods already present // (one may use shims for these if not available) (function() { 'use strict'; var i, // we could also build the array of methods with the following, but the // getownpropertynames() method is non-shimable: // object.getownpropertynames(str...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
for example, do not use the following code: if (x = y) { // do the right thing } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment.
SyntaxError: identifier starts immediately after numeric literal - JavaScript
the following fails: var 1life = 'foo'; // syntaxerror: identifier starts immediately after numeric literal var foo = 1life; // syntaxerror: identifier starts immediately after numeric literal alert(1.foo); // syntaxerror: identifier starts immediately after numeric literal you will need to rename your variable to avoid the leading number.
RangeError: invalid date - JavaScript
however, depending on the implementation, non–conforming iso format strings, may also throw rangeerror: invalid date, like the following cases in firefox: new date('foo-bar 2014'); new date('2014-25-23').toisostring(); new date('foo-bar 2014').tostring(); this, however, returns nan in firefox: date.parse('foo-bar 2014'); // nan for more details, see the date.parse() documentation.
SyntaxError: "x" is a reserved identifier - JavaScript
these are reserved in strict mode and sloppy mode: enum the following are only reserved when they are found in strict mode code: implements interface let package private protected public static examples strict and non-strict reserved keywords the enum identifier is generally reserved.
Warning: unreachable code after return statement - JavaScript
in the case of semicolon-less return statements, it can be unclear whether the developer intended to return the statement on the following line, or to stop execution and return.
SyntaxError: function statement requires a name - JavaScript
the following syntax without a name after the function keyword is valid then.
Arrow function expressions - JavaScript
thus, in the following code, the this within the function that is passed to setinterval has the same value as the this in the lexically enclosing function: function person(){ this.age = 0; setinterval(() => { this.age++; // |this| properly refers to the person object }, 1000); } var p = new person(); relation with strict mode given that this comes from the surrounding lexical context, strict mode rules w...
Method definitions - JavaScript
given the following code: const obj = { foo: function() { // ...
Array.prototype[@@unscopables] - JavaScript
property attributes of array.prototype[@@unscopables] writable no enumerable no configurable yes examples use in with environments the following code works fine in es5 and below.
Array.prototype.reduceRight() - JavaScript
you can work around this by inserting the following code at the beginning of your scripts, allowing use of reduceright in implementations which do not natively support it.
Array.from() - JavaScript
you can work around this by inserting the following code at the beginning of your scripts, allowing use of array.from() in implementations that don't natively support it.
Array.of() - JavaScript
for more information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available.
Array.prototype.push() - JavaScript
examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it.
Array.prototype.slice() - JavaScript
examples return a portion of an existing array let fruits = ['banana', 'orange', 'lemon', 'apple', 'mango'] let citrus = fruits.slice(1, 3) // fruits contains ['banana', 'orange', 'lemon', 'apple', 'mango'] // citrus contains ['orange','lemon'] using slice> in the following example, slice creates a new array, newcar, from mycar.
Array.prototype.toSource() - JavaScript
description the tosource method returns the following values: for the built-in array object, tosource returns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource returns a string representing the source code.
AsyncFunction - JavaScript
it can be obtained with the following code: object.getprototypeof(async function(){}).constructor syntax new asyncfunction([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ...
BigInt - JavaScript
type information when tested against typeof, a bigint will give "bigint": typeof 1n === 'bigint' // true typeof bigint('1') === 'bigint' // true when wrapped in an object, a bigint will be considered as a normal "object" type: typeof object(1n) === 'object' // true operators the following operators may be used with bigints (or object-wrapped bigints): +, *, -, **, %.
Boolean.prototype.toSource() - JavaScript
examples native function for the built-in boolean object, tosource returns the following string indicating that the source code is not available: function boolean() { [native code] } specifications not part of any standard.
Boolean.prototype.toString() - JavaScript
examples using tostring() in the following code, flag.tostring() returns "true": var flag = new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification.
Date.UTC() - JavaScript
examples using date.utc() the following statement creates a date object with the arguments treated as utc instead of local: let utcdate = new date(date.utc(2018, 11, 1, 0, 0, 0)); specifications specification ecmascript (ecma-262)the definition of 'date.utc' in that specification.
Date.prototype.getFullYear() - JavaScript
examples using getfullyear() the following example assigns the four-digit value of the current year to the variable year.
Date.prototype.getMilliseconds() - JavaScript
examples using getmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds: var today = new date(); var milliseconds = today.getmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmilliseconds' in that specification.
Date.prototype.getUTCDate() - JavaScript
examples using getutcdate() the following example assigns the day portion of the current date to the variable day.
Date.prototype.getUTCDay() - JavaScript
examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday.
Date.prototype.getUTCFullYear() - JavaScript
examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year.
Date.prototype.getUTCHours() - JavaScript
examples using getutchours() the following example assigns the hours portion of the current time to the variable hours.
Date.prototype.getUTCMilliseconds() - JavaScript
examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds.
Date.prototype.getUTCMinutes() - JavaScript
examples using getutcminutes() the following example assigns the minutes portion of the current time to the variable minutes.
Date.prototype.getUTCMonth() - JavaScript
examples using getutcmonth() the following example assigns the month portion of the current date to the variable month.
Date.prototype.getUTCSeconds() - JavaScript
examples using getutcseconds() the following example assigns the seconds portion of the current time to the variable seconds.
Date.now() - JavaScript
engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.now) { date.now = function now() { return new date().gettime(); }; } examples reduced time precision to offer protection against timing attacks and fingerprinting, the precision of date.now() might get rounded depending on browser settings.
Date.prototype.setMonth() - JavaScript
so, 0 represents january, 11 represents december, -1 represents december of the previous year, and 12 represents january of the following year.
Date.prototype.toDateString() - JavaScript
the todatestring() method returns the date portion of a date object in english in the following format separated by spaces: first three letters of the week day name first three letters of the month name two digit day of the month, padded on the left a zero if necessary four digit year (at least), padded on the left with zeros if necessary e.g.
Date.prototype.toISOString() - JavaScript
engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.prototype.toisostring) { (function() { function pad(number) { if (number < 10) { return '0' + number; } return number; } date.prototype.toisostring = function() { return this.getutcfullyear() + '-' + pad(this.getutcmonth() + 1) + '-' + pad(this.getutcdate()) + 't' + pad(this.getutchours()) + ':' + pad...
Date.prototype.toSource() - JavaScript
examples native function for the built-in date object, tosource() returns the following string indicating that the source code is not available: function date() { [native code] } specifications not part of any standard.
Date.prototype.toString() - JavaScript
examples using tostring() the following assigns the tostring() value of a date object to myvar: var x = new date(); var myvar = x.tostring(); // assigns a string value to myvar in the same format as: // mon sep 08 1998 14:36:22 gmt-0700 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tostring' in that specification.
Error - JavaScript
otherwise, old versions of babel and other transpilers will not correctly handle the following code without additional configuration.
FinalizationRegistry.prototype.register() - JavaScript
examples using register the following registers the target object referenced by target, passing in the held value "some value" and passing the target object itself as the unregistration token: registry.register(target, "some value", target); the following registers the target object referenced by target, passing in another object as the held value, and not passing in any unregistration token (which means target can't be unregister...
Function() constructor - JavaScript
examples specifying arguments with the function constructor the following code creates a function object that takes two arguments.
Function.prototype.call() - JavaScript
in the following example, the constructor for the product object is defined with two parameters: name and price.
Function.displayName - JavaScript
by entering the following in a console, it should display as something like "function my function()": var a = function() {}; a.displayname = 'my function'; a; // "function my function()" when defined, the displayname property returns the display name of a function: function dosomething() {} console.log(dosomething.displayname); // "undefined" var popup = function(content) { console.log(content); }; popup.displayname = 'show popup'; console.log(popup.displayname); // "show popup" defining a displayname in function expressions you can define a function with a display name...
Function.name - JavaScript
above class definition in es2015 syntax will behave in chrome or firefox similar to the following snippet in es5 syntax: function foo() {} object.defineproperty(foo, 'name', { writable: true }); foo.name = function() {}; trying to obtain the class of fooinstance via fooinstance.constructor.name won't give us the class name at all but a reference to the static class method.
Function.prototype.toSource() - JavaScript
examples native functions for the built-in function object, tosource() returns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() returns the javascript source that defines the object as a string.
Generator.prototype.next() - JavaScript
examples using next() the following example shows a simple generator and the object that the next method returns: function* gen() { yield 1; yield 2; yield 3; } const g = gen(); // "generator { }" g.next(); // "object { value: 1, done: false }" g.next(); // "object { value: 2, done: false }" g.next(); // "object { value: 3, done: false }" g.next(); // "object { value: undefined, done: true }" using nex...
Generator.prototype.return() - JavaScript
examples using return() the following example shows a simple generator and the return method.
Generator.prototype.throw() - JavaScript
examples using throw() the following example shows a simple generator and an error that is thrown using the throw method.
GeneratorFunction - JavaScript
it could be obtained by evaluating the following code.
Intl.Collator.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used.
Intl.Collator.supportedLocalesOf() - JavaScript
an object that may have the following property: localematcher the locale matching algorithm to use.
Intl.Collator - JavaScript
examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary betw...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
the structure the formattoparts() method returns, looks like this: [ { type: 'day', value: '17' }, { type: 'weekday', value: 'monday' } ] possible types are the following: day the string used for the day, for example "17".
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used.
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
an object that may have the following property: localematcher the locale matching algorithm to use.
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used.
Intl.DisplayNames.supportedLocalesOf() - JavaScript
an object that may have the following property: localematcher the locale matching algorithm to use.
Intl​.ListFormat.prototype​.format() - JavaScript
examples using format the following example shows how to create a list formatter using the english language.
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used.
Intl.ListFormat.supportedLocalesOf() - JavaScript
an object that may have the following property: localematcher the locale matching algorithm to use.
Intl.Locale.prototype.calendar - JavaScript
the following table shows all the valid unicode calendar key strings, along with a description of the calendar era they represent.
Intl.NumberFormat.prototype.formatToParts() - JavaScript
the structure the formattoparts() method returns, looks like this: [ { type: "integer", value: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" } ] possible types are the following: currency the currency string, such as the symbols "$" and "€" or the name "dollar", "euro" depending on how currencydisplay is specified.
Intl.NumberFormat.supportedLocalesOf() - JavaScript
an object that may have the following property: localematcher the locale matching algorithm to use.
Intl.PluralRules.supportedLocalesOf() - JavaScript
an object that may have the following property: localematcher the locale matching algorithm to use.
Intl.RelativeTimeFormat.prototype.format() - JavaScript
examples basic format usage the following example shows how to create a relative time formatter using the english language.
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used.
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
an object that may have the following property: localematcher the locale matching algorithm to use.
Map - JavaScript
even though every nan is not equal to itself (nan !== nan is true), the following example works because nans are indistinguishable from each other: let mymap = new map() mymap.set(nan, 'not a number') mymap.get(nan) // "not a number" let othernan = number('foo') mymap.get(othernan) // "not a number" iterating map with for..of maps can be iterated using a for..of loop: let mymap = new map() mymap.set(0, 'zero') mymap.set(1, 'one') for (let [key, value] of mymap) { con...
Math.E - JavaScript
examples using math.e the following function returns e: function getnapier() { return math.e; } getnapier(); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.e' in that specification.
Math.LN10 - JavaScript
examples using math.ln10 the following function returns the natural log of 10: function getnatlog10() { return math.ln10; } getnatlog10(); // 2.302585092994046 specifications specification ecmascript (ecma-262)the definition of 'math.ln10' in that specification.
Math.LN2 - JavaScript
examples using math.ln2 the following function returns the natural log of 2: function getnatlog2() { return math.ln2; } getnatlog2(); // 0.6931471805599453 specifications specification ecmascript (ecma-262)the definition of 'math.ln2' in that specification.
Math.LOG10E - JavaScript
examples using math.log10e the following function returns the base 10 logarithm of e: function getlog10e() { return math.log10e; } getlog10e(); // 0.4342944819032518 specifications specification ecmascript (ecma-262)the definition of 'math.log10e' in that specification.
Math.LOG2E - JavaScript
examples using math.log2e the following function returns the base 2 logarithm of e: function getlog2e() { return math.log2e; } getlog2e(); // 1.4426950408889634 specifications specification ecmascript (ecma-262)the definition of 'math.log2e' in that specification.
Math.PI - JavaScript
examples using math.pi the following function uses math.pi to calculate the circumference of a circle with a passed radius.
Math.SQRT1_2 - JavaScript
examples using math.sqrt1_2 the following function returns 1 over the square root of 2: function getroot1_2() { return math.sqrt1_2; } getroot1_2(); // 0.7071067811865476 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt1_2' in that specification.
Math.SQRT2 - JavaScript
examples using math.sqrt2 the following function returns the square root of 2: function getroot2() { return math.sqrt2; } getroot2(); // 1.4142135623730951 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt2' in that specification.
Math.acosh() - JavaScript
polyfill for all x≥1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so this can be emulated with the following function: math.acosh = math.acosh || function(x) { return math.log(x + math.sqrt(x * x - 1)); }; examples using math.acosh() math.acosh(-1); // nan math.acosh(0); // nan math.acosh(0.5); // nan math.acosh(1); // 0 math.acosh(2); // 1.3169578969248166 for values less than 1 math.acosh() returns nan.
Math.asinh() - JavaScript
polyfill math.asinh can be emulated with the following function: if (!math.asinh) math.asinh = function(x) { var absx = math.abs(x), w if (absx < 3.725290298461914e-9) // |x| < 2^-28 return x if (absx > 268435456) // |x| > 2^28 w = math.log(absx) + math.ln2 else if (absx > 2) // 2^28 >= |x| > 2 w = math.log(2 * absx + 1 / (math.sqrt(x * x + 1) + absx)) else var t = x * x, w = math.log1p(absx + t /...
Math.atanh() - JavaScript
polyfill for |x|<1\left|x\right| < 1, we have artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) so this can be emulated by the following function: math.atanh = math.atanh || function(x) { return math.log((1+x)/(1-x)) / 2; }; examples using math.atanh() math.atanh(-2); // nan math.atanh(-1); // -infinity math.atanh(0); // 0 math.atanh(0.5); // 0.5493061443340548 math.atanh(1); // infinity math.atanh(2); // nan for values greater than 1 or less than -1, nan is returned.
Math.cbrt() - JavaScript
polyfill for all x≥0x \geq 0, have x3=x1/3\sqrt[3]{x} = x^{1/3} so this can be emulated by the following function: if (!math.cbrt) { math.cbrt = (function(pow) { return function cbrt(x){ // ensure negative numbers remain negative: return x < 0 ?
Math.ceil() - JavaScript
examples using math.ceil() the following example shows example usage of math.ceil().
Math.imul() - JavaScript
polyfill this can be emulated with the following function: if (!math.imul) math.imul = function(a, b) { var ahi = (a >>> 16) & 0xffff; var alo = a & 0xffff; var bhi = (b >>> 16) & 0xffff; var blo = b & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((alo * blo) + (((ahi * blo + alo * bhi) << 16) >>> 0) | 0); }; however, the following function is mo...
Math.log() - JavaScript
examples using math.log() math.log(-1); // nan, out of range math.log(0); // -infinity math.log(1); // 0 math.log(10); // 2.302585092994046 using math.log() with a different base the following function returns the logarithm of y with base x (ie.
Math.log10() - JavaScript
examples using math.log10() math.log10(2); // 0.3010299956639812 math.log10(1); // 0 math.log10(0); // -infinity math.log10(-2); // nan math.log10(100000); // 5 polyfill this can be emulated with the following function: math.log10 = math.log10 || function(x) { return math.log(x) * math.log10e; }; specifications specification ecmascript (ecma-262)the definition of 'math.log10' in that specification.
Math.log1p() - JavaScript
polyfill this can be emulated with the following function: math.log1p = math.log1p || function(x) { x = number(x); if (x < -1 || x !== x) return nan; if (x === 0 || x === infinity) return x; var nearx = (x + 1) - 1; return nearx === 0 ?
Math.max() - JavaScript
examples using math.max() math.max(10, 20); // 20 math.max(-10, -20); // -10 math.max(-10, 20); // 20 getting the maximum element of an array array.reduce() can be used to find the maximum element in a numeric array, by comparing each value: var arr = [1,2,3]; var max = arr.reduce(function(a, b) { return math.max(a, b); }); the following function uses function.prototype.apply() to get the maximum of an array.
Math.tan() - JavaScript
examples using math.tan() math.tan(1); // 1.5574077246549023 because the math.tan() function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent.
Math - JavaScript
in javascript, we can do this with the following: 50 * math.tan(degtorad(60)).
Number.MAX_VALUE - JavaScript
examples using max_value the following code multiplies two numeric values.
Number.MIN_VALUE - JavaScript
examples using min_value the following code divides two numeric values.
Number.NEGATIVE_INFINITY - JavaScript
examples using negative_infinity in the following example, the variable smallnumber is assigned a value that is smaller than the minimum value.
Number.POSITIVE_INFINITY - JavaScript
examples using positive_infinity in the following example, the variable bignumber is assigned a value that is larger than the maximum value.
Number.isNaN() - JavaScript
polyfill the following works because nan is the only value in javascript which is not equal to itself.
Number.prototype.toSource() - JavaScript
examples native function for the built-in number object, tosource() returns the following string indicating that the source code is not available: function number() { [native code] } for instances of number, tosource() returns a string representing the source code.
Object() constructor - JavaScript
examples creating a new object let o = new object() o.foo = 42 console.log(o) // object { foo: 42 } using object given undefined and null types the following examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) specifications specification ecmascript (ecma-262)the definition of 'object constructor' in that specification.
Object.entries() - JavaScript
polyfill to add compatible object.entries() support in older environments that do not natively support it, you can use any of the following: a demonstration implementation of object.entries in the tc39/proposal-object-values-entries (if you don't need any support for ie); a polyfill in the es-shims/object.entries repositories; or, you can use the simple, ready-to-deploy polyfill listed below: if (!object.entries) { object.entries = function( obj ){ var ownprops = object.keys( obj ), i = ownprops.length, r...
Object.freeze() - JavaScript
the following example shows that a frozen object is not constant (freeze is shallow).
Object.getOwnPropertyDescriptor() - JavaScript
a property descriptor is a record with some of the following attributes: value the value associated with the property (data descriptors only).
Object.getOwnPropertyDescriptors() - JavaScript
a property descriptor is a record with some of the following attributes: value the value associated with the property (data descriptors only).
Object.is() - JavaScript
two values are the same if one of the following holds: both undefined both null both true or both false both strings of the same length with the same characters in the same order both the same object (means both object have same reference) both numbers and both +0 both -0 both nan or both non-zero and both not nan and both have the same value this is not the same as being equal according to the == operator.
Object.keys() - JavaScript
polyfill to add compatible object.keys support in older environments that do not natively support it, copy the following snippet: // from /docs/web/javascript/reference/global_objects/object/keys if (!object.keys) { object.keys = (function() { 'use strict'; var hasownproperty = object.prototype.hasownproperty, hasdontenumbug = !({ tostring: null }).propertyisenumerable('tostring'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproper...
Object.prototype.valueOf() - JavaScript
the following code assigns a user-defined function to the object's valueof method: mynumbertype.prototype.valueof = function() { return customprimitivevalue; }; with the preceding code in place, any time an object of type mynumbertype is used in a context where it is to be represented as a primitive value, javascript automatically calls the function defined in the preceding code.
Object - JavaScript
examples using object given undefined and null types the following examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) using object to create boolean objects the following examples store boolean objects in o: // equivalent to o = new boolean(true) let o = new object(true) // equivalent to o = new boolean(false) let o = new object(boolean()) object prototypes when altering the behav...
Promise.all() - JavaScript
omise.reject(555)]); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log(p); console.log(p2); console.log(p3); }); // logs // promise { <state>: "fulfilled", <value>: array[3] } // promise { <state>: "fulfilled", <value>: array[4] } // promise { <state>: "rejected", <reason>: 555 } asynchronicity or synchronicity of promise.all this following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of promise.all: // we are passing as argument an array of promises that are already resolved, // to trigger promise.all as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.all(resolvedpromisesarray); // immediately logging the value of p console.log...
Promise.prototype.catch() - JavaScript
g the catch method var p1 = new promise(function(resolve, reject) { resolve('success'); }); p1.then(function(value) { console.log(value); // "success!" throw new error('oh, no!'); }).catch(function(e) { console.error(e.message); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); // the following behaves the same as above p1.then(function(value) { console.log(value); // "success!" return promise.reject('oh, no!'); }).catch(function(e) { console.error(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); gotchas when throwing errors // throwing an error will call the catch method...
Promise.race() - JavaScript
examples asynchronicity of promise.race this following example demonstrates the asynchronicity of promise.race: // we are passing as argument an array of promises that are already resolved, // to trigger promise.race as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.race(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code aft...
Proxy.revocable() - JavaScript
description a revocable proxy is an object with following two properties {proxy: proxy, revoke: revoke}.
Reflect - JavaScript
the reflect object provides the following static functions which have the same names as the proxy handler methods.
RegExp.prototype[@@match]() - JavaScript
for example, the following two examples return same result.
RegExp.prototype[@@matchAll]() - JavaScript
for example, the following two examples return same result.
RegExp.prototype[@@replace]() - JavaScript
for example, following two examples return same result.
RegExp.prototype[@@search]() - JavaScript
for example, the following two examples return the same result.
RegExp.prototype[@@split]() - JavaScript
for example, the following two examples return the same result.
RegExp.prototype.dotAll - JavaScript
the "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: u+000a line feed (lf) ("\n") u+000d carriage return (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will match any character on the unicode basic multilingual plane (bmp).
RegExp.rightContext ($') - JavaScript
the non-standard rightcontext property is a static and read-only property of regular expressions that contains the substring following the most recent match.
RegExp.prototype.toSource() - JavaScript
examples native function for the built-in regexp object, tosource() returns the following string indicating that the source code is not available: function regexp() { [native code] } for instances of regexp, tosource() returns a string representing the source code.
RegExp.prototype.toString() - JavaScript
examples using tostring() the following example displays the string value of a regexp object: var myexp = new regexp('a+b+c'); console.log(myexp.tostring()); // logs '/a+b+c/' var foo = new regexp('bar', 'g'); console.log(foo.tostring()); // logs '/bar/g' empty regular expressions and escaping starting with ecmascript 5, an empty regular expression returns the string "/(?:)/" and line terminators such as "\n" are escaped: new...
Set.prototype.forEach() - JavaScript
examples logging the contents of a set object the following code logs a line for each element in a set object: function logsetelements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); } new set(['foo', 'bar', undefined]).foreach(logsetelements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.foreach...
Set - JavaScript
"a": 1, "b": 2} for (let item of myset.values()) console.log(item) // logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of myset.entries()) console.log(key) // convert set object to an array object, with array.from let myarr = array.from(myset) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an html document myset.add(document.body) myset.has(document.queryselector('body')) // true // converting between set and array myset2 = new set([1, 2, 3, 4]) myset2.size // 4 [...myset2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new set([...set1].filter(x => set2.has(x))) // difference can be simulated v...
String.prototype.anchor() - JavaScript
examples using anchor() var mystring = 'table of contents'; document.body.innerhtml = mystring.anchor('contents_anchor'); will output the following html: <a name="contents_anchor">table of contents</a> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.anchor' in that specification.
String.prototype.big() - JavaScript
examples using big() the following example uses string methods to change the size of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <fontsize=7>hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it ...
String.prototype.blink() - JavaScript
examples using blink() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ...
String.prototype.bold() - JavaScript
examples using bold() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.bold' in that specification.
String.prototype.charCodeAt() - JavaScript
examples using charcodeat() the following example returns 65, the unicode value for a.
String.prototype.codePointAt() - JavaScript
polyfill the following extends strings to include the codepointat() function as specified in ecmascript 2015 for browsers without native support.
String.prototype.concat() - JavaScript
examples using concat() the following example combines strings into a new string.
String.prototype.endsWith() - JavaScript
however, you can polyfill string.prototype.endswith() with the following snippet: if (!string.prototype.endswith) { string.prototype.endswith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } return this.substring(this_len - search.length, this_len) === search; }; } examples using endswith() let str = 'to be, or not to be, that is the question.' console.log(str.endswith('question.')) // ...
String.prototype.fixed() - JavaScript
examples using fixed() the following example uses the fixed method to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.fixed()); // "<tt>hello, world</tt>" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fixed' in that specification.
String.prototype.fontcolor() - JavaScript
examples using fontcolor() the following example uses the fontcolor() method to change the color of a string by producing a string with the html <font> tag.
String.prototype.fontsize() - JavaScript
examples using fontsize() the following example uses string methods to change the size of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate ...
String.prototype.includes() - JavaScript
for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet.
String.prototype.italics() - JavaScript
examples using italics() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.italics' in that specification.
String.prototype.lastIndexOf() - JavaScript
for example, the following expression returns -1: 'blue whale, killer whale'.lastindexof('blue'); // returns -1 examples using indexof() and lastindexof() the following example uses indexof() and lastindexof() to locate values in the string "brave new world".
String.prototype.link() - JavaScript
examples using link() the following example displays the word "mdn" as a hypertext link that returns the user to the mozilla developer network.
String.prototype.normalize() - JavaScript
these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition.
String.raw() - JavaScript
// the following is equivalent to // `t${0}e${1}s${2}t`: string.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t' specifications specification ecmascript (ecma-262)the definition of 'string.raw' in that specification.
String.prototype.repeat() - JavaScript
however, you can polyfill string.prototype.repeat() with the following snippet: if (!string.prototype.repeat) { string.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new typeerror('can\'t convert ' + this + ' to object'); var str = '' + this; // to convert string to integer.
String.prototype.replaceAll() - JavaScript
specifying a string as a parameter the replacement string can include the following special replacement patterns: pattern inserts $$ inserts a "$".
String.prototype.search() - JavaScript
examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs.
String.prototype.small() - JavaScript
examples using small() the following example uses string methods to change the size of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7...
String.prototype.startsWith() - JavaScript
however, you can polyfill string.prototype.startswith() with the following snippet: if (!string.prototype.startswith) { object.defineproperty(string.prototype, 'startswith', { value: function(search, rawpos) { var pos = rawpos > 0 ?
String.prototype.strike() - JavaScript
examples using strike() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.strike' in that specific...
String.prototype.sub() - JavaScript
examples using sub() and sup() methods the following example uses the sub() and sup() methods to format a string: var supertext = 'superscript'; var subtext = 'subscript'; console.log('this is what a ' + supertext.sup() + ' looks like.'); // this is what a <sup>superscript</sup> looks like console.log('this is what a ' + subtext.sub() + ' looks like.'); // this is what a <sub>subscript</sub> looks like.
String.prototype.substr() - JavaScript
to use this feature in jscript, you can use the following code: // only run when the substr() function is broken if ('ab'.substr(-1) != 'b') { /** * get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to return * @return {string} */ string.prototype.substr = function(substr) { return function(start, length) { // call the original method...
String.prototype.sup() - JavaScript
examples using sub() and sup() methods the following example uses the sub() and sup() methods to format a string: var supertext = 'superscript'; var subtext = 'subscript'; console.log('this is what a ' + supertext.sup() + ' looks like.'); // "this is what a <sup>superscript</sup> looks like." console.log('this is what a ' + subtext.sub() + ' looks like.'); // "this is what a <sub>subscript</sub> looks like." specifications specification ecmascript (ecma-262)the definition of 'string.prototype.sup' in that specificatio...
String.prototype.toLocaleUpperCase() - JavaScript
the following can return false: x.tolocalelowercase() === x.tolocaleuppercase().tolocalelowercase() examples using tolocaleuppercase() 'alphabet'.tolocaleuppercase(); // 'alphabet' 'gesäß'.tolocaleuppercase(); // 'gesÄss' 'i\u0307'.tolocaleuppercase('lt-lt'); // 'i' let locales = ['lt', 'lt', 'lt-lt', 'lt-u-co-phonebk', 'lt-x-lietuva']; 'i\u0307'.tolocaleuppercase(locales); // 'i' specifications ...
String.prototype.toSource() - JavaScript
examples native function for the built-in string object, tosource() returns the following string indicating that the source code is not available: function string() { [native code] } for instances of string or string literals, tosource() returns a string representing the source code.
String.prototype.toString() - JavaScript
examples using tostring() the following example displays the string value of a string object: var x = new string('hello world'); console.log(x.tostring()); // logs 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tostring' in that specification.
String.prototype.trimEnd() - JavaScript
in some engines this means: string.prototype.trimright.name === "trimend"; examples using trimend() the following example displays the lowercase string ' foo': var str = ' foo '; console.log(str.length); // 8 str = str.trimend(); console.log(str.length); // 6 console.log(str); // ' foo' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.trimend' in that specification.
String.prototype.trimStart() - JavaScript
} } })(proto,'trimstart'); })(window); /* es6: (w=>{ const string=w.string, proto=string.prototype; ((o,p)=>{ if(p in o?o[p]?false:true:true){ const r=/^\s+/; o[p]=o.trimleft||function(){ return this.replace(r,'') } } })(proto,'trimstart'); })(window); */ examples using trimstart() the following example displays the lowercase string 'foo ': var str = ' foo '; console.log(str.length); // 8 str = str.trimstart(); console.log(str.length); // 5 console.log(str); // 'foo ' specifications specification ecmascript (ecma-262)the definition of ' string.prototype.trimstart' in that specification.
Symbol() constructor - JavaScript
it creates a new symbol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
Symbol.for() - JavaScript
global symbol registry the global symbol registry is a list with the following record structure and it is initialized empty: a record in the global symbol registry field name value [[key]] a string key used to identify a symbol.
Symbol.match - JavaScript
property attributes of symbol.match writable no enumerable no configurable no examples disabling the isregexp check the following code will throw a typeerror: '/bar/'.startswith(/bar/); // throws typeerror, as /bar/ is a regular expression // and symbol.match is not modified.
Symbol.matchAll - JavaScript
the following two examples return same result: 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing match behavior within regexp subclasses.
Symbol.toPrimitive - JavaScript
property attributes of symbol.toprimitive writable no enumerable no configurable no examples modifying primitive values converted from an object following example describes how symbol.toprimitive property can modify the primitive value converted from an object.
Symbol.prototype.toSource() - JavaScript
examples native function for the built-in symbol object, tosource returns the following string indicating that the source code is not available: "function symbol() { [native code] }" for instances of symbol, tosource returns a string representing the source code.
Symbol.unscopables - JavaScript
property attributes of symbol.unscopables writable no enumerable no configurable no examples scoping in with statements the following code works fine in es5 and below.
Symbol - JavaScript
it creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
TypedArray.prototype.every() - JavaScript
examples testing size of all typed array elements the following example tests whether all elements in the typed array are bigger than 10.
TypedArray.prototype.fill() - JavaScript
use the following "polyfill" along with the array.prototype.fill() polyfill.
TypedArray.prototype.filter() - JavaScript
examples filtering out all small values the following example uses filter() to create a filtered typed array that has all elements with values less than 10 removed.
TypedArray.prototype.find() - JavaScript
examples find a prime number in a typed array the following example finds an element in the typed array that is a prime number (or returns undefined if there is no prime number).
TypedArray.prototype.findIndex() - JavaScript
for (i in this) { if (evaluator(this[i], i, this)) { return i; } } return -1; } for (i in this) { if (evaluator.call(thisarg, this[i], i, this)) { return i; } } return -1; }; examples find the index of a prime number in a typed array the following example finds the index of an element in the typed array that is a prime number (or returns -1 if there is no prime number).
TypedArray.prototype.forEach() - JavaScript
examples logging the contents of a typed array the following code logs a line for each element in a typed array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element); } new uint8array([0, 1, 2, 3]).foreach(logarrayelements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.foreach' in that s...
TypedArray.prototype.some() - JavaScript
examples testing size of all typed array elements the following example tests whether any element in the typed array is bigger than 10.
TypedArray.prototype.toString() - JavaScript
for example, the following code creates a typed array and uses tostring to convert the array to a string.
TypedArray - JavaScript
on the following pages you will find common properties and methods that can be used with any typed array containing elements of any type.
WebAssembly.CompileError() constructor - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(...
WebAssembly.CompileError - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(...
WebAssembly.Global() constructor - JavaScript
examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
WebAssembly.Global - JavaScript
examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
WebAssembly.LinkError() constructor - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber...
WebAssembly.LinkError - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber...
WebAssembly.Memory.prototype.buffer - JavaScript
examples using buffer the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above.
WebAssembly.Memory.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib).
WebAssembly.Module.customSections() - JavaScript
the wast2wasm command available as part of the wabt tool has a --debug-names option — specify this during conversion to get a .wasm with a names custom section, for example: wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names examples using customsections the following example (see the custom-section.html source and live example) compiles the loaded simple-name-section.wasm byte code.
WebAssembly.Module.exports() - JavaScript
examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage().
WebAssembly.Module.imports() - JavaScript
examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module.
WebAssembly.Module - JavaScript
examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends the resulting module instance to a worker using postmessage().
WebAssembly.RuntimeError() constructor - JavaScript
examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(...
WebAssembly.RuntimeError - JavaScript
examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(...
WebAssembly.Table.prototype.get() - JavaScript
examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method.
WebAssembly.Table.prototype.set() - JavaScript
examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references.
WebAssembly.Table - JavaScript
examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
WebAssembly.compile() - JavaScript
examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage().
WebAssembly.compileStreaming() - JavaScript
examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a webassembly.module object.
WebAssembly.instantiate() - JavaScript
second overload example the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage().
WebAssembly.instantiateStreaming() - JavaScript
examples instantiating streaming the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject.
WebAssembly.validate() - JavaScript
examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array.
WebAssembly - JavaScript
examples stream a .wasm module then compile and instantiate it the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject.
escape() - JavaScript
note: this function was used mostly for url queries (the part of a url following ?)—not for escaping ordinary string literals, which use the format "\xhh".
undefined - JavaScript
in the following code, the variable x is not initialized, and the if statement evaluates to true.
Addition assignment (+=) - JavaScript
syntax operator: x += y meaning: x = x + y examples using addition assignment // assuming the following variables // foo = 'foo' // bar = 5 // baz = true // number + number -> addition bar += 2 // 7 // boolean + number -> addition baz += 1 // 2 // boolean + boolean -> addition baz += false // 1 // number + string -> concatenation bar += 'foo' // "5foo" // string + boolean -> concatenation foo += false // "foofalse" // string + string -> concatenation foo += 'bar' // "foobar" specification...
Assignment (=) - JavaScript
syntax operator: x = y examples simple assignment and chaining // assuming the following variables // x = 5 // y = 10 // z = 25 x = y // x is 10 x = y = z // x, y and z are all 25 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Bitwise AND (&) - JavaScript
for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
Bitwise NOT (~) - JavaScript
for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
Bitwise OR (|) - JavaScript
for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
Bitwise XOR (^) - JavaScript
for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
Conditional (ternary) operator - JavaScript
person.name : `stranger` return `howdy, ${name}` } console.log(greeting({name: `alice`})); // "howdy, alice" console.log(greeting(null)); // "howdy, stranger" conditional chains the ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain: function example(…) { return condition1 ?
Destructuring assignment - JavaScript
say you want the third element in the array props below, and then you want the name property in the object, you can do the following: const props = [ { id: 1, name: 'fizz'}, { id: 2, name: 'buzz'}, { id: 3, name: 'fizzbuzz'} ]; const [,, { name }] = props; console.log(name); // "fizzbuzz" the prototype chain is looked up when the object is deconstructed when deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
Division assignment (/=) - JavaScript
syntax operator: x /= y meaning: x = x / y examples using division assignment // assuming the following variable // bar = 5 bar /= 2 // 2.5 bar /= 'foo' // nan bar /= 0 // infinity specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Exponentiation assignment (**=) - JavaScript
syntax operator: x **= y meaning: x = x ** y examples using exponentiation assignment // assuming the following variable // bar = 5 bar **= 2 // 25 bar **= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Inequality (!=) - JavaScript
it is the negation of the equality operator so the following two lines will always give the same result: x != y !(x == y) for details of the comparison algorithm, see the page for the equality operator.
Logical OR assignment (||=) - JavaScript
in other words, x ||= y is equivalent to: x || (x = y); and not equivalent to the following which would always perform an assignment: x = x || y; note that this behavior is different to mathematical and bitwise assignment operators.
Multiplication assignment (*=) - JavaScript
syntax operator: x *= y meaning: x = x * y examples using multiplication assignment // assuming the following variable // bar = 5 bar *= 2 // 10 bar *= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Object initializer - JavaScript
the following code creates an object with three properties and the keys are "foo", "age" and "baz".
Operator precedence - JavaScript
table the following table is ordered from highest (21) to lowest (1) precedence.
Optional chaining (?.) - JavaScript
this is equivalent to the following, except that the temporary variable is in fact not created: let temp = obj.first; let nestedprop = ((temp === null || temp === undefined) ?
Property accessors - JavaScript
for example, the following syntax is often seen in many scripts.
Remainder assignment (%=) - JavaScript
syntax operator: x %= y meaning: x = x % y examples using remainder assignment // assuming the following variable // bar = 5 bar %= 2 // 1 bar %= 'foo' // nan bar %= 0 // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Spread syntax (...) - JavaScript
therefore, it may be unsuitable for copying multidimensional arrays, as the following example shows.
Strict inequality (!==) - JavaScript
it is the negation of the strict equality operator so the following two lines will always give the same result: x !== y !(x === y) for details of the comparison algorithm, see the page for the strict equality operator.
Subtraction assignment (-=) - JavaScript
syntax operator: x -= y meaning: x = x - y examples using subtraction assignment // assuming the following variable // bar = 5 bar -= 2 // 3 bar -= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
await - JavaScript
if the value of the expression following the await operator is not a promise, it's converted to a resolved promise.
function* expression - JavaScript
examples using function* the following example defines an unnamed generator function and assigns it to x.
Function expression - JavaScript
var foo = function() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined) examples creating an unnamed function the following example defines an unnamed function and assigns it to x.
in operator - JavaScript
examples basic usage the following examples show some uses of the in operator.
void operator - JavaScript
it should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', returns false void (2 == '2'); // void (2 == '2'), returns undefined examples immediately invoked function expressions when using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.
yield* - JavaScript
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().
class - JavaScript
examples a simple class declaration in the following example, we first define a class named polygon, then extend it to create a class named square.
const - JavaScript
my_object = {'other_key': 'value'}; // however, object keys are not protected, // so the following statement is executed without problem my_object.key = 'othervalue'; // use object.freeze() to make object immutable // the same applies to arrays const my_array = []; // it's possible to push items into the array my_array.push('a'); // ["a"] // however, assigning a new array to the variable throws an error // uncaught typeerror: assignment to constant variable.
debugger - JavaScript
syntax debugger; examples using the debugger statement the following example shows code where a debugger statement has been inserted, to invoke a debugger (if one exists) when the function is called.
for...in - JavaScript
var obj = {a: 1, b: 2, c: 3}; for (const prop in obj) { console.log(`obj.${prop} = ${obj[prop]}`); } // output: // "obj.a = 1" // "obj.b = 2" // "obj.c = 3" iterating own properties the following function illustrates the use of hasownproperty(): the inherited properties are not displayed.
function declaration - JavaScript
you can use the function before you declared it: hoisted(); // logs "foo" function hoisted() { console.log('foo'); } note that function expressions are not hoisted: nothoisted(); // typeerror: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; examples using function the following code declares a function that returns the total amount of sales, when given the number of units sold of products a, b, and c.
if...else - JavaScript
for example, do not use the following code: if (x = y) { /* do something */ } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment.
import - JavaScript
the following are some reasons why you might need to use dynamic import: when importing statically significantly slows the loading of your code and there is a low likelihood that you will need the code you are importing, or you will not need it until a later time.
let - JavaScript
function test(){ var foo = 33; if(foo) { let foo = (foo + 55); // referenceerror } } test(); this phenomenon may confuse you in a situation like the following.
Statements and declarations - JavaScript
break terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
Transitioning to strict mode - JavaScript
differences from non-strict to strict syntax errors when adding 'use strict';, the following cases will throw a syntaxerror before the script is executing: octal syntax var n = 023; with statement using delete on a variable name delete myvariable; using eval or arguments as variable or function argument name using one of the newly reserved keywords (in prevision for ecmascript 2015): implements, interface, let, package, private, protected, public, static, and yield declaring func...
JavaScript typed arrays - JavaScript
this can be done using array.from(), or using the following code where array.from() is unsupported.
dir - Web app manifests
WebManifestdir
the dir member can be set to one of the following values: auto — text direction is determined by the user agent ltr — left to right rtl — right to left the directionality-capable members are: name short_name description note: if the value is omitted or set to auto, the browser will use the unicode bidirectional algorithm to make a best guess about the text's direction.
orientation - Web app manifests
values orientation can take one of the following values: any natural landscape landscape-primary landscape-secondary portrait portrait-primary portrait-secondary examples "orientation": "portrait-primary" specification specification status comment feedback web app manifestthe definition of 'orientation' in that specification.
related_applications - Web app manifests
examples "related_applications": [ { "platform": "play", "url": "https://play.google.com/store/apps/details?id=com.example.app1", "id": "com.example.app1" }, { "platform": "itunes", "url": "https://itunes.apple.com/app/example-app1/id123456789" } ] related application values application objects may contain the following values: member description platform the platform on which the application can be found.
scope - Web app manifests
examples if the scope is relative, the manifest url is used as a base url: "scope": "/app/" the following scope limits navigation to the current site: "scope": "https://example.com/" finally, the following example limits navigation to a subdirectory of the current site: "scope": "https://example.com/subdirectory/" specification specification status comment feedback web app manifestthe definition of 'scope' in that specification.
serviceworker - Web app manifests
examples "serviceworker": { "src": "./serviceworker.js", "scope": "/app", "type": "", "update_via_cache": "none" } values service worker contain the following values (only src is required): member description src the url to download the service worker script from.
shortcuts - Web app manifests
examples the following is a list of shortcuts a calendar app might have: "shortcuts" : [ { "name": "today's agenda", "url": "/today", "description": "list of events planned for today" }, { "name": "new event", "url": "/create/event" }, { "name": "new reminder", "url": "/create/reminder" } ] specification specification status comment feedback ...
Web app manifests
members web manifests can contain the following keys.
<maction> - MathML
examples the following example uses the "toggle" actiontype: <math> <maction actiontype="toggle"> <mfrac> <mn>6</mn> <mn>8</mn> </mfrac> <mfrac> <mrow> <mn>3</mn> <mo>&sdot;</mo> <mn>2</mn> </mrow> <mrow> <mn>4</mn> <mo>&sdot;</mo> <mn>2</mn> </mrow> </mfrac> <mfrac> <mn>3</mn> <mn>4</mn> </mfrac> </maction> </math> specifications ...
<mi> - MathML
WebMathMLElementmi
the following values are allowed: normal (default value for more than one character) ; example bold ; example italic (default value for a single character) ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-ser...
<mn> - MathML
WebMathMLElementmn
the following values are allowed: normal (default value) ; example bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; م�...
<mo> - MathML
WebMathMLElementmo
the following values are allowed: normal (default value) ; example bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; م�...
<mover> - MathML
WebMathMLElementmover
use the following syntax: <mover> base overscript </mover> attributes accent if true the over-script is an accent, which is drawn closer to the base expression.
<ms> - MathML
WebMathMLElementms
the following values are allowed: normal (default value) ; example bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; م�...
<msqrt> - MathML
WebMathMLElementmsqrt
the square root accepts only one argument, which leads to the following syntax: <msqrt> base </msqrt>.
<mstyle> - MathML
WebMathMLElementmstyle
the <mstyle> element accepts all attributes of all presentation elements with the following exceptions: height, depth or width do not apply to <mglyph>, <mpadded> or <mtable>.
<msub> - MathML
WebMathMLElementmsub
it uses the following syntax: <msub> base subscript </msub>.
<msubsup> - MathML
it uses the following syntax: <msubsup> base subscript superscript </msubsup>.
<msup> - MathML
WebMathMLElementmsup
it uses the following syntax: <msup> base superscript </msup>.
<mtext> - MathML
WebMathMLElementmtext
the following values are allowed: normal (default value) ; example bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example normal (defau...
<munder> - MathML
WebMathMLElementmunder
it uses the following syntax: <munder> base underscript </munder> attributes accentunder if true, the element is an accent, which is drawn closer to the base expression.
<munderover> - MathML
it uses the following syntax: <munderover> base underscript overscript </munderover> attributes accent if true, the overscript is an accent, which is drawn closer to the base expression.
Web audio codec guide - Web media technologies
when choosing a codec to use for your audio, you should first consider the following questions: will the encoded audio be getting remixed or recompressed?
Digital audio concepts - Web media technologies
in other words, given a left channel, l, and a right channel, r, you perform the following calculations when encoding a sample: mid=l+r2mid = \frac { l + r }{ 2 } side=l-r2side = \frac { l - r }{ 2 } then you store the values of mid and side.
OpenSearch description format
if the error message isn't be helpful, the following tips could help you find the problem.
Critical rendering path - Web Performance
the greater the number of nodes, the longer the following events in the critical rendering path will take.
Performance fundamentals - Web Performance
specific coding tips for application performance the following practical tips will help improve one or more of the application performance factors discussed above.
Navigation and resource timings - Web Performance
in the above image, we see via the name property that the file being timed is this document for the rest of this explanation, we use the following variable: let timing = performance.getentriesbytype('navigation')[0]; protocol we can check the protocol used by querying: let protocol = timing.nexthopprotocol it returns the network protocol used to fetch the resource: in this case h2 for http/2.
Privacy, permissions, and information security
the following list includes features affecting both, since many of these features are used for both.
Introduction to progressive web apps - Progressive web apps (PWAs)
advantages of web applications a fully-capable progressive web application should provide all of the following advantages to the user.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
you can use the following ones:"); console.log(webpush.generatevapidkeys()); return; } webpush.setvapiddetails( 'https://serviceworke.rs/', process.env.vapid_public_key, process.env.vapid_private_key ); next, a module defines and exports all the routes an app needs to handle: getting the vapid public key, registering, and then sending notifications.
Responsive Navigation Patterns - Progressive web apps (PWAs)
the following present several ways to handle navigation on large and small screens.
Structural overview of progressive web apps - Progressive web apps (PWAs)
the first thing it does is to generate the app's displayed content using the following template: var template = "<article>\n\ <img src='data/img/slug.jpg' alt='name'>\n\ <h3>#pos.
SVG Event Attributes - SVG: Scalable Vector Graphics
WebSVGAttributeEvents
for every event type that the browser supports, svg supports that as an event attribute, following the same requirements as for html event attributes.
alignment-baseline - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following four elements: <tspan>, <tref>, <altglyph>, and <textpath> usage notes value auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | top | center | bottom default value auto animatable yes auto the value is the dominant-baseline of the script to which ...
baseline-shift - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following four elements: <altglyph>, <textpath>, <tref>, and <tspan> usage notes value <length-percentage> | sub | super default value 0 animatable yes sub the dominant-baseline is shifted to the default position for subscripts.
clip-path - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has noticeable effects mostly on the following nineteen elements: <a>, <circle>, <clippath>, <ellipse>, <g>, <glyph>, <image>, <line>, <marker>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <svg>, <symbol>, <text>, <use> html,body,svg { height:100% } <svg viewbox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"> <clippath id="myclip" clippathunits="objectboundingbox"> <circle cx=".5" cy=".5" r=".5" /> </clippath> <!-- top-left: apply a custom defined clipping path --> <rect x="1" y="1" width="8" height="8" stroke="gre...
color-interpolation-filters - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it only has an effect on the following eighteen elements: <fespotlight>, <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feconvolvematrix>, <fediffuselighting>, <fedisplacementmap>, <fedropshadow>, <feflood>, <fegaussianblur>, <feimage>, <femerge>, <femorphology>, <feoffset>, <fespecularlighting>, <fetile>, <feturbulence> usage notes value auto | srgb | linearrgb default value linearrgb ...
color-interpolation - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it only has an effect on the following 29 elements: <a>, <animate>, <animatecolor>, <circle>, <clippath>, <defs>, <ellipse>, <foreignobject>, <g>, <glyph>, <image>, <line>, <lineargradient>, <marker>, <mask>, <missing-glyph>, <path>, <pattern>, <polygon>, <polyline>, <radialgradient>, <rect>, <svg>, <switch>, <symbol>, <text>, <textpath>, <tspan>, and <use> usage notes value auto | srgb | linearrgb default value...
color-profile - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it only has an effect on the following element: <image> usage notes value auto | srgb | <name> | <iri> default value auto animatable yes auto all colors are presumed to be defined in the srgb color space unless a more precise embedded profile is specified within content data.
color-rendering - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it only has an effect on the following 29 elements: <a>, <animate>, <animatecolor>, <circle>, <clippath>, <defs>, <ellipse>, <foreignobject>, <g>, <glyph>, <image>, <line>, <lineargradient>, <marker>, <mask>, <missing-glyph>, <path>, <pattern>, <polygon>, <polyline>, <radialgradient>, <rect>, <svg>, <switch>, <symbol>, <text>, <textpath>, <tspan>, and <use> html, body, svg { height: 100%; } <svg viewbox="0 0 480 200" xmlns="htt...
cursor - SVG: Scalable Vector Graphics
WebSVGAttributecursor
elements the following elements can use the cursor attribute container elements » graphics elements » browser compatibility the compatibility table on this page is generated from structured data.
data-* - SVG: Scalable Vector Graphics
WebSVGAttributedata-*
the * can be replaced by any characters allowed in xml's rules for names, with the following restrictions: can't start with xml.
enable-background - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eleven elements: <a>, <defs>, <glyph>, <g>, <marker>, <mask>, <missing-glyph>, <pattern>, <svg>, <switch>, and <symbol> context notes value accumulate | new [ <x> <y> <width> <height> ]?
end - SVG: Scalable Vector Graphics
WebSVGAttributeend
each value can be one of the following: <offset-value> this value defines a clock-value that represents a point in time relative to the beginning of the svg document (usually the load or domcontentloaded event).
fill-opacity - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eleven elements: <altglyph>, <circle>, <ellipse>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="0 0 400 100" xmlns="http://www.w3.org/2000/svg"> <!-- default fill opacity: 1 --> <circle cx="50" cy="50" r="40" /> <!-- fill opacity as a number --> <circle cx="150" cy="50" r="40" fill-opacity="0.7" /> <!-- fill opacity as a percentage --> <circle cx="250" cy="50" r="40" ...
fill-rule - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <path>, <polygon>, <polyline>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="-10 -10 220 120" xmlns="http://www.w3.org/2000/svg"> <!-- default value for fill-rule --> <polygon fill-rule="nonzero" stroke="red" points="50,0 21,90 98,35 2,35 79,90"/> <!-- the center of the shape has two path segments (shown by the red stroke) between it and infinity.
fill - SVG: Scalable Vector Graphics
WebSVGAttributefill
as a presentation attribute, it can be applied to any element but it only has an effect on the following eleven elements: <altglyph>, <circle>, <ellipse>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan>.
flood-color - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following two elements: <feflood> and <fedropshadow> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="flood1"> <feflood flood-color="skyblue" x="0" y="0" width="200" height="200"/> </filter> <filter id="flood2"> <feflood flood-color="seagreen" x="0" y="0" width="200" height="200"/> </filter> <rect x="0" y="0" width="200" height="200" style="filter: url(#flood1);" /> <rect x="0" y="0" width="200" height="200" style="filter: url(#flood2); tran...
flood-opacity - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following two elements: <feflood> and <fedropshadow> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="flood1"> <feflood flood-color="seagreen" flood-opacity="1" x="0" y="0" width="200" height="200"/> </filter> <filter id="flood2"> <feflood flood-color="seagreen" flood-opacity="0.3" x="0" y="0" width="200" height="200"/> </filter> <rect x="0" y="0" width="200" height="200" style="filter: url(#flood1);" /> <rect x="0" y="0" width="200...
font-family - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 200 30" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-family="arial, helvetica, sans-serif">sans serif</text> <text x="100" y="20" font-family="monospace">monospace</text> </svg> usage notes value [ <family-name> | <generic-family> ]#where <famil...
font-size-adjust - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg width="600" height="80" viewbox="0 0 500 80" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-family="times, serif" font-size="10px"> this text uses the times font (10px), which is hard to read in small sizes.
font-size - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 200 30" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-size="smaller">smaller</text> <text x="100" y="20" font-size="2em">2em</text> </svg> usage notes value <absolute-size> | <relative-size> | <length-percentage> default value medium animat...
font-stretch - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> usage notes value <font-stretch-absolute>where <font-stretch-absolute> = normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | <percentage> default value normal animatable yes specifications specification status comment css ...
font-style - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but only has an effect on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 250 30" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-style="normal">normal font style</text> <text x="150" y="20" font-style="italic">italic font style</text> </svg> usage notes value normal | italic | oblique default value normal animatable yes for a description of the valu...
font-variant - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 250 30" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-variant="normal">normal text</text> <text x="100" y="20" font-variant="small-caps">small-caps text</text> </svg> usage notes value normal | none | [ <common-lig-values> || <discretionary-lig-values> || <historical-lig-values> || <contextual-a...
font-weight - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 200 30" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-weight="normal">normal text</text> <text x="100" y="20" font-weight="bold">bold text</text> </svg> usage notes value normal | bold | bolder | lighter | <number> default value normal animatab...
glyph-orientation-horizontal - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <textpath>, <text>, <tref>, and <tspan> context notes value <angle> default value 0deg animatable no <angle> the value of the angle is restricted to 0, 90, 180, and 270 degrees.
glyph-orientation-vertical - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <textpath>, <text>, <tref>, and <tspan> context notes value auto | <angle> default value auto animatable no auto fullwidth ideographic and fullwidth latin text will be set with a glyph orientation of 0 degrees.
image-rendering - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following element: <image> usage notes value auto | optimizespeed | optimizequality default value auto animatable yes auto indicates that the user agent shall make appropriate tradeoffs to balance speed and quality, but quality shall be given more importance than speed.
k1 - SVG: Scalable Vector Graphics
WebSVGAttributek1
the pixel composition is computed using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 only one element is using this attribute: <fecomposite> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="composite1" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="1" k2="0" k3="0" k4="0" /> </filter> <filter id="composite2" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="10" k2="0" k3="0" k4="0" /> </filter> <image href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0"...
k2 - SVG: Scalable Vector Graphics
WebSVGAttributek2
the pixel composition is computed using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 only one element is using this attribute: <fecomposite> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="composite1" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="1" k2="1" k3="0" k4="0" /> </filter> <filter id="composite2" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="1" k2="10" k3="0" k4="0" /> </filter> <image href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0"...
k3 - SVG: Scalable Vector Graphics
WebSVGAttributek3
the pixel composition is computed using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 only one element is using this attribute: <fecomposite> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="composite1" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="1" k2="0" k3="1" k4="0" /> </filter> <filter id="composite2" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="1" k2="0" k3="10" k4="0" /> </filter> <image href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0"...
k4 - SVG: Scalable Vector Graphics
WebSVGAttributek4
the pixel composition is computed using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 only one element is using this attribute: <fecomposite> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="composite1" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="1" k2="0" k3="0" k4="0" /> </filter> <filter id="composite2" x="0" y="0" width="100%" height="100%"> <fecomposite in2="sourcegraphic" operator="arithmetic" k1="10" k2="0" k3="0" k4="0.3" /> </filter> <image href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="...
kerning - SVG: Scalable Vector Graphics
WebSVGAttributekerning
as a presentation attribute, it can be applied to any element but it has effect only on the following four elements: <altglyph>, <textpath>, <text>, <tref>, and <tspan> html, body, svg { height: 100%; font: 36px verdana, helvetica, arial, sans-serif; } <svg viewbox="0 0 150 125" xmlns="http://www.w3.org/2000/svg"> <text x="10" y="30" kerning="auto">auto</text> <text x="10" y="70" kerning="0">number</text> <text x="10" y="110" kerning="20px">length</text> </svg> usage notes ...
lang - SVG: Scalable Vector Graphics
WebSVGAttributelang
the glyph was meant to be used if the xml:lang attribute exactly matched one of the languages given in the value of this parameter, or if the xml:lang attribute exactly equaled a prefix of one of the languages given in the value of this parameter such that the first tag character following the prefix was "-".
letter-spacing - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 400 30" xmlns="http://www.w3.org/2000/svg"> <text y="20" letter-spacing="2">bigger letter-spacing</text> <text x="200" y="20" letter-spacing="-0.5">smaller letter-spacing</text> </svg> usage notes value normal | <length> default value norm...
marker-end - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following seven elements: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <defs> <marker id="triangle" viewbox="0 0 10 10" refx="1" refy="5" markerunits="strokewidth" markerwidth="10" markerheight="10" orient="auto"> <path d="m 0...
marker-mid - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following seven elements: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <defs> <marker id="circle" markerwidth="8" markerheight="8" refx="4" refy="4"> <circle cx="4" cy="4" r="4" stroke="none" fill="#f00"/> </marker> </defs> <polyline fill="none" stroke="black" ...
marker-start - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following seven elements: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <defs> <marker id="triangle" viewbox="0 0 10 10" refx="1" refy="5" markerunits="strokewidth" markerwidth="10" markerheight="10" orient="auto"> <path d="m 0...
mask - SVG: Scalable Vector Graphics
WebSVGAttributemask
as a presentation attribute, it can be applied to any element but it has noticeable effects mostly on the following nineteen elements: <a>, <circle>, <clippath>, <ellipse>, <g>, <glyph>, <image>, <line>, <marker>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <svg>, <symbol>, <text>, <use> usage notes value see the css property mask default value none animatable yes specifications specification status comment css masking modu...
opacity - SVG: Scalable Vector Graphics
WebSVGAttributeopacity
as a presentation attribute, it can be applied to any element but it has effect only on the following elements: <a>, <audio>, <canvas>, <circle>, <ellipse>, <foreignobject>, <g>, <iframe>, <image>, <line>, <marker>, <path>, <polygon>, <polyline>, <rect>, <svg>, <switch>, <symbol>, <text>, <textpath>, <tspan>, <use>, <unknown>, and <video> html, body, svg { height: 100%; } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <defs> <lineargradient id="gradient" x1="0%" y1="0%" x2="0" y2="10...
operator - SVG: Scalable Vector Graphics
arithmetic this value indicates that the source graphic defined in the in attribute and the destination graphic defined in the in2 attribute are combined using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 where: i1 and i2 indicate the corresponding pixel channel values of the input image, which map to in and in2 respectively, and k1,k2,k3,and k4 indicate the values of the attributes with the same name.
overline-position - SVG: Scalable Vector Graphics
usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the overline-position attribute: <font-face> ...
overline-thickness - SVG: Scalable Vector Graphics
usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the overline-thickness attribute: <font-face> ...
pointer-events - SVG: Scalable Vector Graphics
or between #000000 and #ffffff const color = math.round(math.random() * 0xffffff) // let's format the color to fit css requirements const fill = '#' + color.tostring(16).padstart(6,'0') // let's apply our color in the // element we actually clicked on e.target.style.fill = fill }) as a presentation attribute, it can be applied to any element but it is mostly relevant only on the following twenty-three elements: <a>, <circle>, <clippath>, <defs>, <ellipse>, <foreignobject>, <g>, <image>, <line>, <marker>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <svg>, <switch>, <symbol>, <text>, <textpath>, <tspan>, <use> usage notes value bounding-box | visiblepainted | visiblefill | visiblestroke | visible | painted | fill | stroke | all | none default val...
shape-rendering - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following seven elements: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <circle cx="100" cy="100" r="100" shape-rendering="geometricprecision"/> <circle cx="320" cy="100" r="100" shape-rendering="crispedges"/> </svg> usage notes value auto | optimizespeed | crispedges | geometricprecision default value auto anim...
stop-color - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following element: <stop> usage notes value currentcolor | <color> <icccolor> default value black animatable yes currentcolor this keyword denotes the current fill color and can be specified in the same manner as within a <paint> specification for the fill and stroke attributes.
stop-opacity - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following element: <stop> usage notes value <opacity-value> default value 1 animatable yes <opacity-value> this value is either a <number> between 0 and 1 or a <percentage> value specifying the opacity of the color gradient stop.
strikethrough-position - SVG: Scalable Vector Graphics
usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the strikethrough-position attribute: <font-face> ...
strikethrough-thickness - SVG: Scalable Vector Graphics
usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the strikethrough-thickness attribute: <font-face> ...
stroke-dasharray - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element, but it only has effect on the following twelve elements: <altglyph> <circle> <ellipse> <path> <line> <polygon> <polyline> <rect> <text> <textpath> <tref> <tspan> html,body,svg { height:100% } <svg viewbox="0 0 30 10" xmlns="http://www.w3.org/2000/svg"> <!-- no dashes nor gaps --> <line x1="0" y1="1" x2="30" y2="1" stroke="black" /> <!-- dashes and gaps of the same size --> <line x1="0" y1="3" x2="30" y2="3" stroke="black" stroke-dasharray="4" /> <!-- dashes and gaps of d...
stroke-opacity - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following twelve elements: <altglyph>, <circle>, <ellipse>, <path>, <line>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="0 0 40 10" xmlns="http://www.w3.org/2000/svg"> <!-- default stroke opacity: 1 --> <circle cx="5" cy="5" r="4" stroke="green" /> <!-- stroke opacity as a number --> <circle cx="15" cy="5" r="4" stroke="green" stroke-opacity="0.7" /> <!-- stroke opacity ...
stroke - SVG: Scalable Vector Graphics
WebSVGAttributestroke
as a presentation attribute, it can be applied to any element but it has effect only on the following twelve elements: <altglyph>, <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="0 0 20 10" xmlns="http://www.w3.org/2000/svg"> <!-- simple color stroke --> <circle cx="5" cy="5" r="4" fill="none" stroke="green" /> <!-- stroke a circle with a gradient --> <defs> <lineargradient id="mygradient"> <stop offset="0%" stop-color="green" ...
text-anchor - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <!-- materialisation of anchors --> <path d="m60,15 l60,110 m30,40 l90,40 m30,75 l90,75 m30,110 l90,110" stroke="grey" /> <!-- anchors in action --> <text text-anchor="start" x="60" y="40">a</text> <text text-anchor="...
text-decoration - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 250 50" xmlns="http://www.w3.org/2000/svg"> <text y="20" text-decoration="underline">underlined text</text> <text x="0" y="40" text-decoration="line-through">struck-through text</text> </svg> usage notes value <'text-decoration-line'> || <'text-decorat...
text-rendering - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following element: <text> html, body, svg { height: 100%; } <svg viewbox="0 0 140 40" xmlns="http://www.w3.org/2000/svg"> <text y="15" text-rendering="geometricprecision">geometric precision</text> <text y="35" text-rendering="optimizelegibility">optimized legibility</text> </svg> usage notes value auto | optimizespeed | optimizelegibility | geometricprecision default value auto animatable yes auto t...
type - SVG: Scalable Vector Graphics
WebSVGAttributetype
tegories none value fractalnoise | turbulence animatable yes normative document svg 1.1 (2nd edition) for the <style> and <script> elements categories none value <content-type> animatable no normative document svg 1.1 (2nd edition) : script svg 1.1 (2nd edition) : style example elements the following elements can use the values attribute <animatetransform> <fecolormatrix> <fefunca> <fefuncb> <fefuncg> <fefuncr> <feturbulence> <script> <style> ...
underline-position - SVG: Scalable Vector Graphics
usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the underline-position attribute: <font-face> ...
underline-thickness - SVG: Scalable Vector Graphics
usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the underline-thickness attribute: <font-face> ...
unicode-bidi - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eleven elements: <altglyph>, <textpath>, <text>, <tref>, and <tspan> context notes value normal | embed | isolate | bidi-override | isolate-override | plaintext default value normal animatable no for a description of the values, please refer to the css unicode-bidi property.
vector-effect - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following ten elements: <circle>, <ellipse>, <foreignobject>, <image>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath> <tspan>, and <use> usage notes value none | non-scaling-stroke | non-scaling-size | non-rotation | fixed-position default value none animatable yes none this value specifies that no vector effect shall be applied, i.e.
word-spacing - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 250 50" xmlns="http://www.w3.org/2000/svg"> <text y="20" word-spacing="2">bigger spacing between words</text> <text x="0" y="40" word-spacing="-0.5">smaller spacing between words</text> </svg> usage notes value normal | <length> animatable ...
writing-mode - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> usage notes default value horizontal-tb value horizontal-tb | vertical-rl | vertical-lr animatable yes horizontal-tb this value defines a top-to-bottom block flow direction.
Compatibility sources - SVG: Scalable Vector Graphics
the following sources are used for the compatibility tables on svg elements and attributes: https://developer.mozilla.org/en/svg_in_firefox together with its revision history for firefox http://www.webkit.org/projects/svg/status.xml together with its recorded archive for webkit, safari and chrome http://www.opera.com/docs/specs/opera9/svg/ and accompanying pages for opera >= 9, http://www.opera.com/docs/specs/opera8/ for opera 8 http://blogs.msdn.com/b/ie/archive/2010/03/18/svg-in-ie9-roadmap.aspx for hints on ie9 support status the svg support charts at codedread.com for basic checks against the w3c test suite wikipedia for basic hints, not normative ...
<a> - SVG: Scalable Vector Graphics
WebSVGElementa
tiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphics ...
<animateColor> - SVG: Scalable Vector Graphics
usage context categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes conditional processing attributes core attributes animation event attributes xlink attributes animation attribute target attributes animation timing attributes animation value attributes animation addition attributes externalresourcesrequired specific attributes by from to dom interface this element im...
<animateMotion> - SVG: Scalable Vector Graphics
200 100" xmlns="http://www.w3.org/2000/svg"> <path fill="none" stroke="lightgrey" d="m20,50 c20,-50 180,150 180,50 c180-50 20,150 20,50 z" /> <circle r="5" fill="red"> <animatemotion dur="10s" repeatcount="indefinite" path="m20,50 c20,-50 180,150 180,50 c180-50 20,150 20,50 z" /> </circle> </svg> usage context categoriesanimation elementpermitted contentany number of the following elements, in any order:descriptive elements<mpath> attributes keypoints this attribute indicate, in the range [0,1], how far is the object along the path for each keytimes associated values.
<animateTransform> - SVG: Scalable Vector Graphics
usage context categoriesanimation elementpermitted contentany number of the following elements, in any order:descriptive elements example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <polygon points="60,30 90,90 30,90"> <animatetransform attributename="transform" attributetype="xml" type="rotate" from="0 60 70" to="360 60 70" dur="10s" repeatcount="indefinite"/> </polygon> </svg> live sample attribute...
<circle> - SVG: Scalable Vector Graphics
WebSVGElementcircle
orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition of '<circle>' in that specification.
<clipPath> - SVG: Scalable Vector Graphics
WebSVGElementclipPath
nsions, systemlanguage presentation attributes most notably: clip-path, clip-rule, color, display, fill, fill-opacity, fill-rule, filter, mask, opacity, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriesnonepermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elements<text>, <use> specifications specification status comment css masking module level 1the definition of '<clippath>' in that specification.
<color-profile> - SVG: Scalable Vector Graphics
usage context categoriesnonepermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes core attributes » xlink attributes » specific attributes local name rendering-intent xlink:href dom interface this element implements the svgcolorprofileelement interface.
<cursor> - SVG: Scalable Vector Graphics
WebSVGElementcursor
usage context categoriesnonepermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes conditional processing attributes core attributes xlink attributes externalresourcesrequired specific attributes x y xlink:href dom interface this element implements the svgcursorelement interface.
<defs> - SVG: Scalable Vector Graphics
WebSVGElementdefs
or-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphics ...
<discard> - SVG: Scalable Vector Graphics
WebSVGElementdiscard
usage context categoriesanimation elementpermitted contentany number of the following elements, in any order:descriptive elements<script> attributes global attributes conditional processing attributes core attributes aria attributes specific attributes begin href (but note that <discard> has never supported xlink:href) specifications specification status comment svg animations level 2the definition of '<discard>' in that specification.
<ellipse> - SVG: Scalable Vector Graphics
WebSVGElementellipse
orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition of '<ellipse>' in that specification.
<feBlend> - SVG: Scalable Vector Graphics
WebSVGElementfeBlend
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in in2 mode dom interface this element implements the svgfeblendelement interface.
<feColorMatrix> - SVG: Scalable Vector Graphics
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in type values dom interface this element implements the svgfecolormatrixelement interface.
<feComponentTransfer> - SVG: Scalable Vector Graphics
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<fefunca>, <fefuncr>, <fefuncb>, <fefuncg> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in dom interface this element implements the svgfecomponenttransferelement interface.
<feComposite> - SVG: Scalable Vector Graphics
if the arithmetic operation is chosen, each result pixel is computed using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 where: i1 and i2 indicate the corresponding pixel channel values of the input image, which map to in and in2 respectively k1, k2, k3 and k4 indicate the values of the attributes with the same name usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes...
<feConvolveMatrix> - SVG: Scalable Vector Graphics
st case (where the input image's pixel grid aligns perfectly with the kernel's pixel grid) and assuming default values for attributes ‘divisor’, ‘targetx’ and ‘targety’, then resulting color value will be: (9* 0 + 8* 20 + 7* 40 + 6*100 + 5*120 + 4*140 + 3*200 + 2*220 + 1*240) / (9+8+7+6+5+4+3+2+1) usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in order kernelmatrix divisor bias targetx targety edgemode kernelunitlength preservealpha dom interface this element implements the svgfeconvolvematrixelement interface.
<feDiffuseLighting> - SVG: Scalable Vector Graphics
example the following example show the effect of the <fediffuselighting> element on a circle with each light source available.
<feDisplacementMap> - SVG: Scalable Vector Graphics
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in in2 scale xchannelselector ychannelselector dom interface this element implements the svgfedisplacementmapelement interface.
<feDistantLight> - SVG: Scalable Vector Graphics
usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes azimuth elevation dom interface this element implements the svgfedistantlightelement interface.
<feDropShadow> - SVG: Scalable Vector Graphics
value type: <number>; default value: 2; animatable: yes global attributes core attributes most notably: id styling attributes class, style filter primitive attributes height, in, result, x, y, width presentation attributes most notably: flood-color, flood-opacity usage notes categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <script>, <set> specifications specification status comment filter effects module level 1the definition of '<fedropshadow>' in that specification.
<feFlood> - SVG: Scalable Vector Graphics
WebSVGElementfeFlood
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <animatecolor>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes flood-color flood-opacity dom interface this element implements the svgfefloodelement interface.
<feFuncA> - SVG: Scalable Vector Graphics
WebSVGElementfeFuncA
usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncaelement interface.
<feFuncB> - SVG: Scalable Vector Graphics
WebSVGElementfeFuncB
usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncbelement interface.
<feFuncG> - SVG: Scalable Vector Graphics
WebSVGElementfeFuncG
usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncgelement interface.
<feFuncR> - SVG: Scalable Vector Graphics
WebSVGElementfeFuncR
usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncrelement interface.
<feGaussianBlur> - SVG: Scalable Vector Graphics
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in stddeviation edgemode dom interface this element implements the svgfegaussianblurelement interface.
<feImage> - SVG: Scalable Vector Graphics
WebSVGElementfeImage
the <feimage> svg filter primitive fetches image data from an external source and provides the pixel data as output (meaning if the external source is an svg image, it is rasterized.) usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <animatetransform>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes xlink attributes class style externalresourcesrequired specific attributes preserveaspectratio xlink:href dom interface this element implements the svgfeimageelement interface.
<feMerge> - SVG: Scalable Vector Graphics
WebSVGElementfeMerge
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<femergenode> example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <filter id="feoffset" x="-40" y="-20" width="100" height="200"> <feoffset in="sourcegraphic" dx="60" dy="60" /> <fegaussianblur stddeviation="5" result="blur2" /> <femerge> <femergenode in="blur2" /> <femergenode in="sourcegraphic" /> </femerge> </filter> <rect x="40" y="40" width="100" height="100" style="stroke: #000000; ...
<feMergeNode> - SVG: Scalable Vector Graphics
usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> example <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <filter id="feoffset" x="-40" y="-20" width="100" height="200"> <feoffset in="sourcegraphic" dx="60" dy="60" /> <fegaussianblur in="sourcegraphic" stddeviation="5" result="blur2" /> <femerge> <femergenode in="blur2" /> <femergenode in="sourcegraphic" /> </femerge> </filter> <rect x="40" y="40" width="100" height="100" style="stroke: #000000; fill: green; filter: url(#feoffset);" /> <rect ...
<feMorphology> - SVG: Scalable Vector Graphics
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in operator radius dom interface this element implements the svgfemorphologyelement interface.
<feOffset> - SVG: Scalable Vector Graphics
WebSVGElementfeOffset
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in dx dy dom interface this element implements the svgfeoffsetelement interface.
<fePointLight> - SVG: Scalable Vector Graphics
usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes x y z dom interface this element implements the svgfepointlightelement interface.
<feSpotLight> - SVG: Scalable Vector Graphics
usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes x y z pointsatx pointsaty pointsatz specularexponent limitingconeangle dom interface this element implements the svgfespotlightelement interface.
<feTile> - SVG: Scalable Vector Graphics
WebSVGElementfeTile
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in dom interface this element implements the svgfetileelement interface.
<feTurbulence> - SVG: Scalable Vector Graphics
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes basefrequency numoctaves seed stitchtiles type dom interface this element implements the svgfeturbulenceelement interface.
<filter> - SVG: Scalable Vector Graphics
WebSVGElementfilter
usage context categoriesnonepermitted contentany number of the following elements, in any order:descriptive elementsfilter primitive elements<animate>, <set> attributes global attributes core attributes presentation attributes xlink attributes class style externalresourcesrequired specific attributes x y width height filterres filterunits primitiveunits xlink:href dom interface this element implements the svgfilterelement interface.
<font-face-src> - SVG: Scalable Vector Graphics
usage context categoriesfont elementpermitted contentone or more of the following elements, in any order:<font-face-name>, <font-face-uri> attributes global attributes core attributes specific attributes none dom interface this element implements the svgfontfacesrcelement interface.
<font-face-uri> - SVG: Scalable Vector Graphics
usage context categoriesfont elementpermitted contentany number of the following elements, in any order:<font-face-format> attributes global attributes core attributes xlink attributes specific attributes xlink:href dom interface this element implements the svgfontfaceurielement interface.
<font> - SVG: Scalable Vector Graphics
WebSVGElementfont
usage context categoriesfont elementpermitted contentany number of the following elements, in any order:descriptive elements<font-face>, <glyph>, <hkern>, <missing-glyph>, <vkern> attributes global attributes core attributes presentation attributes class style externalresourcesrequired specific attributes horiz-origin-x horiz-origin-y horiz-adv-x vert-origin-x vert-origin-y vert-adv-y dom interface this element implements the svgfontelement interface.
<g> - SVG: Scalable Vector Graphics
WebSVGElementg
lectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphics ...
<glyph> - SVG: Scalable Vector Graphics
WebSVGElementglyph
usage context categoriestext content elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> attributes global attributes core attributes presentation attributes class style specific attributes d horiz-adv-x vert-origin-x vert-origin-y vert-adv-y unicode glyph-name orientation arabic-form lang dom interface this element implements the svgglyphelement interface.
<hatch> - SVG: Scalable Vector Graphics
WebSVGElementhatch
usage context categoriesnever-rendered element, paint server elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements<hatchpath>, <script>, <style> attributes global attributes core attributes global event attributes presentation attributes style attributes specific attributes x y pitch rotate hatchunits hatchcontentunits transform href dom interface this element implements the svghatchelement interface.
<hatchpath> - SVG: Scalable Vector Graphics
WebSVGElementhatchpath
usage context categoriesnonepermitted contentany number of the following elements, in any order:animation elementsdescriptive elements<script>, <style> attributes global attributes core attributes global event attributes presentation attributes style attributes specific attributes d offset dom interface this element implements the svghatchpathelement interface.
<image> - SVG: Scalable Vector Graphics
WebSVGElementimage
usage context categoriesgraphics element, graphics referencing elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements attributes global attributes conditional processing attributes core attributes graphical event attributes presentation attributes xlink attributes class style externalresourcesrequired transform specific attributes x: positions the image horizontally from the origin.
<line> - SVG: Scalable Vector Graphics
WebSVGElementline
orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition of '<line>' in that specification.
<linearGradient> - SVG: Scalable Vector Graphics
r-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes xlink:href, xlink:title usage notes categoriesgradient elementpermitted contentany number of the following elements, in any order:descriptive elements<animate>, <animatetransform>, <set>, <stop> specifications specification status comment scalable vector graphics (svg) 2the definition of '<lineargradient>' in that specification.
<marker> - SVG: Scalable Vector Graphics
WebSVGElementmarker
tiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment svg markersthe definition...
<mask> - SVG: Scalable Vector Graphics
WebSVGElementmask
mlanguage presentation attributes most notably: clip-path, clip-rule, color, display, fill, fill-opacity, fill-rule, filter, mask, opacity, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment css masking module level ...
<missing-glyph> - SVG: Scalable Vector Graphics
usage context categoriesnonepermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> attributes global attributes core attributes presentation attributes class style specific attributes d horiz-adv-x vert-origin-x vert-origin-y vert-adv-y dom interface this element implements the svgmissingglyphelement interface.
<mpath> - SVG: Scalable Vector Graphics
WebSVGElementmpath
usage context categoriesanimation elementpermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes core attributes » xlink attributes » externalresourcesrequired specific attributes xlink:href dom interface this element implements the svgmpathelement interface.
<path> - SVG: Scalable Vector Graphics
WebSVGElementpath
ultiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesgraphics element, shape elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment svg pathsthe definition of '<path>' in that specification.
<pattern> - SVG: Scalable Vector Graphics
WebSVGElementpattern
endering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes most notably: xlink:title usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphics ...
<polygon> - SVG: Scalable Vector Graphics
WebSVGElementpolygon
orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition of '<polygon>' in that specification.
<polyline> - SVG: Scalable Vector Graphics
WebSVGElementpolyline
orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition of '<polyline>' in that specification.
<radialGradient> - SVG: Scalable Vector Graphics
r-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes xlink:href, xlink:title usage notes categoriesgradient elementpermitted contentany number of the following elements, in any order:descriptive elements<animate>, <animatetransform>, <set>, <stop> specifications specification status comment scalable vector graphics (svg) 2the definition of '<radialgradient>' in that specification.
<rect> - SVG: Scalable Vector Graphics
WebSVGElementrect
orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition of '<rect>' in that specification.
<set> - SVG: Scalable Vector Graphics
WebSVGElementset
repeatcount, repeatdur, fill other animation attributes most notably: attributename animation event attributes most notably: onbegin, onend, onrepeat global attributes core attributes most notably: id styling attributes class, style event attributes global event attributes, document element event attributes usage notes categoriesanimation elementpermitted contentany number of the following elements, in any order:descriptive elements specifications specification status comment svg animations level 2the definition of '<set>' in that specification.
<stop> - SVG: Scalable Vector Graphics
WebSVGElementstop
value type: <opacity>; default value: 1; animatable: yes global attributes core attributes most notably: id styling attributes class, style event attributes global event attributes, document element event attributes presentation attributes most notably: color, display, stop-color, stop-opacity, visibility usage notes categoriesgradient elementpermitted contentany number of the following elements, in any order:<animate>, <animatecolor>, <set> specifications specification status comment scalable vector graphics (svg) 2the definition of '<stop>' in that specification.
<svg> - SVG: Scalable Vector Graphics
WebSVGElementsvg
lectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphics ...
<switch> - SVG: Scalable Vector Graphics
WebSVGElementswitch
usage context categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elements<a>, <foreignobject>, <g>, <image>, <svg>, <switch>, <text>, <use> attributes global attributes conditional processing attributes core attributes graphical event attributes presentation attributes class style externalresourcesrequired transform dom interface this element implements the svgswitchelement inter...
<symbol> - SVG: Scalable Vector Graphics
WebSVGElementsymbol
lectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> note: a <symbol> element itself is not meant to be rendered.
<text> - SVG: Scalable Vector Graphics
WebSVGElementtext
tation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesgraphics element, text content elementpermitted contentcharacter data and any number of the following elements, in any order:animation elementsdescriptive elementstext content elements<a> specifications specification status comment scalable vector graphics (svg) 2the definition of '<text>' in that specification.
<textPath> - SVG: Scalable Vector Graphics
WebSVGElementtextPath
-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role xlink attributes xlink:title usage notes categoriestext content element, text content child elementpermitted contentcharacter data and any number of the following elements, in any order:descriptive elements<a>, <altglyph>, <animate>, <animatecolor>, <set>, <tref>, <tspan> specifications specification status comment scalable vector graphics (svg) 2the definition of '<textpath>' in that specification.
<tref> - SVG: Scalable Vector Graphics
WebSVGElementtref
usage context categoriestext content element, text content child elementpermitted contentany number of the following elements, in any order:descriptive elements<animate>, <animatecolor>, <set> attributes global attributes conditional processing attributes core attributes graphical event attributes presentation attributes xlink attributes class style externalresourcesrequired specific attributes xlink:href dom interface this element implements the svgtrefelement interface.
<tspan> - SVG: Scalable Vector Graphics
WebSVGElementtspan
ia-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriestext content element, text content child elementpermitted contentcharacter data and any number of the following elements, in any order:descriptive elements<a>, <altglyph>, <animate>, <animatecolor>, <set>, <tref>, <tspan> specifications specification status comment scalable vector graphics (svg) 2the definition of '<tspan>' in that specification.
<use> - SVG: Scalable Vector Graphics
WebSVGElementuse
ria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role xlink attributes xlink:href, xlink:title usage notes categoriesgraphics element, graphics referencing element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition of '<use>' in that specification.
<view> - SVG: Scalable Vector Graphics
WebSVGElementview
usage context categoriesnonepermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes aria attributes » core attributes » global event attributes » externalresourcesrequired specific attributes viewbox preserveaspectratio zoomandpan viewtarget example svg <svg width="600" height="200" viewbox="0 0 600 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <radialgradient id="gradient"> <stop offset="0%" stop-color="#8cffa0" /> <stop offset="100%" stop-color="#8ca0ff" /> </radialgradient> </defs> <circle r="50" cx="180" cy="50" style="fill:url(#gradient)"/> <view i...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
1920) css transforms on outermost <svg> not affecting svgsvgelement.currentscale or svgsvgelement.currenttranslate implementation status unknown rootelement attribute deprecated implementation status unknown svgelementinstance and svgelementinstancelist and corresponding attributes on svguseelement removed implementation status unknown <use> event flow following shadow dom spec.
Basic Transformations - SVG: Scalable Vector Graphics
an example: <svg width="30" height="10"> <g fill="red"> <rect x="0" y="0" width="10" height="10" /> <rect x="20" y="0" width="10" height="10" /> </g> </svg> all following transformations are summed up in an element's transform attribute.
Clipping and masking - SVG: Scalable Vector Graphics
but when you try to create a semicircle in svg, you will find out the use of the following properties quickly.
Paths - SVG: Scalable Vector Graphics
WebSVGTutorialPaths
for example: m x y (or) m dx dy in the following example there's only a point at (10,10).
SVG Tutorial - SVG: Scalable Vector Graphics
WebSVGTutorial
introducing svg from scratch introduction getting started positions basic shapes paths fills and strokes gradients patterns texts basic transformations clipping and masking other content in svg filter effects svg fonts svg image tag tools for svg svg and css the following topics are more advanced and hence should get their own tutorials.
Securing your site - Web security
note: this article is a work in progress, and is neither complete nor does following its suggestions guarantee your site will be fully secure.
Transport Layer Security - Web security
to assist you in configuring your site, mozilla provides a helpful tls configuration generator that will generate configuration files for the following web servers: apache nginx lighttpd haproxy amazon web services cloudformation elastic load balancer using the configurator is a recommended way to create the configuration to meet your needs; then copy and paste it into the appropriate file on your server and restart the server to pick up the changes.
Using custom elements - Web Components
class customelement extends htmlelement { constructor(...args) { const self = super(...args); // self functionality written in here // self.addeventlistener(...) // return the right context return self; } } if you don't need to perform any operation in the constructor, you can simply omit it so that its native behavior (see following) will be preserved.
XML introduction - XML: Extensible Markup Language
comments <!-- comment --> "correct" xml (valid and well-formed) Сorrect design rules for an xml document to be correct, the following conditions must be fulfilled: document must be well-formed.
Comparison of CSS Selectors and XPath - XPath
xpath feature css equivalent ancestor, parent or preceding-sibling axis :has() selector attribute axis attribute selectors child axis child combinator descendant axis descendant combinator following-sibling axis general sibling combinator or adjacent sibling combinator self axis :scope or :host selector ...
Functions - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the following is an annotated list of core xpath functions and xslt-specific additions to xpath, including a description, syntax, a list of arguments, result-type, source in the appropriate w3c recommendation, and degree of present gecko support.
XSLT elements reference - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElement
for example, assume that a variable "image-dir" is defined as follows: <xsl:variable name="image-dir">/images</xsl:variable> the expression to be evaluated is placed inside curly brackets: <img src="{$image-dir}/mygraphic.jpg"/> this would result in the following: <img src="/images/mygraphic.jpg"/> the element annotations that follow include a description, a syntax listing, a list of required and optional attributes, a description of type and position, its source in the w3c recommendation and an explanation of the degree of present gecko support.
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
sl:processing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported) xsl:with-param (supported) axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self functions boolean() (supported) ceiling() (supported) concat() (supported) contains() (supported) count() (supported) current() (supported) document() (supported) element-available() (supported) false() (supported) floor() (supported) format-number() (supported) function-available() (supporte...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
resources the following reflect the interface of the xsltprocessor object: nsixsltprocessor.idl xsltprocessor.webidl using xsltprocessor from xpcom components instantiating an xsltprocessor from an xpcom component requires a different syntax as the constructor is not defined inside components.
Caching compiled WebAssembly modules - WebAssembly
errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(fetch(url)).then(results => { return results.instance }); }); } caching a wasm module with the above library function defined, getting a wasm module instance and using its exported features (while handling caching in the background) is as simple as calling it with the following parameters: a cache version, which — as we explained above — you need to update when any wasm module is updated or moved to a different url.
WebAssembly Concepts - WebAssembly
webassembly goals webassembly is being created as an open standard inside the w3c webassembly community group with the following goals: be fast, efficient, and portable — webassembly code can be executed at near-native speed across different platforms by taking advantage of common hardware capabilities.
Exported WebAssembly functions - WebAssembly
if you load the above example in a webassembly-supporting browser, and run the following lines in your console: var testfunc = othertable.get(0); typeof testfunc; you'll get the result function returned.
Loading and running WebAssembly code - WebAssembly
the following sections explain.